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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
13,300
|
apache/groovy
|
subprojects/groovy-dateutil/src/main/java/org/apache/groovy/dateutil/extensions/DateUtilExtensions.java
|
DateUtilExtensions.minus
|
public static java.sql.Date minus(java.sql.Date self, int days) {
return new java.sql.Date(minus((Date) self, days).getTime());
}
|
java
|
public static java.sql.Date minus(java.sql.Date self, int days) {
return new java.sql.Date(minus((Date) self, days).getTime());
}
|
[
"public",
"static",
"java",
".",
"sql",
".",
"Date",
"minus",
"(",
"java",
".",
"sql",
".",
"Date",
"self",
",",
"int",
"days",
")",
"{",
"return",
"new",
"java",
".",
"sql",
".",
"Date",
"(",
"minus",
"(",
"(",
"Date",
")",
"self",
",",
"days",
")",
".",
"getTime",
"(",
")",
")",
";",
"}"
] |
Subtract a number of days from this date and returns the new date.
@param self a java.sql.Date
@param days the number of days to subtract
@return the new date
@since 1.0
|
[
"Subtract",
"a",
"number",
"of",
"days",
"from",
"this",
"date",
"and",
"returns",
"the",
"new",
"date",
"."
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-dateutil/src/main/java/org/apache/groovy/dateutil/extensions/DateUtilExtensions.java#L432-L434
|
13,301
|
apache/groovy
|
subprojects/groovy-dateutil/src/main/java/org/apache/groovy/dateutil/extensions/DateUtilExtensions.java
|
DateUtilExtensions.upto
|
public static void upto(Date self, Date to, Closure closure) {
if (self.compareTo(to) <= 0) {
for (Date i = (Date) self.clone(); i.compareTo(to) <= 0; i = next(i)) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("The argument (" + to +
") to upto() cannot be earlier than the value (" + self + ") it's called on.");
}
|
java
|
public static void upto(Date self, Date to, Closure closure) {
if (self.compareTo(to) <= 0) {
for (Date i = (Date) self.clone(); i.compareTo(to) <= 0; i = next(i)) {
closure.call(i);
}
} else
throw new GroovyRuntimeException("The argument (" + to +
") to upto() cannot be earlier than the value (" + self + ") it's called on.");
}
|
[
"public",
"static",
"void",
"upto",
"(",
"Date",
"self",
",",
"Date",
"to",
",",
"Closure",
"closure",
")",
"{",
"if",
"(",
"self",
".",
"compareTo",
"(",
"to",
")",
"<=",
"0",
")",
"{",
"for",
"(",
"Date",
"i",
"=",
"(",
"Date",
")",
"self",
".",
"clone",
"(",
")",
";",
"i",
".",
"compareTo",
"(",
"to",
")",
"<=",
"0",
";",
"i",
"=",
"next",
"(",
"i",
")",
")",
"{",
"closure",
".",
"call",
"(",
"i",
")",
";",
"}",
"}",
"else",
"throw",
"new",
"GroovyRuntimeException",
"(",
"\"The argument (\"",
"+",
"to",
"+",
"\") to upto() cannot be earlier than the value (\"",
"+",
"self",
"+",
"\") it's called on.\"",
")",
";",
"}"
] |
Iterates from this date up to the given date, inclusive,
incrementing by one day each time.
@param self a Date
@param to another Date to go up to
@param closure the closure to call
@since 2.2
|
[
"Iterates",
"from",
"this",
"date",
"up",
"to",
"the",
"given",
"date",
"inclusive",
"incrementing",
"by",
"one",
"day",
"each",
"time",
"."
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-dateutil/src/main/java/org/apache/groovy/dateutil/extensions/DateUtilExtensions.java#L709-L717
|
13,302
|
apache/groovy
|
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
|
StaticTypeCheckingVisitor.isSkippedInnerClass
|
protected boolean isSkippedInnerClass(AnnotatedNode node) {
if (!(node instanceof InnerClassNode)) return false;
MethodNode enclosingMethod = ((InnerClassNode) node).getEnclosingMethod();
return enclosingMethod != null && isSkipMode(enclosingMethod);
}
|
java
|
protected boolean isSkippedInnerClass(AnnotatedNode node) {
if (!(node instanceof InnerClassNode)) return false;
MethodNode enclosingMethod = ((InnerClassNode) node).getEnclosingMethod();
return enclosingMethod != null && isSkipMode(enclosingMethod);
}
|
[
"protected",
"boolean",
"isSkippedInnerClass",
"(",
"AnnotatedNode",
"node",
")",
"{",
"if",
"(",
"!",
"(",
"node",
"instanceof",
"InnerClassNode",
")",
")",
"return",
"false",
";",
"MethodNode",
"enclosingMethod",
"=",
"(",
"(",
"InnerClassNode",
")",
"node",
")",
".",
"getEnclosingMethod",
"(",
")",
";",
"return",
"enclosingMethod",
"!=",
"null",
"&&",
"isSkipMode",
"(",
"enclosingMethod",
")",
";",
"}"
] |
Test if a node is an inner class node, and if it is, then checks if the enclosing method is skipped.
@param node
@return true if the inner class node should be skipped
|
[
"Test",
"if",
"a",
"node",
"is",
"an",
"inner",
"class",
"node",
"and",
"if",
"it",
"is",
"then",
"checks",
"if",
"the",
"enclosing",
"method",
"is",
"skipped",
"."
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L473-L477
|
13,303
|
apache/groovy
|
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
|
StaticTypeCheckingVisitor.checkOrMarkPrivateAccess
|
private void checkOrMarkPrivateAccess(Expression source, FieldNode fn, boolean lhsOfAssignment) {
if (fn == null) return;
ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode();
ClassNode declaringClass = fn.getDeclaringClass();
if (fn.isPrivate() &&
(declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) &&
declaringClass.getModule() == enclosingClassNode.getModule()) {
if (!lhsOfAssignment && enclosingClassNode.isDerivedFrom(declaringClass)) {
// check for a public/protected getter since JavaBean getters haven't been recognised as properties
// at this point and we don't want private field access for that case which will be handled later
boolean isPrimBool = fn.getOriginType().equals(ClassHelper.boolean_TYPE);
String suffix = Verifier.capitalize(fn.getName());
MethodNode getterNode = findValidGetter(enclosingClassNode, "get" + suffix);
if (getterNode == null && isPrimBool) {
getterNode = findValidGetter(enclosingClassNode, "is" + suffix);
}
if (getterNode != null) {
source.putNodeMetaData(INFERRED_TYPE, getterNode.getReturnType());
return;
}
}
StaticTypesMarker marker = lhsOfAssignment ? StaticTypesMarker.PV_FIELDS_MUTATION : StaticTypesMarker.PV_FIELDS_ACCESS;
addPrivateFieldOrMethodAccess(source, declaringClass, marker, fn);
}
}
|
java
|
private void checkOrMarkPrivateAccess(Expression source, FieldNode fn, boolean lhsOfAssignment) {
if (fn == null) return;
ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode();
ClassNode declaringClass = fn.getDeclaringClass();
if (fn.isPrivate() &&
(declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) &&
declaringClass.getModule() == enclosingClassNode.getModule()) {
if (!lhsOfAssignment && enclosingClassNode.isDerivedFrom(declaringClass)) {
// check for a public/protected getter since JavaBean getters haven't been recognised as properties
// at this point and we don't want private field access for that case which will be handled later
boolean isPrimBool = fn.getOriginType().equals(ClassHelper.boolean_TYPE);
String suffix = Verifier.capitalize(fn.getName());
MethodNode getterNode = findValidGetter(enclosingClassNode, "get" + suffix);
if (getterNode == null && isPrimBool) {
getterNode = findValidGetter(enclosingClassNode, "is" + suffix);
}
if (getterNode != null) {
source.putNodeMetaData(INFERRED_TYPE, getterNode.getReturnType());
return;
}
}
StaticTypesMarker marker = lhsOfAssignment ? StaticTypesMarker.PV_FIELDS_MUTATION : StaticTypesMarker.PV_FIELDS_ACCESS;
addPrivateFieldOrMethodAccess(source, declaringClass, marker, fn);
}
}
|
[
"private",
"void",
"checkOrMarkPrivateAccess",
"(",
"Expression",
"source",
",",
"FieldNode",
"fn",
",",
"boolean",
"lhsOfAssignment",
")",
"{",
"if",
"(",
"fn",
"==",
"null",
")",
"return",
";",
"ClassNode",
"enclosingClassNode",
"=",
"typeCheckingContext",
".",
"getEnclosingClassNode",
"(",
")",
";",
"ClassNode",
"declaringClass",
"=",
"fn",
".",
"getDeclaringClass",
"(",
")",
";",
"if",
"(",
"fn",
".",
"isPrivate",
"(",
")",
"&&",
"(",
"declaringClass",
"!=",
"enclosingClassNode",
"||",
"typeCheckingContext",
".",
"getEnclosingClosure",
"(",
")",
"!=",
"null",
")",
"&&",
"declaringClass",
".",
"getModule",
"(",
")",
"==",
"enclosingClassNode",
".",
"getModule",
"(",
")",
")",
"{",
"if",
"(",
"!",
"lhsOfAssignment",
"&&",
"enclosingClassNode",
".",
"isDerivedFrom",
"(",
"declaringClass",
")",
")",
"{",
"// check for a public/protected getter since JavaBean getters haven't been recognised as properties",
"// at this point and we don't want private field access for that case which will be handled later",
"boolean",
"isPrimBool",
"=",
"fn",
".",
"getOriginType",
"(",
")",
".",
"equals",
"(",
"ClassHelper",
".",
"boolean_TYPE",
")",
";",
"String",
"suffix",
"=",
"Verifier",
".",
"capitalize",
"(",
"fn",
".",
"getName",
"(",
")",
")",
";",
"MethodNode",
"getterNode",
"=",
"findValidGetter",
"(",
"enclosingClassNode",
",",
"\"get\"",
"+",
"suffix",
")",
";",
"if",
"(",
"getterNode",
"==",
"null",
"&&",
"isPrimBool",
")",
"{",
"getterNode",
"=",
"findValidGetter",
"(",
"enclosingClassNode",
",",
"\"is\"",
"+",
"suffix",
")",
";",
"}",
"if",
"(",
"getterNode",
"!=",
"null",
")",
"{",
"source",
".",
"putNodeMetaData",
"(",
"INFERRED_TYPE",
",",
"getterNode",
".",
"getReturnType",
"(",
")",
")",
";",
"return",
";",
"}",
"}",
"StaticTypesMarker",
"marker",
"=",
"lhsOfAssignment",
"?",
"StaticTypesMarker",
".",
"PV_FIELDS_MUTATION",
":",
"StaticTypesMarker",
".",
"PV_FIELDS_ACCESS",
";",
"addPrivateFieldOrMethodAccess",
"(",
"source",
",",
"declaringClass",
",",
"marker",
",",
"fn",
")",
";",
"}",
"}"
] |
Given a field node, checks if we are accessing or setting a private field from an inner class.
|
[
"Given",
"a",
"field",
"node",
"checks",
"if",
"we",
"are",
"accessing",
"or",
"setting",
"a",
"private",
"field",
"from",
"an",
"inner",
"class",
"."
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L502-L526
|
13,304
|
apache/groovy
|
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
|
StaticTypeCheckingVisitor.checkOrMarkInnerFieldAccess
|
private String checkOrMarkInnerFieldAccess(Expression source, FieldNode fn, boolean lhsOfAssignment, String delegationData) {
if (fn == null || fn.isStatic()) return delegationData;
ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode();
ClassNode declaringClass = fn.getDeclaringClass();
// private handled elsewhere
if ((fn.isPublic() || fn.isProtected()) &&
(declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) &&
declaringClass.getModule() == enclosingClassNode.getModule() && !lhsOfAssignment && enclosingClassNode.isDerivedFrom(declaringClass)) {
if (source instanceof PropertyExpression) {
PropertyExpression pe = (PropertyExpression) source;
// this and attributes handled elsewhere
if ("this".equals(pe.getPropertyAsString()) || source instanceof AttributeExpression) return delegationData;
pe.getObjectExpression().putNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER, "owner");
}
return "owner";
}
return delegationData;
}
|
java
|
private String checkOrMarkInnerFieldAccess(Expression source, FieldNode fn, boolean lhsOfAssignment, String delegationData) {
if (fn == null || fn.isStatic()) return delegationData;
ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode();
ClassNode declaringClass = fn.getDeclaringClass();
// private handled elsewhere
if ((fn.isPublic() || fn.isProtected()) &&
(declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) &&
declaringClass.getModule() == enclosingClassNode.getModule() && !lhsOfAssignment && enclosingClassNode.isDerivedFrom(declaringClass)) {
if (source instanceof PropertyExpression) {
PropertyExpression pe = (PropertyExpression) source;
// this and attributes handled elsewhere
if ("this".equals(pe.getPropertyAsString()) || source instanceof AttributeExpression) return delegationData;
pe.getObjectExpression().putNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER, "owner");
}
return "owner";
}
return delegationData;
}
|
[
"private",
"String",
"checkOrMarkInnerFieldAccess",
"(",
"Expression",
"source",
",",
"FieldNode",
"fn",
",",
"boolean",
"lhsOfAssignment",
",",
"String",
"delegationData",
")",
"{",
"if",
"(",
"fn",
"==",
"null",
"||",
"fn",
".",
"isStatic",
"(",
")",
")",
"return",
"delegationData",
";",
"ClassNode",
"enclosingClassNode",
"=",
"typeCheckingContext",
".",
"getEnclosingClassNode",
"(",
")",
";",
"ClassNode",
"declaringClass",
"=",
"fn",
".",
"getDeclaringClass",
"(",
")",
";",
"// private handled elsewhere",
"if",
"(",
"(",
"fn",
".",
"isPublic",
"(",
")",
"||",
"fn",
".",
"isProtected",
"(",
")",
")",
"&&",
"(",
"declaringClass",
"!=",
"enclosingClassNode",
"||",
"typeCheckingContext",
".",
"getEnclosingClosure",
"(",
")",
"!=",
"null",
")",
"&&",
"declaringClass",
".",
"getModule",
"(",
")",
"==",
"enclosingClassNode",
".",
"getModule",
"(",
")",
"&&",
"!",
"lhsOfAssignment",
"&&",
"enclosingClassNode",
".",
"isDerivedFrom",
"(",
"declaringClass",
")",
")",
"{",
"if",
"(",
"source",
"instanceof",
"PropertyExpression",
")",
"{",
"PropertyExpression",
"pe",
"=",
"(",
"PropertyExpression",
")",
"source",
";",
"// this and attributes handled elsewhere",
"if",
"(",
"\"this\"",
".",
"equals",
"(",
"pe",
".",
"getPropertyAsString",
"(",
")",
")",
"||",
"source",
"instanceof",
"AttributeExpression",
")",
"return",
"delegationData",
";",
"pe",
".",
"getObjectExpression",
"(",
")",
".",
"putNodeMetaData",
"(",
"StaticTypesMarker",
".",
"IMPLICIT_RECEIVER",
",",
"\"owner\"",
")",
";",
"}",
"return",
"\"owner\"",
";",
"}",
"return",
"delegationData",
";",
"}"
] |
Given a field node, checks if we are accessing or setting a public or protected field from an inner class.
|
[
"Given",
"a",
"field",
"node",
"checks",
"if",
"we",
"are",
"accessing",
"or",
"setting",
"a",
"public",
"or",
"protected",
"field",
"from",
"an",
"inner",
"class",
"."
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L531-L548
|
13,305
|
apache/groovy
|
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
|
StaticTypeCheckingVisitor.silentlyVisitMethodNode
|
protected void silentlyVisitMethodNode(final MethodNode directMethodCallCandidate) {
// visit is authorized because the classnode belongs to the same source unit
ErrorCollector collector = new ErrorCollector(typeCheckingContext.getErrorCollector().getConfiguration());
startMethodInference(directMethodCallCandidate, collector);
}
|
java
|
protected void silentlyVisitMethodNode(final MethodNode directMethodCallCandidate) {
// visit is authorized because the classnode belongs to the same source unit
ErrorCollector collector = new ErrorCollector(typeCheckingContext.getErrorCollector().getConfiguration());
startMethodInference(directMethodCallCandidate, collector);
}
|
[
"protected",
"void",
"silentlyVisitMethodNode",
"(",
"final",
"MethodNode",
"directMethodCallCandidate",
")",
"{",
"// visit is authorized because the classnode belongs to the same source unit",
"ErrorCollector",
"collector",
"=",
"new",
"ErrorCollector",
"(",
"typeCheckingContext",
".",
"getErrorCollector",
"(",
")",
".",
"getConfiguration",
"(",
")",
")",
";",
"startMethodInference",
"(",
"directMethodCallCandidate",
",",
"collector",
")",
";",
"}"
] |
visit a method call target, to infer the type. Don't report errors right
away, that will be done by a later visitMethod call
|
[
"visit",
"a",
"method",
"call",
"target",
"to",
"infer",
"the",
"type",
".",
"Don",
"t",
"report",
"errors",
"right",
"away",
"that",
"will",
"be",
"done",
"by",
"a",
"later",
"visitMethod",
"call"
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L2714-L2718
|
13,306
|
apache/groovy
|
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
|
StaticTypeCheckingVisitor.createUsableClassNodeFromGenericsType
|
private static ClassNode createUsableClassNodeFromGenericsType(final GenericsType genericsType) {
ClassNode value = genericsType.getType();
if (genericsType.isPlaceholder()) {
value = OBJECT_TYPE;
}
ClassNode lowerBound = genericsType.getLowerBound();
if (lowerBound != null) {
value = lowerBound;
} else {
ClassNode[] upperBounds = genericsType.getUpperBounds();
if (upperBounds != null) {
value = WideningCategories.lowestUpperBound(Arrays.asList(upperBounds));
}
}
return value;
}
|
java
|
private static ClassNode createUsableClassNodeFromGenericsType(final GenericsType genericsType) {
ClassNode value = genericsType.getType();
if (genericsType.isPlaceholder()) {
value = OBJECT_TYPE;
}
ClassNode lowerBound = genericsType.getLowerBound();
if (lowerBound != null) {
value = lowerBound;
} else {
ClassNode[] upperBounds = genericsType.getUpperBounds();
if (upperBounds != null) {
value = WideningCategories.lowestUpperBound(Arrays.asList(upperBounds));
}
}
return value;
}
|
[
"private",
"static",
"ClassNode",
"createUsableClassNodeFromGenericsType",
"(",
"final",
"GenericsType",
"genericsType",
")",
"{",
"ClassNode",
"value",
"=",
"genericsType",
".",
"getType",
"(",
")",
";",
"if",
"(",
"genericsType",
".",
"isPlaceholder",
"(",
")",
")",
"{",
"value",
"=",
"OBJECT_TYPE",
";",
"}",
"ClassNode",
"lowerBound",
"=",
"genericsType",
".",
"getLowerBound",
"(",
")",
";",
"if",
"(",
"lowerBound",
"!=",
"null",
")",
"{",
"value",
"=",
"lowerBound",
";",
"}",
"else",
"{",
"ClassNode",
"[",
"]",
"upperBounds",
"=",
"genericsType",
".",
"getUpperBounds",
"(",
")",
";",
"if",
"(",
"upperBounds",
"!=",
"null",
")",
"{",
"value",
"=",
"WideningCategories",
".",
"lowestUpperBound",
"(",
"Arrays",
".",
"asList",
"(",
"upperBounds",
")",
")",
";",
"}",
"}",
"return",
"value",
";",
"}"
] |
Given a GenericsType instance, returns a ClassNode which can be used as an inferred type.
@param genericsType a {@link org.codehaus.groovy.ast.GenericsType} representing either a type, a placeholder or a wildcard
@return a class node usable as an inferred type
|
[
"Given",
"a",
"GenericsType",
"instance",
"returns",
"a",
"ClassNode",
"which",
"can",
"be",
"used",
"as",
"an",
"inferred",
"type",
"."
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L3156-L3171
|
13,307
|
apache/groovy
|
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
|
StaticTypeCheckingVisitor.adjustWithTraits
|
private static ClassNode adjustWithTraits(final MethodNode directMethodCallCandidate, final ClassNode receiver, final ClassNode[] args, final ClassNode returnType) {
if (directMethodCallCandidate instanceof ExtensionMethodNode) {
ExtensionMethodNode emn = (ExtensionMethodNode) directMethodCallCandidate;
if ("withTraits".equals(emn.getName()) && "DefaultGroovyMethods".equals(emn.getExtensionMethodNode().getDeclaringClass().getNameWithoutPackage())) {
List<ClassNode> nodes = new LinkedList<ClassNode>();
Collections.addAll(nodes, receiver.getInterfaces());
for (ClassNode arg : args) {
if (isClassClassNodeWrappingConcreteType(arg)) {
nodes.add(arg.getGenericsTypes()[0].getType());
} else {
nodes.add(arg);
}
}
return new LowestUpperBoundClassNode(returnType.getName() + "Composed", OBJECT_TYPE, nodes.toArray(ClassNode.EMPTY_ARRAY));
}
}
return returnType;
}
|
java
|
private static ClassNode adjustWithTraits(final MethodNode directMethodCallCandidate, final ClassNode receiver, final ClassNode[] args, final ClassNode returnType) {
if (directMethodCallCandidate instanceof ExtensionMethodNode) {
ExtensionMethodNode emn = (ExtensionMethodNode) directMethodCallCandidate;
if ("withTraits".equals(emn.getName()) && "DefaultGroovyMethods".equals(emn.getExtensionMethodNode().getDeclaringClass().getNameWithoutPackage())) {
List<ClassNode> nodes = new LinkedList<ClassNode>();
Collections.addAll(nodes, receiver.getInterfaces());
for (ClassNode arg : args) {
if (isClassClassNodeWrappingConcreteType(arg)) {
nodes.add(arg.getGenericsTypes()[0].getType());
} else {
nodes.add(arg);
}
}
return new LowestUpperBoundClassNode(returnType.getName() + "Composed", OBJECT_TYPE, nodes.toArray(ClassNode.EMPTY_ARRAY));
}
}
return returnType;
}
|
[
"private",
"static",
"ClassNode",
"adjustWithTraits",
"(",
"final",
"MethodNode",
"directMethodCallCandidate",
",",
"final",
"ClassNode",
"receiver",
",",
"final",
"ClassNode",
"[",
"]",
"args",
",",
"final",
"ClassNode",
"returnType",
")",
"{",
"if",
"(",
"directMethodCallCandidate",
"instanceof",
"ExtensionMethodNode",
")",
"{",
"ExtensionMethodNode",
"emn",
"=",
"(",
"ExtensionMethodNode",
")",
"directMethodCallCandidate",
";",
"if",
"(",
"\"withTraits\"",
".",
"equals",
"(",
"emn",
".",
"getName",
"(",
")",
")",
"&&",
"\"DefaultGroovyMethods\"",
".",
"equals",
"(",
"emn",
".",
"getExtensionMethodNode",
"(",
")",
".",
"getDeclaringClass",
"(",
")",
".",
"getNameWithoutPackage",
"(",
")",
")",
")",
"{",
"List",
"<",
"ClassNode",
">",
"nodes",
"=",
"new",
"LinkedList",
"<",
"ClassNode",
">",
"(",
")",
";",
"Collections",
".",
"addAll",
"(",
"nodes",
",",
"receiver",
".",
"getInterfaces",
"(",
")",
")",
";",
"for",
"(",
"ClassNode",
"arg",
":",
"args",
")",
"{",
"if",
"(",
"isClassClassNodeWrappingConcreteType",
"(",
"arg",
")",
")",
"{",
"nodes",
".",
"add",
"(",
"arg",
".",
"getGenericsTypes",
"(",
")",
"[",
"0",
"]",
".",
"getType",
"(",
")",
")",
";",
"}",
"else",
"{",
"nodes",
".",
"add",
"(",
"arg",
")",
";",
"}",
"}",
"return",
"new",
"LowestUpperBoundClassNode",
"(",
"returnType",
".",
"getName",
"(",
")",
"+",
"\"Composed\"",
",",
"OBJECT_TYPE",
",",
"nodes",
".",
"toArray",
"(",
"ClassNode",
".",
"EMPTY_ARRAY",
")",
")",
";",
"}",
"}",
"return",
"returnType",
";",
"}"
] |
A special method handling the "withTrait" call for which the type checker knows more than
what the type signature is able to tell. If "withTrait" is detected, then a new class node
is created representing the list of trait interfaces.
@param directMethodCallCandidate a method selected by the type checker
@param receiver the receiver of the method call
@param args the arguments of the method call
@param returnType the original return type, as inferred by the type checker
@return fixed return type if the selected method is {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#withTraits(Object, Class[]) withTraits}
|
[
"A",
"special",
"method",
"handling",
"the",
"withTrait",
"call",
"for",
"which",
"the",
"type",
"checker",
"knows",
"more",
"than",
"what",
"the",
"type",
"signature",
"is",
"able",
"to",
"tell",
".",
"If",
"withTrait",
"is",
"detected",
"then",
"a",
"new",
"class",
"node",
"is",
"created",
"representing",
"the",
"list",
"of",
"trait",
"interfaces",
"."
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L3757-L3774
|
13,308
|
apache/groovy
|
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
|
StaticTypeCheckingVisitor.findMethodsWithGenerated
|
protected List<MethodNode> findMethodsWithGenerated(ClassNode receiver, String name) {
List<MethodNode> methods = receiver.getMethods(name);
if (methods.isEmpty() || receiver.isResolved()) return methods;
List<MethodNode> result = addGeneratedMethods(receiver, methods);
return result;
}
|
java
|
protected List<MethodNode> findMethodsWithGenerated(ClassNode receiver, String name) {
List<MethodNode> methods = receiver.getMethods(name);
if (methods.isEmpty() || receiver.isResolved()) return methods;
List<MethodNode> result = addGeneratedMethods(receiver, methods);
return result;
}
|
[
"protected",
"List",
"<",
"MethodNode",
">",
"findMethodsWithGenerated",
"(",
"ClassNode",
"receiver",
",",
"String",
"name",
")",
"{",
"List",
"<",
"MethodNode",
">",
"methods",
"=",
"receiver",
".",
"getMethods",
"(",
"name",
")",
";",
"if",
"(",
"methods",
".",
"isEmpty",
"(",
")",
"||",
"receiver",
".",
"isResolved",
"(",
")",
")",
"return",
"methods",
";",
"List",
"<",
"MethodNode",
">",
"result",
"=",
"addGeneratedMethods",
"(",
"receiver",
",",
"methods",
")",
";",
"return",
"result",
";",
"}"
] |
This method returns the list of methods named against the supplied parameter that
are defined on the specified receiver, but it will also add "non existing" methods
that will be generated afterwards by the compiler, for example if a method is using
default values and that the specified class node isn't compiled yet.
@param receiver the receiver where to find methods
@param name the name of the methods to return
@return the methods that are defined on the receiver completed with stubs for future methods
|
[
"This",
"method",
"returns",
"the",
"list",
"of",
"methods",
"named",
"against",
"the",
"supplied",
"parameter",
"that",
"are",
"defined",
"on",
"the",
"specified",
"receiver",
"but",
"it",
"will",
"also",
"add",
"non",
"existing",
"methods",
"that",
"will",
"be",
"generated",
"afterwards",
"by",
"the",
"compiler",
"for",
"example",
"if",
"a",
"method",
"is",
"using",
"default",
"values",
"and",
"that",
"the",
"specified",
"class",
"node",
"isn",
"t",
"compiled",
"yet",
"."
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L4666-L4672
|
13,309
|
apache/groovy
|
src/main/java/org/codehaus/groovy/runtime/ScriptBytecodeAdapter.java
|
ScriptBytecodeAdapter.asType
|
public static Object asType(Object object, Class type) throws Throwable {
if (object == null) object = NullObject.getNullObject();
return invokeMethodN(object.getClass(), object, "asType", new Object[]{type});
}
|
java
|
public static Object asType(Object object, Class type) throws Throwable {
if (object == null) object = NullObject.getNullObject();
return invokeMethodN(object.getClass(), object, "asType", new Object[]{type});
}
|
[
"public",
"static",
"Object",
"asType",
"(",
"Object",
"object",
",",
"Class",
"type",
")",
"throws",
"Throwable",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"object",
"=",
"NullObject",
".",
"getNullObject",
"(",
")",
";",
"return",
"invokeMethodN",
"(",
"object",
".",
"getClass",
"(",
")",
",",
"object",
",",
"\"asType\"",
",",
"new",
"Object",
"[",
"]",
"{",
"type",
"}",
")",
";",
"}"
] |
Provides a hook for type coercion of the given object to the required type
@param type of object to convert the given object to
@param object the object to be converted
@return the original object or a new converted value
@throws Throwable if the coercion fails
|
[
"Provides",
"a",
"hook",
"for",
"type",
"coercion",
"of",
"the",
"given",
"object",
"to",
"the",
"required",
"type"
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/ScriptBytecodeAdapter.java#L601-L604
|
13,310
|
apache/groovy
|
src/main/java/org/codehaus/groovy/runtime/ScriptBytecodeAdapter.java
|
ScriptBytecodeAdapter.castToType
|
public static Object castToType(Object object, Class type) throws Throwable {
return DefaultTypeTransformation.castToType(object, type);
}
|
java
|
public static Object castToType(Object object, Class type) throws Throwable {
return DefaultTypeTransformation.castToType(object, type);
}
|
[
"public",
"static",
"Object",
"castToType",
"(",
"Object",
"object",
",",
"Class",
"type",
")",
"throws",
"Throwable",
"{",
"return",
"DefaultTypeTransformation",
".",
"castToType",
"(",
"object",
",",
"type",
")",
";",
"}"
] |
Provides a hook for type casting of the given object to the required type
@param type of object to convert the given object to
@param object the object to be converted
@return the original object or a new converted value
@throws Throwable if the type casting fails
|
[
"Provides",
"a",
"hook",
"for",
"type",
"casting",
"of",
"the",
"given",
"object",
"to",
"the",
"required",
"type"
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/ScriptBytecodeAdapter.java#L614-L616
|
13,311
|
apache/groovy
|
src/main/java/org/apache/groovy/util/Maps.java
|
Maps.inverse
|
public static <K, V> Map<V, K> inverse(Map<K, V> map) {
return inverse(map, false);
}
|
java
|
public static <K, V> Map<V, K> inverse(Map<K, V> map) {
return inverse(map, false);
}
|
[
"public",
"static",
"<",
"K",
",",
"V",
">",
"Map",
"<",
"V",
",",
"K",
">",
"inverse",
"(",
"Map",
"<",
"K",
",",
"V",
">",
"map",
")",
"{",
"return",
"inverse",
"(",
"map",
",",
"false",
")",
";",
"}"
] |
Returns the inverse view of this map, and duplicated key is not allowed
@param map the map to inverse
@param <K> key type
@param <V> value type
@return the inverse view of this map
|
[
"Returns",
"the",
"inverse",
"view",
"of",
"this",
"map",
"and",
"duplicated",
"key",
"is",
"not",
"allowed"
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/apache/groovy/util/Maps.java#L5789-L5791
|
13,312
|
apache/groovy
|
src/main/java/org/apache/groovy/util/Maps.java
|
Maps.inverse
|
public static <K, V> Map<V, K> inverse(Map<K, V> map, boolean force) {
// Because we can not rely on 3rd party library(excluding antlr, asm), we have to implement our own utils such as the `inverse` method...
// Actually `BiMap` of Guava and `BidiMap` of commons-collections are both suitable for this scenario.
Map<V, K> resultMap = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : map.entrySet()) {
V value = entry.getValue();
if (!force && resultMap.containsKey(value)) {
throw new IllegalArgumentException("duplicated key found: " + value);
}
resultMap.put(value, entry.getKey());
}
return Collections.<V, K>unmodifiableMap(resultMap);
}
|
java
|
public static <K, V> Map<V, K> inverse(Map<K, V> map, boolean force) {
// Because we can not rely on 3rd party library(excluding antlr, asm), we have to implement our own utils such as the `inverse` method...
// Actually `BiMap` of Guava and `BidiMap` of commons-collections are both suitable for this scenario.
Map<V, K> resultMap = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : map.entrySet()) {
V value = entry.getValue();
if (!force && resultMap.containsKey(value)) {
throw new IllegalArgumentException("duplicated key found: " + value);
}
resultMap.put(value, entry.getKey());
}
return Collections.<V, K>unmodifiableMap(resultMap);
}
|
[
"public",
"static",
"<",
"K",
",",
"V",
">",
"Map",
"<",
"V",
",",
"K",
">",
"inverse",
"(",
"Map",
"<",
"K",
",",
"V",
">",
"map",
",",
"boolean",
"force",
")",
"{",
"// Because we can not rely on 3rd party library(excluding antlr, asm), we have to implement our own utils such as the `inverse` method...",
"// Actually `BiMap` of Guava and `BidiMap` of commons-collections are both suitable for this scenario.",
"Map",
"<",
"V",
",",
"K",
">",
"resultMap",
"=",
"new",
"LinkedHashMap",
"<>",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"K",
",",
"V",
">",
"entry",
":",
"map",
".",
"entrySet",
"(",
")",
")",
"{",
"V",
"value",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"!",
"force",
"&&",
"resultMap",
".",
"containsKey",
"(",
"value",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"duplicated key found: \"",
"+",
"value",
")",
";",
"}",
"resultMap",
".",
"put",
"(",
"value",
",",
"entry",
".",
"getKey",
"(",
")",
")",
";",
"}",
"return",
"Collections",
".",
"<",
"V",
",",
"K",
">",
"unmodifiableMap",
"(",
"resultMap",
")",
";",
"}"
] |
Returns the inverse view of this map
@param map the map to inverse
@param force whether to put anyway even if duplicated key exists
@param <K> key type
@param <V> value type
@return the inverse view of this map
|
[
"Returns",
"the",
"inverse",
"view",
"of",
"this",
"map"
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/apache/groovy/util/Maps.java#L5802-L5819
|
13,313
|
apache/groovy
|
subprojects/groovy-xml/src/main/java/groovy/xml/Namespace.java
|
Namespace.get
|
public QName get(String localName) {
if (uri != null && uri.length() > 0) {
if (prefix != null) {
return new QName(uri, localName, prefix);
}
else {
return new QName(uri, localName);
}
}
else {
return new QName(localName);
}
}
|
java
|
public QName get(String localName) {
if (uri != null && uri.length() > 0) {
if (prefix != null) {
return new QName(uri, localName, prefix);
}
else {
return new QName(uri, localName);
}
}
else {
return new QName(localName);
}
}
|
[
"public",
"QName",
"get",
"(",
"String",
"localName",
")",
"{",
"if",
"(",
"uri",
"!=",
"null",
"&&",
"uri",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"if",
"(",
"prefix",
"!=",
"null",
")",
"{",
"return",
"new",
"QName",
"(",
"uri",
",",
"localName",
",",
"prefix",
")",
";",
"}",
"else",
"{",
"return",
"new",
"QName",
"(",
"uri",
",",
"localName",
")",
";",
"}",
"}",
"else",
"{",
"return",
"new",
"QName",
"(",
"localName",
")",
";",
"}",
"}"
] |
Returns the QName for the given localName.
@param localName
the local name within this
|
[
"Returns",
"the",
"QName",
"for",
"the",
"given",
"localName",
"."
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-xml/src/main/java/groovy/xml/Namespace.java#L48-L60
|
13,314
|
apache/groovy
|
subprojects/groovy-xml/src/main/java/groovy/xml/NamespaceBuilderSupport.java
|
NamespaceBuilderSupport.invokeMethod
|
@Override
public Object invokeMethod(String methodName, Object args) {
// detect namespace declared on the added node like xmlns:foo="http:/foo"
Map attributes = findAttributes(args);
for (Iterator<Map.Entry> iter = attributes.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = iter.next();
String key = String.valueOf(entry.getKey());
if (key.startsWith("xmlns:")) {
String prefix = key.substring(6);
String uri = String.valueOf(entry.getValue());
namespace(uri, prefix);
iter.remove();
}
}
return super.invokeMethod(methodName, args);
}
|
java
|
@Override
public Object invokeMethod(String methodName, Object args) {
// detect namespace declared on the added node like xmlns:foo="http:/foo"
Map attributes = findAttributes(args);
for (Iterator<Map.Entry> iter = attributes.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = iter.next();
String key = String.valueOf(entry.getKey());
if (key.startsWith("xmlns:")) {
String prefix = key.substring(6);
String uri = String.valueOf(entry.getValue());
namespace(uri, prefix);
iter.remove();
}
}
return super.invokeMethod(methodName, args);
}
|
[
"@",
"Override",
"public",
"Object",
"invokeMethod",
"(",
"String",
"methodName",
",",
"Object",
"args",
")",
"{",
"// detect namespace declared on the added node like xmlns:foo=\"http:/foo\"",
"Map",
"attributes",
"=",
"findAttributes",
"(",
"args",
")",
";",
"for",
"(",
"Iterator",
"<",
"Map",
".",
"Entry",
">",
"iter",
"=",
"attributes",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"iter",
".",
"hasNext",
"(",
")",
";",
")",
"{",
"Map",
".",
"Entry",
"entry",
"=",
"iter",
".",
"next",
"(",
")",
";",
"String",
"key",
"=",
"String",
".",
"valueOf",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
";",
"if",
"(",
"key",
".",
"startsWith",
"(",
"\"xmlns:\"",
")",
")",
"{",
"String",
"prefix",
"=",
"key",
".",
"substring",
"(",
"6",
")",
";",
"String",
"uri",
"=",
"String",
".",
"valueOf",
"(",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"namespace",
"(",
"uri",
",",
"prefix",
")",
";",
"iter",
".",
"remove",
"(",
")",
";",
"}",
"}",
"return",
"super",
".",
"invokeMethod",
"(",
"methodName",
",",
"args",
")",
";",
"}"
] |
Allow automatic detection of namespace declared in the attributes
|
[
"Allow",
"automatic",
"detection",
"of",
"namespace",
"declared",
"in",
"the",
"attributes"
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-xml/src/main/java/groovy/xml/NamespaceBuilderSupport.java#L119-L135
|
13,315
|
apache/groovy
|
src/main/java/org/codehaus/groovy/classgen/asm/OperandStack.java
|
OperandStack.dup
|
public void dup() {
ClassNode type = getTopOperand();
stack.add(type);
MethodVisitor mv = controller.getMethodVisitor();
if (type == ClassHelper.double_TYPE || type == ClassHelper.long_TYPE) {
mv.visitInsn(DUP2);
} else {
mv.visitInsn(DUP);
}
}
|
java
|
public void dup() {
ClassNode type = getTopOperand();
stack.add(type);
MethodVisitor mv = controller.getMethodVisitor();
if (type == ClassHelper.double_TYPE || type == ClassHelper.long_TYPE) {
mv.visitInsn(DUP2);
} else {
mv.visitInsn(DUP);
}
}
|
[
"public",
"void",
"dup",
"(",
")",
"{",
"ClassNode",
"type",
"=",
"getTopOperand",
"(",
")",
";",
"stack",
".",
"add",
"(",
"type",
")",
";",
"MethodVisitor",
"mv",
"=",
"controller",
".",
"getMethodVisitor",
"(",
")",
";",
"if",
"(",
"type",
"==",
"ClassHelper",
".",
"double_TYPE",
"||",
"type",
"==",
"ClassHelper",
".",
"long_TYPE",
")",
"{",
"mv",
".",
"visitInsn",
"(",
"DUP2",
")",
";",
"}",
"else",
"{",
"mv",
".",
"visitInsn",
"(",
"DUP",
")",
";",
"}",
"}"
] |
duplicate top element
|
[
"duplicate",
"top",
"element"
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/classgen/asm/OperandStack.java#L187-L196
|
13,316
|
apache/groovy
|
src/main/java/org/codehaus/groovy/classgen/asm/OperandStack.java
|
OperandStack.remove
|
public void remove(int amount) {
int size = stack.size();
for (int i=size-1; i>size-1-amount; i--) {
popWithMessage(i);
}
}
|
java
|
public void remove(int amount) {
int size = stack.size();
for (int i=size-1; i>size-1-amount; i--) {
popWithMessage(i);
}
}
|
[
"public",
"void",
"remove",
"(",
"int",
"amount",
")",
"{",
"int",
"size",
"=",
"stack",
".",
"size",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"size",
"-",
"1",
";",
"i",
">",
"size",
"-",
"1",
"-",
"amount",
";",
"i",
"--",
")",
"{",
"popWithMessage",
"(",
"i",
")",
";",
"}",
"}"
] |
Remove amount elements from the operand stack, without using pop.
For example after a method invocation
|
[
"Remove",
"amount",
"elements",
"from",
"the",
"operand",
"stack",
"without",
"using",
"pop",
".",
"For",
"example",
"after",
"a",
"method",
"invocation"
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/classgen/asm/OperandStack.java#L215-L220
|
13,317
|
apache/groovy
|
src/main/java/org/codehaus/groovy/classgen/asm/OperandStack.java
|
OperandStack.swap
|
public void swap() {
MethodVisitor mv = controller.getMethodVisitor();
int size = stack.size();
ClassNode b = stack.get(size-1);
ClassNode a = stack.get(size-2);
// dup_x1: ---
// dup_x2: aab -> baab
// dup2_x1: abb -> bbabb
// dup2_x2: aabb -> bbaabb
// b = top element, a = element under b
// top element at right
if (isTwoSlotType(a)) { // aa
if (isTwoSlotType(b)) { // aabb
// aabb -> bbaa
mv.visitInsn(DUP2_X2); // bbaabb
mv.visitInsn(POP2); // bbaa
} else {
// aab -> baa
mv.visitInsn(DUP_X2); // baab
mv.visitInsn(POP); // baa
}
} else { // a
if (isTwoSlotType(b)) { //abb
// abb -> bba
mv.visitInsn(DUP2_X1); // bbabb
mv.visitInsn(POP2); // bba
} else {
// ab -> ba
mv.visitInsn(SWAP);
}
}
stack.set(size-1,a);
stack.set(size-2,b);
}
|
java
|
public void swap() {
MethodVisitor mv = controller.getMethodVisitor();
int size = stack.size();
ClassNode b = stack.get(size-1);
ClassNode a = stack.get(size-2);
// dup_x1: ---
// dup_x2: aab -> baab
// dup2_x1: abb -> bbabb
// dup2_x2: aabb -> bbaabb
// b = top element, a = element under b
// top element at right
if (isTwoSlotType(a)) { // aa
if (isTwoSlotType(b)) { // aabb
// aabb -> bbaa
mv.visitInsn(DUP2_X2); // bbaabb
mv.visitInsn(POP2); // bbaa
} else {
// aab -> baa
mv.visitInsn(DUP_X2); // baab
mv.visitInsn(POP); // baa
}
} else { // a
if (isTwoSlotType(b)) { //abb
// abb -> bba
mv.visitInsn(DUP2_X1); // bbabb
mv.visitInsn(POP2); // bba
} else {
// ab -> ba
mv.visitInsn(SWAP);
}
}
stack.set(size-1,a);
stack.set(size-2,b);
}
|
[
"public",
"void",
"swap",
"(",
")",
"{",
"MethodVisitor",
"mv",
"=",
"controller",
".",
"getMethodVisitor",
"(",
")",
";",
"int",
"size",
"=",
"stack",
".",
"size",
"(",
")",
";",
"ClassNode",
"b",
"=",
"stack",
".",
"get",
"(",
"size",
"-",
"1",
")",
";",
"ClassNode",
"a",
"=",
"stack",
".",
"get",
"(",
"size",
"-",
"2",
")",
";",
"// dup_x1: --- ",
"// dup_x2: aab -> baab",
"// dup2_x1: abb -> bbabb",
"// dup2_x2: aabb -> bbaabb",
"// b = top element, a = element under b",
"// top element at right",
"if",
"(",
"isTwoSlotType",
"(",
"a",
")",
")",
"{",
"// aa",
"if",
"(",
"isTwoSlotType",
"(",
"b",
")",
")",
"{",
"// aabb",
"// aabb -> bbaa",
"mv",
".",
"visitInsn",
"(",
"DUP2_X2",
")",
";",
"// bbaabb",
"mv",
".",
"visitInsn",
"(",
"POP2",
")",
";",
"// bbaa",
"}",
"else",
"{",
"// aab -> baa",
"mv",
".",
"visitInsn",
"(",
"DUP_X2",
")",
";",
"// baab",
"mv",
".",
"visitInsn",
"(",
"POP",
")",
";",
"// baa",
"}",
"}",
"else",
"{",
"// a",
"if",
"(",
"isTwoSlotType",
"(",
"b",
")",
")",
"{",
"//abb",
"// abb -> bba",
"mv",
".",
"visitInsn",
"(",
"DUP2_X1",
")",
";",
"// bbabb",
"mv",
".",
"visitInsn",
"(",
"POP2",
")",
";",
"// bba",
"}",
"else",
"{",
"// ab -> ba",
"mv",
".",
"visitInsn",
"(",
"SWAP",
")",
";",
"}",
"}",
"stack",
".",
"set",
"(",
"size",
"-",
"1",
",",
"a",
")",
";",
"stack",
".",
"set",
"(",
"size",
"-",
"2",
",",
"b",
")",
";",
"}"
] |
swap two top level operands
|
[
"swap",
"two",
"top",
"level",
"operands"
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/classgen/asm/OperandStack.java#L232-L265
|
13,318
|
apache/groovy
|
src/main/java/org/codehaus/groovy/classgen/asm/BinaryIntExpressionHelper.java
|
BinaryIntExpressionHelper.writeStdCompare
|
protected boolean writeStdCompare(int type, boolean simulate) {
type = type-COMPARE_NOT_EQUAL;
// look if really compare
if (type<0||type>7) return false;
if (!simulate) {
MethodVisitor mv = getController().getMethodVisitor();
OperandStack operandStack = getController().getOperandStack();
// operands are on the stack already
int bytecode = stdCompareCodes[type];
Label l1 = new Label();
mv.visitJumpInsn(bytecode,l1);
mv.visitInsn(ICONST_1);
Label l2 = new Label();
mv.visitJumpInsn(GOTO, l2);
mv.visitLabel(l1);
mv.visitInsn(ICONST_0);
mv.visitLabel(l2);
operandStack.replace(ClassHelper.boolean_TYPE, 2);
}
return true;
}
|
java
|
protected boolean writeStdCompare(int type, boolean simulate) {
type = type-COMPARE_NOT_EQUAL;
// look if really compare
if (type<0||type>7) return false;
if (!simulate) {
MethodVisitor mv = getController().getMethodVisitor();
OperandStack operandStack = getController().getOperandStack();
// operands are on the stack already
int bytecode = stdCompareCodes[type];
Label l1 = new Label();
mv.visitJumpInsn(bytecode,l1);
mv.visitInsn(ICONST_1);
Label l2 = new Label();
mv.visitJumpInsn(GOTO, l2);
mv.visitLabel(l1);
mv.visitInsn(ICONST_0);
mv.visitLabel(l2);
operandStack.replace(ClassHelper.boolean_TYPE, 2);
}
return true;
}
|
[
"protected",
"boolean",
"writeStdCompare",
"(",
"int",
"type",
",",
"boolean",
"simulate",
")",
"{",
"type",
"=",
"type",
"-",
"COMPARE_NOT_EQUAL",
";",
"// look if really compare",
"if",
"(",
"type",
"<",
"0",
"||",
"type",
">",
"7",
")",
"return",
"false",
";",
"if",
"(",
"!",
"simulate",
")",
"{",
"MethodVisitor",
"mv",
"=",
"getController",
"(",
")",
".",
"getMethodVisitor",
"(",
")",
";",
"OperandStack",
"operandStack",
"=",
"getController",
"(",
")",
".",
"getOperandStack",
"(",
")",
";",
"// operands are on the stack already",
"int",
"bytecode",
"=",
"stdCompareCodes",
"[",
"type",
"]",
";",
"Label",
"l1",
"=",
"new",
"Label",
"(",
")",
";",
"mv",
".",
"visitJumpInsn",
"(",
"bytecode",
",",
"l1",
")",
";",
"mv",
".",
"visitInsn",
"(",
"ICONST_1",
")",
";",
"Label",
"l2",
"=",
"new",
"Label",
"(",
")",
";",
"mv",
".",
"visitJumpInsn",
"(",
"GOTO",
",",
"l2",
")",
";",
"mv",
".",
"visitLabel",
"(",
"l1",
")",
";",
"mv",
".",
"visitInsn",
"(",
"ICONST_0",
")",
";",
"mv",
".",
"visitLabel",
"(",
"l2",
")",
";",
"operandStack",
".",
"replace",
"(",
"ClassHelper",
".",
"boolean_TYPE",
",",
"2",
")",
";",
"}",
"return",
"true",
";",
"}"
] |
writes a std compare. This involves the tokens IF_ICMPEQ, IF_ICMPNE,
IF_ICMPEQ, IF_ICMPNE, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE and IF_ICMPLT
@param type the token type
@return true if a successful std compare write
|
[
"writes",
"a",
"std",
"compare",
".",
"This",
"involves",
"the",
"tokens",
"IF_ICMPEQ",
"IF_ICMPNE",
"IF_ICMPEQ",
"IF_ICMPNE",
"IF_ICMPGE",
"IF_ICMPGT",
"IF_ICMPLE",
"and",
"IF_ICMPLT"
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/classgen/asm/BinaryIntExpressionHelper.java#L145-L166
|
13,319
|
apache/groovy
|
src/main/java/org/codehaus/groovy/classgen/asm/BinaryIntExpressionHelper.java
|
BinaryIntExpressionHelper.writeSpaceship
|
protected boolean writeSpaceship(int type, boolean simulate) {
if (type != COMPARE_TO) return false;
/*
we will actually do
(x < y) ? -1 : ((x == y) ? 0 : 1)
which is the essence of what the call with Integers would do
this compiles to something along
<x>
<y>
IF_ICMPGE L1
ICONST_M1
GOTO L2
L1
<x>
<y>
IF_ICMPNE L3
ICONST_0
GOTO L2
L3
ICONST_1
L2
since the operators are already on the stack and we don't want
to load them again, we will instead duplicate them. This will
require some pop actions in the branches!
DUP2 (operands: IIII)
IF_ICMPGE L1 (operands: II)
ICONST_M1 (operands: III)
GOTO L2
L1
----- (operands: II)
IF_ICMPNE L3 (operands: -)
ICONST_0 (operands: I)
GOTO L2
L3
- jump from L1 branch to here (operands: -)
ICONST_1 (operands: I)
L2
- if jump from GOTO L2 we have III, but need only I
- if from L3 branch we get only I
this means we have to pop of II before loading -1
*/
if (!simulate) {
MethodVisitor mv = getController().getMethodVisitor();
// duplicate int arguments
mv.visitInsn(DUP2);
Label l1 = new Label();
mv.visitJumpInsn(IF_ICMPGE,l1);
// no jump, so -1, need to pop off surplus II
mv.visitInsn(POP2);
mv.visitInsn(ICONST_M1);
Label l2 = new Label();
mv.visitJumpInsn(GOTO, l2);
mv.visitLabel(l1);
Label l3 = new Label();
mv.visitJumpInsn(IF_ICMPNE,l3);
mv.visitInsn(ICONST_0);
mv.visitJumpInsn(GOTO,l2);
mv.visitLabel(l3);
mv.visitInsn(ICONST_1);
getController().getOperandStack().replace(ClassHelper.int_TYPE, 2);
}
return true;
}
|
java
|
protected boolean writeSpaceship(int type, boolean simulate) {
if (type != COMPARE_TO) return false;
/*
we will actually do
(x < y) ? -1 : ((x == y) ? 0 : 1)
which is the essence of what the call with Integers would do
this compiles to something along
<x>
<y>
IF_ICMPGE L1
ICONST_M1
GOTO L2
L1
<x>
<y>
IF_ICMPNE L3
ICONST_0
GOTO L2
L3
ICONST_1
L2
since the operators are already on the stack and we don't want
to load them again, we will instead duplicate them. This will
require some pop actions in the branches!
DUP2 (operands: IIII)
IF_ICMPGE L1 (operands: II)
ICONST_M1 (operands: III)
GOTO L2
L1
----- (operands: II)
IF_ICMPNE L3 (operands: -)
ICONST_0 (operands: I)
GOTO L2
L3
- jump from L1 branch to here (operands: -)
ICONST_1 (operands: I)
L2
- if jump from GOTO L2 we have III, but need only I
- if from L3 branch we get only I
this means we have to pop of II before loading -1
*/
if (!simulate) {
MethodVisitor mv = getController().getMethodVisitor();
// duplicate int arguments
mv.visitInsn(DUP2);
Label l1 = new Label();
mv.visitJumpInsn(IF_ICMPGE,l1);
// no jump, so -1, need to pop off surplus II
mv.visitInsn(POP2);
mv.visitInsn(ICONST_M1);
Label l2 = new Label();
mv.visitJumpInsn(GOTO, l2);
mv.visitLabel(l1);
Label l3 = new Label();
mv.visitJumpInsn(IF_ICMPNE,l3);
mv.visitInsn(ICONST_0);
mv.visitJumpInsn(GOTO,l2);
mv.visitLabel(l3);
mv.visitInsn(ICONST_1);
getController().getOperandStack().replace(ClassHelper.int_TYPE, 2);
}
return true;
}
|
[
"protected",
"boolean",
"writeSpaceship",
"(",
"int",
"type",
",",
"boolean",
"simulate",
")",
"{",
"if",
"(",
"type",
"!=",
"COMPARE_TO",
")",
"return",
"false",
";",
"/* \n we will actually do\n \n (x < y) ? -1 : ((x == y) ? 0 : 1)\n which is the essence of what the call with Integers would do\n this compiles to something along\n \n <x>\n <y>\n IF_ICMPGE L1\n ICONST_M1\n GOTO L2\n L1\n <x>\n <y>\n IF_ICMPNE L3\n ICONST_0\n GOTO L2\n L3\n ICONST_1\n L2\n \n since the operators are already on the stack and we don't want\n to load them again, we will instead duplicate them. This will\n require some pop actions in the branches!\n \n DUP2 (operands: IIII) \n IF_ICMPGE L1 (operands: II)\n ICONST_M1 (operands: III)\n GOTO L2\n L1\n ----- (operands: II)\n IF_ICMPNE L3 (operands: -)\n ICONST_0 (operands: I)\n GOTO L2\n L3\n - jump from L1 branch to here (operands: -)\n ICONST_1 (operands: I)\n L2 \n - if jump from GOTO L2 we have III, but need only I\n - if from L3 branch we get only I\n \n this means we have to pop of II before loading -1\n \n */",
"if",
"(",
"!",
"simulate",
")",
"{",
"MethodVisitor",
"mv",
"=",
"getController",
"(",
")",
".",
"getMethodVisitor",
"(",
")",
";",
"// duplicate int arguments",
"mv",
".",
"visitInsn",
"(",
"DUP2",
")",
";",
"Label",
"l1",
"=",
"new",
"Label",
"(",
")",
";",
"mv",
".",
"visitJumpInsn",
"(",
"IF_ICMPGE",
",",
"l1",
")",
";",
"// no jump, so -1, need to pop off surplus II",
"mv",
".",
"visitInsn",
"(",
"POP2",
")",
";",
"mv",
".",
"visitInsn",
"(",
"ICONST_M1",
")",
";",
"Label",
"l2",
"=",
"new",
"Label",
"(",
")",
";",
"mv",
".",
"visitJumpInsn",
"(",
"GOTO",
",",
"l2",
")",
";",
"mv",
".",
"visitLabel",
"(",
"l1",
")",
";",
"Label",
"l3",
"=",
"new",
"Label",
"(",
")",
";",
"mv",
".",
"visitJumpInsn",
"(",
"IF_ICMPNE",
",",
"l3",
")",
";",
"mv",
".",
"visitInsn",
"(",
"ICONST_0",
")",
";",
"mv",
".",
"visitJumpInsn",
"(",
"GOTO",
",",
"l2",
")",
";",
"mv",
".",
"visitLabel",
"(",
"l3",
")",
";",
"mv",
".",
"visitInsn",
"(",
"ICONST_1",
")",
";",
"getController",
"(",
")",
".",
"getOperandStack",
"(",
")",
".",
"replace",
"(",
"ClassHelper",
".",
"int_TYPE",
",",
"2",
")",
";",
"}",
"return",
"true",
";",
"}"
] |
writes the spaceship operator, type should be COMPARE_TO
@param type the token type
@return true if a successful spaceship operator write
|
[
"writes",
"the",
"spaceship",
"operator",
"type",
"should",
"be",
"COMPARE_TO"
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/classgen/asm/BinaryIntExpressionHelper.java#L173-L245
|
13,320
|
apache/groovy
|
subprojects/groovy-json/src/main/java/org/apache/groovy/json/internal/LazyValueMap.java
|
LazyValueMap.chopMap
|
public final void chopMap() {
/* if it has been chopped then you have to return. */
if (mapChopped) {
return;
}
mapChopped = true;
/* If the internal map was not create yet, don't. We can chop the value w/o creating the internal map.*/
if (this.map == null) {
for (int index = 0; index < len; index++) {
MapItemValue entry = (MapItemValue) items[index];
Value value = entry.getValue();
if (value == null) continue;
if (value.isContainer()) {
chopContainer(value);
} else {
value.chop();
}
}
} else {
/* Iterate through the map and do the same thing. Make sure children and children of children are chopped. */
for (Map.Entry<String, Object> entry : map.entrySet()) {
Object object = entry.getValue();
if (object instanceof Value) {
Value value = (Value) object;
if (value.isContainer()) {
chopContainer(value);
} else {
value.chop();
}
} else if (object instanceof LazyValueMap) {
LazyValueMap m = (LazyValueMap) object;
m.chopMap();
} else if (object instanceof ValueList) {
ValueList list = (ValueList) object;
list.chopList();
}
}
}
}
|
java
|
public final void chopMap() {
/* if it has been chopped then you have to return. */
if (mapChopped) {
return;
}
mapChopped = true;
/* If the internal map was not create yet, don't. We can chop the value w/o creating the internal map.*/
if (this.map == null) {
for (int index = 0; index < len; index++) {
MapItemValue entry = (MapItemValue) items[index];
Value value = entry.getValue();
if (value == null) continue;
if (value.isContainer()) {
chopContainer(value);
} else {
value.chop();
}
}
} else {
/* Iterate through the map and do the same thing. Make sure children and children of children are chopped. */
for (Map.Entry<String, Object> entry : map.entrySet()) {
Object object = entry.getValue();
if (object instanceof Value) {
Value value = (Value) object;
if (value.isContainer()) {
chopContainer(value);
} else {
value.chop();
}
} else if (object instanceof LazyValueMap) {
LazyValueMap m = (LazyValueMap) object;
m.chopMap();
} else if (object instanceof ValueList) {
ValueList list = (ValueList) object;
list.chopList();
}
}
}
}
|
[
"public",
"final",
"void",
"chopMap",
"(",
")",
"{",
"/* if it has been chopped then you have to return. */",
"if",
"(",
"mapChopped",
")",
"{",
"return",
";",
"}",
"mapChopped",
"=",
"true",
";",
"/* If the internal map was not create yet, don't. We can chop the value w/o creating the internal map.*/",
"if",
"(",
"this",
".",
"map",
"==",
"null",
")",
"{",
"for",
"(",
"int",
"index",
"=",
"0",
";",
"index",
"<",
"len",
";",
"index",
"++",
")",
"{",
"MapItemValue",
"entry",
"=",
"(",
"MapItemValue",
")",
"items",
"[",
"index",
"]",
";",
"Value",
"value",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"continue",
";",
"if",
"(",
"value",
".",
"isContainer",
"(",
")",
")",
"{",
"chopContainer",
"(",
"value",
")",
";",
"}",
"else",
"{",
"value",
".",
"chop",
"(",
")",
";",
"}",
"}",
"}",
"else",
"{",
"/* Iterate through the map and do the same thing. Make sure children and children of children are chopped. */",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Object",
">",
"entry",
":",
"map",
".",
"entrySet",
"(",
")",
")",
"{",
"Object",
"object",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"object",
"instanceof",
"Value",
")",
"{",
"Value",
"value",
"=",
"(",
"Value",
")",
"object",
";",
"if",
"(",
"value",
".",
"isContainer",
"(",
")",
")",
"{",
"chopContainer",
"(",
"value",
")",
";",
"}",
"else",
"{",
"value",
".",
"chop",
"(",
")",
";",
"}",
"}",
"else",
"if",
"(",
"object",
"instanceof",
"LazyValueMap",
")",
"{",
"LazyValueMap",
"m",
"=",
"(",
"LazyValueMap",
")",
"object",
";",
"m",
".",
"chopMap",
"(",
")",
";",
"}",
"else",
"if",
"(",
"object",
"instanceof",
"ValueList",
")",
"{",
"ValueList",
"list",
"=",
"(",
"ValueList",
")",
"object",
";",
"list",
".",
"chopList",
"(",
")",
";",
"}",
"}",
"}",
"}"
] |
Chop this map.
|
[
"Chop",
"this",
"map",
"."
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-json/src/main/java/org/apache/groovy/json/internal/LazyValueMap.java#L133-L174
|
13,321
|
apache/groovy
|
src/main/java/org/codehaus/groovy/antlr/AntlrParserPlugin.java
|
AntlrParserPlugin.convertGroovy
|
protected void convertGroovy(AST node) {
while (node != null) {
int type = node.getType();
switch (type) {
case PACKAGE_DEF:
packageDef(node);
break;
case STATIC_IMPORT:
case IMPORT:
importDef(node);
break;
case TRAIT_DEF:
case CLASS_DEF:
classDef(node);
break;
case INTERFACE_DEF:
interfaceDef(node);
break;
case METHOD_DEF:
methodDef(node);
break;
case ENUM_DEF:
enumDef(node);
break;
case ANNOTATION_DEF:
annotationDef(node);
break;
default: {
Statement statement = statement(node);
output.addStatement(statement);
}
}
node = node.getNextSibling();
}
}
|
java
|
protected void convertGroovy(AST node) {
while (node != null) {
int type = node.getType();
switch (type) {
case PACKAGE_DEF:
packageDef(node);
break;
case STATIC_IMPORT:
case IMPORT:
importDef(node);
break;
case TRAIT_DEF:
case CLASS_DEF:
classDef(node);
break;
case INTERFACE_DEF:
interfaceDef(node);
break;
case METHOD_DEF:
methodDef(node);
break;
case ENUM_DEF:
enumDef(node);
break;
case ANNOTATION_DEF:
annotationDef(node);
break;
default: {
Statement statement = statement(node);
output.addStatement(statement);
}
}
node = node.getNextSibling();
}
}
|
[
"protected",
"void",
"convertGroovy",
"(",
"AST",
"node",
")",
"{",
"while",
"(",
"node",
"!=",
"null",
")",
"{",
"int",
"type",
"=",
"node",
".",
"getType",
"(",
")",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"PACKAGE_DEF",
":",
"packageDef",
"(",
"node",
")",
";",
"break",
";",
"case",
"STATIC_IMPORT",
":",
"case",
"IMPORT",
":",
"importDef",
"(",
"node",
")",
";",
"break",
";",
"case",
"TRAIT_DEF",
":",
"case",
"CLASS_DEF",
":",
"classDef",
"(",
"node",
")",
";",
"break",
";",
"case",
"INTERFACE_DEF",
":",
"interfaceDef",
"(",
"node",
")",
";",
"break",
";",
"case",
"METHOD_DEF",
":",
"methodDef",
"(",
"node",
")",
";",
"break",
";",
"case",
"ENUM_DEF",
":",
"enumDef",
"(",
"node",
")",
";",
"break",
";",
"case",
"ANNOTATION_DEF",
":",
"annotationDef",
"(",
"node",
")",
";",
"break",
";",
"default",
":",
"{",
"Statement",
"statement",
"=",
"statement",
"(",
"node",
")",
";",
"output",
".",
"addStatement",
"(",
"statement",
")",
";",
"}",
"}",
"node",
"=",
"node",
".",
"getNextSibling",
"(",
")",
";",
"}",
"}"
] |
Converts the Antlr AST to the Groovy AST
|
[
"Converts",
"the",
"Antlr",
"AST",
"to",
"the",
"Groovy",
"AST"
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/antlr/AntlrParserPlugin.java#L347-L388
|
13,322
|
apache/groovy
|
src/main/java/org/codehaus/groovy/antlr/AntlrParserPlugin.java
|
AntlrParserPlugin.mapExpression
|
protected Expression mapExpression(AST mapNode) {
List expressions = new ArrayList();
AST elist = mapNode.getFirstChild();
if (elist != null) { // totally empty in the case of [:]
assertNodeType(ELIST, elist);
for (AST node = elist.getFirstChild(); node != null; node = node.getNextSibling()) {
switch (node.getType()) {
case LABELED_ARG:
case SPREAD_MAP_ARG:
break; // legal cases
case SPREAD_ARG:
assertNodeType(SPREAD_MAP_ARG, node);
break; // helpful error
default:
assertNodeType(LABELED_ARG, node);
break; // helpful error
}
expressions.add(mapEntryExpression(node));
}
}
MapExpression mapExpression = new MapExpression(expressions);
configureAST(mapExpression, mapNode);
return mapExpression;
}
|
java
|
protected Expression mapExpression(AST mapNode) {
List expressions = new ArrayList();
AST elist = mapNode.getFirstChild();
if (elist != null) { // totally empty in the case of [:]
assertNodeType(ELIST, elist);
for (AST node = elist.getFirstChild(); node != null; node = node.getNextSibling()) {
switch (node.getType()) {
case LABELED_ARG:
case SPREAD_MAP_ARG:
break; // legal cases
case SPREAD_ARG:
assertNodeType(SPREAD_MAP_ARG, node);
break; // helpful error
default:
assertNodeType(LABELED_ARG, node);
break; // helpful error
}
expressions.add(mapEntryExpression(node));
}
}
MapExpression mapExpression = new MapExpression(expressions);
configureAST(mapExpression, mapNode);
return mapExpression;
}
|
[
"protected",
"Expression",
"mapExpression",
"(",
"AST",
"mapNode",
")",
"{",
"List",
"expressions",
"=",
"new",
"ArrayList",
"(",
")",
";",
"AST",
"elist",
"=",
"mapNode",
".",
"getFirstChild",
"(",
")",
";",
"if",
"(",
"elist",
"!=",
"null",
")",
"{",
"// totally empty in the case of [:]",
"assertNodeType",
"(",
"ELIST",
",",
"elist",
")",
";",
"for",
"(",
"AST",
"node",
"=",
"elist",
".",
"getFirstChild",
"(",
")",
";",
"node",
"!=",
"null",
";",
"node",
"=",
"node",
".",
"getNextSibling",
"(",
")",
")",
"{",
"switch",
"(",
"node",
".",
"getType",
"(",
")",
")",
"{",
"case",
"LABELED_ARG",
":",
"case",
"SPREAD_MAP_ARG",
":",
"break",
";",
"// legal cases",
"case",
"SPREAD_ARG",
":",
"assertNodeType",
"(",
"SPREAD_MAP_ARG",
",",
"node",
")",
";",
"break",
";",
"// helpful error",
"default",
":",
"assertNodeType",
"(",
"LABELED_ARG",
",",
"node",
")",
";",
"break",
";",
"// helpful error",
"}",
"expressions",
".",
"add",
"(",
"mapEntryExpression",
"(",
"node",
")",
")",
";",
"}",
"}",
"MapExpression",
"mapExpression",
"=",
"new",
"MapExpression",
"(",
"expressions",
")",
";",
"configureAST",
"(",
"mapExpression",
",",
"mapNode",
")",
";",
"return",
"mapExpression",
";",
"}"
] |
Typically only used for map constructors I think?
|
[
"Typically",
"only",
"used",
"for",
"map",
"constructors",
"I",
"think?"
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/antlr/AntlrParserPlugin.java#L2294-L2317
|
13,323
|
apache/groovy
|
src/main/java/org/codehaus/groovy/antlr/AntlrParserPlugin.java
|
AntlrParserPlugin.buildName
|
protected ClassNode buildName(AST node) {
if (isType(TYPE, node)) {
node = node.getFirstChild();
}
ClassNode answer = null;
if (isType(DOT, node) || isType(OPTIONAL_DOT, node)) {
answer = ClassHelper.make(qualifiedName(node));
} else if (isPrimitiveTypeLiteral(node)) {
answer = ClassHelper.make(node.getText());
} else if (isType(INDEX_OP, node) || isType(ARRAY_DECLARATOR, node)) {
AST child = node.getFirstChild();
answer = buildName(child).makeArray();
configureAST(answer, node);
return answer;
} else {
String identifier = node.getText();
answer = ClassHelper.make(identifier);
}
AST nextSibling = node.getNextSibling();
if (isType(INDEX_OP, nextSibling) || isType(ARRAY_DECLARATOR, node)) {
answer = answer.makeArray();
configureAST(answer, node);
return answer;
} else {
configureAST(answer, node);
return answer;
}
}
|
java
|
protected ClassNode buildName(AST node) {
if (isType(TYPE, node)) {
node = node.getFirstChild();
}
ClassNode answer = null;
if (isType(DOT, node) || isType(OPTIONAL_DOT, node)) {
answer = ClassHelper.make(qualifiedName(node));
} else if (isPrimitiveTypeLiteral(node)) {
answer = ClassHelper.make(node.getText());
} else if (isType(INDEX_OP, node) || isType(ARRAY_DECLARATOR, node)) {
AST child = node.getFirstChild();
answer = buildName(child).makeArray();
configureAST(answer, node);
return answer;
} else {
String identifier = node.getText();
answer = ClassHelper.make(identifier);
}
AST nextSibling = node.getNextSibling();
if (isType(INDEX_OP, nextSibling) || isType(ARRAY_DECLARATOR, node)) {
answer = answer.makeArray();
configureAST(answer, node);
return answer;
} else {
configureAST(answer, node);
return answer;
}
}
|
[
"protected",
"ClassNode",
"buildName",
"(",
"AST",
"node",
")",
"{",
"if",
"(",
"isType",
"(",
"TYPE",
",",
"node",
")",
")",
"{",
"node",
"=",
"node",
".",
"getFirstChild",
"(",
")",
";",
"}",
"ClassNode",
"answer",
"=",
"null",
";",
"if",
"(",
"isType",
"(",
"DOT",
",",
"node",
")",
"||",
"isType",
"(",
"OPTIONAL_DOT",
",",
"node",
")",
")",
"{",
"answer",
"=",
"ClassHelper",
".",
"make",
"(",
"qualifiedName",
"(",
"node",
")",
")",
";",
"}",
"else",
"if",
"(",
"isPrimitiveTypeLiteral",
"(",
"node",
")",
")",
"{",
"answer",
"=",
"ClassHelper",
".",
"make",
"(",
"node",
".",
"getText",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"isType",
"(",
"INDEX_OP",
",",
"node",
")",
"||",
"isType",
"(",
"ARRAY_DECLARATOR",
",",
"node",
")",
")",
"{",
"AST",
"child",
"=",
"node",
".",
"getFirstChild",
"(",
")",
";",
"answer",
"=",
"buildName",
"(",
"child",
")",
".",
"makeArray",
"(",
")",
";",
"configureAST",
"(",
"answer",
",",
"node",
")",
";",
"return",
"answer",
";",
"}",
"else",
"{",
"String",
"identifier",
"=",
"node",
".",
"getText",
"(",
")",
";",
"answer",
"=",
"ClassHelper",
".",
"make",
"(",
"identifier",
")",
";",
"}",
"AST",
"nextSibling",
"=",
"node",
".",
"getNextSibling",
"(",
")",
";",
"if",
"(",
"isType",
"(",
"INDEX_OP",
",",
"nextSibling",
")",
"||",
"isType",
"(",
"ARRAY_DECLARATOR",
",",
"node",
")",
")",
"{",
"answer",
"=",
"answer",
".",
"makeArray",
"(",
")",
";",
"configureAST",
"(",
"answer",
",",
"node",
")",
";",
"return",
"answer",
";",
"}",
"else",
"{",
"configureAST",
"(",
"answer",
",",
"node",
")",
";",
"return",
"answer",
";",
"}",
"}"
] |
Extracts an identifier from the Antlr AST and then performs a name resolution
to see if the given name is a type from imports, aliases or newly created classes
|
[
"Extracts",
"an",
"identifier",
"from",
"the",
"Antlr",
"AST",
"and",
"then",
"performs",
"a",
"name",
"resolution",
"to",
"see",
"if",
"the",
"given",
"name",
"is",
"a",
"type",
"from",
"imports",
"aliases",
"or",
"newly",
"created",
"classes"
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/antlr/AntlrParserPlugin.java#L3125-L3152
|
13,324
|
apache/groovy
|
src/main/java/org/codehaus/groovy/runtime/callsite/CallSiteArray.java
|
CallSiteArray.createPojoSite
|
private static CallSite createPojoSite(CallSite callSite, Object receiver, Object[] args) {
final Class klazz = receiver.getClass();
MetaClass metaClass = InvokerHelper.getMetaClass(receiver);
if (!GroovyCategorySupport.hasCategoryInCurrentThread() && metaClass instanceof MetaClassImpl) {
final MetaClassImpl mci = (MetaClassImpl) metaClass;
final ClassInfo info = mci.getTheCachedClass().classInfo;
if (info.hasPerInstanceMetaClasses()) {
return new PerInstancePojoMetaClassSite(callSite, info);
} else {
return mci.createPojoCallSite(callSite, receiver, args);
}
}
ClassInfo info = ClassInfo.getClassInfo(klazz);
if (info.hasPerInstanceMetaClasses())
return new PerInstancePojoMetaClassSite(callSite, info);
else
return new PojoMetaClassSite(callSite, metaClass);
}
|
java
|
private static CallSite createPojoSite(CallSite callSite, Object receiver, Object[] args) {
final Class klazz = receiver.getClass();
MetaClass metaClass = InvokerHelper.getMetaClass(receiver);
if (!GroovyCategorySupport.hasCategoryInCurrentThread() && metaClass instanceof MetaClassImpl) {
final MetaClassImpl mci = (MetaClassImpl) metaClass;
final ClassInfo info = mci.getTheCachedClass().classInfo;
if (info.hasPerInstanceMetaClasses()) {
return new PerInstancePojoMetaClassSite(callSite, info);
} else {
return mci.createPojoCallSite(callSite, receiver, args);
}
}
ClassInfo info = ClassInfo.getClassInfo(klazz);
if (info.hasPerInstanceMetaClasses())
return new PerInstancePojoMetaClassSite(callSite, info);
else
return new PojoMetaClassSite(callSite, metaClass);
}
|
[
"private",
"static",
"CallSite",
"createPojoSite",
"(",
"CallSite",
"callSite",
",",
"Object",
"receiver",
",",
"Object",
"[",
"]",
"args",
")",
"{",
"final",
"Class",
"klazz",
"=",
"receiver",
".",
"getClass",
"(",
")",
";",
"MetaClass",
"metaClass",
"=",
"InvokerHelper",
".",
"getMetaClass",
"(",
"receiver",
")",
";",
"if",
"(",
"!",
"GroovyCategorySupport",
".",
"hasCategoryInCurrentThread",
"(",
")",
"&&",
"metaClass",
"instanceof",
"MetaClassImpl",
")",
"{",
"final",
"MetaClassImpl",
"mci",
"=",
"(",
"MetaClassImpl",
")",
"metaClass",
";",
"final",
"ClassInfo",
"info",
"=",
"mci",
".",
"getTheCachedClass",
"(",
")",
".",
"classInfo",
";",
"if",
"(",
"info",
".",
"hasPerInstanceMetaClasses",
"(",
")",
")",
"{",
"return",
"new",
"PerInstancePojoMetaClassSite",
"(",
"callSite",
",",
"info",
")",
";",
"}",
"else",
"{",
"return",
"mci",
".",
"createPojoCallSite",
"(",
"callSite",
",",
"receiver",
",",
"args",
")",
";",
"}",
"}",
"ClassInfo",
"info",
"=",
"ClassInfo",
".",
"getClassInfo",
"(",
"klazz",
")",
";",
"if",
"(",
"info",
".",
"hasPerInstanceMetaClasses",
"(",
")",
")",
"return",
"new",
"PerInstancePojoMetaClassSite",
"(",
"callSite",
",",
"info",
")",
";",
"else",
"return",
"new",
"PojoMetaClassSite",
"(",
"callSite",
",",
"metaClass",
")",
";",
"}"
] |
otherwise or if method doesn't exist we make call via POJO meta class
|
[
"otherwise",
"or",
"if",
"method",
"doesn",
"t",
"exist",
"we",
"make",
"call",
"via",
"POJO",
"meta",
"class"
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/callsite/CallSiteArray.java#L122-L140
|
13,325
|
apache/groovy
|
src/main/java/org/codehaus/groovy/runtime/memoize/UnlimitedConcurrentCache.java
|
UnlimitedConcurrentCache.clearAll
|
@Override
public Map<K, V> clearAll() {
Map<K, V> result = new LinkedHashMap<K, V>(map.size());
for (Map.Entry<K, V> entry : map.entrySet()) {
K key = entry.getKey();
V value = entry.getValue();
boolean removed = map.remove(key, value);
if (removed) {
result.put(key, value);
}
}
return result;
}
|
java
|
@Override
public Map<K, V> clearAll() {
Map<K, V> result = new LinkedHashMap<K, V>(map.size());
for (Map.Entry<K, V> entry : map.entrySet()) {
K key = entry.getKey();
V value = entry.getValue();
boolean removed = map.remove(key, value);
if (removed) {
result.put(key, value);
}
}
return result;
}
|
[
"@",
"Override",
"public",
"Map",
"<",
"K",
",",
"V",
">",
"clearAll",
"(",
")",
"{",
"Map",
"<",
"K",
",",
"V",
">",
"result",
"=",
"new",
"LinkedHashMap",
"<",
"K",
",",
"V",
">",
"(",
"map",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"K",
",",
"V",
">",
"entry",
":",
"map",
".",
"entrySet",
"(",
")",
")",
"{",
"K",
"key",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"V",
"value",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"boolean",
"removed",
"=",
"map",
".",
"remove",
"(",
"key",
",",
"value",
")",
";",
"if",
"(",
"removed",
")",
"{",
"result",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] |
Clear the cache
@return returns the content of the cleared map
|
[
"Clear",
"the",
"cache"
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/memoize/UnlimitedConcurrentCache.java#L88-L104
|
13,326
|
apache/groovy
|
src/main/java/org/codehaus/groovy/tools/ErrorReporter.java
|
ErrorReporter.dispatch
|
protected void dispatch(Throwable object, boolean child) {
if (object instanceof CompilationFailedException) {
report((CompilationFailedException) object, child);
} else if (object instanceof GroovyExceptionInterface) {
report((GroovyExceptionInterface) object, child);
} else if (object instanceof GroovyRuntimeException) {
report((GroovyRuntimeException) object, child);
} else if (object instanceof Exception) {
report((Exception) object, child);
} else {
report(object, child);
}
}
|
java
|
protected void dispatch(Throwable object, boolean child) {
if (object instanceof CompilationFailedException) {
report((CompilationFailedException) object, child);
} else if (object instanceof GroovyExceptionInterface) {
report((GroovyExceptionInterface) object, child);
} else if (object instanceof GroovyRuntimeException) {
report((GroovyRuntimeException) object, child);
} else if (object instanceof Exception) {
report((Exception) object, child);
} else {
report(object, child);
}
}
|
[
"protected",
"void",
"dispatch",
"(",
"Throwable",
"object",
",",
"boolean",
"child",
")",
"{",
"if",
"(",
"object",
"instanceof",
"CompilationFailedException",
")",
"{",
"report",
"(",
"(",
"CompilationFailedException",
")",
"object",
",",
"child",
")",
";",
"}",
"else",
"if",
"(",
"object",
"instanceof",
"GroovyExceptionInterface",
")",
"{",
"report",
"(",
"(",
"GroovyExceptionInterface",
")",
"object",
",",
"child",
")",
";",
"}",
"else",
"if",
"(",
"object",
"instanceof",
"GroovyRuntimeException",
")",
"{",
"report",
"(",
"(",
"GroovyRuntimeException",
")",
"object",
",",
"child",
")",
";",
"}",
"else",
"if",
"(",
"object",
"instanceof",
"Exception",
")",
"{",
"report",
"(",
"(",
"Exception",
")",
"object",
",",
"child",
")",
";",
"}",
"else",
"{",
"report",
"(",
"object",
",",
"child",
")",
";",
"}",
"}"
] |
Runs the report once all initialization is complete.
|
[
"Runs",
"the",
"report",
"once",
"all",
"initialization",
"is",
"complete",
"."
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/tools/ErrorReporter.java#L87-L100
|
13,327
|
apache/groovy
|
src/main/java/org/codehaus/groovy/tools/ErrorReporter.java
|
ErrorReporter.report
|
protected void report(CompilationFailedException e, boolean child) {
println(e.toString());
stacktrace(e, false);
}
|
java
|
protected void report(CompilationFailedException e, boolean child) {
println(e.toString());
stacktrace(e, false);
}
|
[
"protected",
"void",
"report",
"(",
"CompilationFailedException",
"e",
",",
"boolean",
"child",
")",
"{",
"println",
"(",
"e",
".",
"toString",
"(",
")",
")",
";",
"stacktrace",
"(",
"e",
",",
"false",
")",
";",
"}"
] |
For CompilationFailedException.
|
[
"For",
"CompilationFailedException",
"."
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/tools/ErrorReporter.java#L110-L113
|
13,328
|
apache/groovy
|
src/main/java/org/codehaus/groovy/tools/ErrorReporter.java
|
ErrorReporter.report
|
protected void report(GroovyExceptionInterface e, boolean child) {
println(((Exception) e).getMessage());
stacktrace((Exception) e, false);
}
|
java
|
protected void report(GroovyExceptionInterface e, boolean child) {
println(((Exception) e).getMessage());
stacktrace((Exception) e, false);
}
|
[
"protected",
"void",
"report",
"(",
"GroovyExceptionInterface",
"e",
",",
"boolean",
"child",
")",
"{",
"println",
"(",
"(",
"(",
"Exception",
")",
"e",
")",
".",
"getMessage",
"(",
")",
")",
";",
"stacktrace",
"(",
"(",
"Exception",
")",
"e",
",",
"false",
")",
";",
"}"
] |
For GroovyException.
|
[
"For",
"GroovyException",
"."
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/tools/ErrorReporter.java#L119-L122
|
13,329
|
apache/groovy
|
src/main/java/org/codehaus/groovy/tools/ErrorReporter.java
|
ErrorReporter.report
|
protected void report(Throwable e, boolean child) {
println(">>> a serious error occurred: " + e.getMessage());
stacktrace(e, true);
}
|
java
|
protected void report(Throwable e, boolean child) {
println(">>> a serious error occurred: " + e.getMessage());
stacktrace(e, true);
}
|
[
"protected",
"void",
"report",
"(",
"Throwable",
"e",
",",
"boolean",
"child",
")",
"{",
"println",
"(",
"\">>> a serious error occurred: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"stacktrace",
"(",
"e",
",",
"true",
")",
";",
"}"
] |
For everything else.
|
[
"For",
"everything",
"else",
"."
] |
71cf20addb611bb8d097a59e395fd20bc7f31772
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/tools/ErrorReporter.java#L137-L140
|
13,330
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/layout/MarginLayoutHelper.java
|
MarginLayoutHelper.setPadding
|
public void setPadding(int leftPadding, int topPadding, int rightPadding, int bottomPadding) {
mPaddingLeft = leftPadding;
mPaddingRight = rightPadding;
mPaddingTop = topPadding;
mPaddingBottom = bottomPadding;
}
|
java
|
public void setPadding(int leftPadding, int topPadding, int rightPadding, int bottomPadding) {
mPaddingLeft = leftPadding;
mPaddingRight = rightPadding;
mPaddingTop = topPadding;
mPaddingBottom = bottomPadding;
}
|
[
"public",
"void",
"setPadding",
"(",
"int",
"leftPadding",
",",
"int",
"topPadding",
",",
"int",
"rightPadding",
",",
"int",
"bottomPadding",
")",
"{",
"mPaddingLeft",
"=",
"leftPadding",
";",
"mPaddingRight",
"=",
"rightPadding",
";",
"mPaddingTop",
"=",
"topPadding",
";",
"mPaddingBottom",
"=",
"bottomPadding",
";",
"}"
] |
set paddings for this layoutHelper
@param leftPadding left padding
@param topPadding top padding
@param rightPadding right padding
@param bottomPadding bottom padding
|
[
"set",
"paddings",
"for",
"this",
"layoutHelper"
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/layout/MarginLayoutHelper.java#L55-L60
|
13,331
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/layout/MarginLayoutHelper.java
|
MarginLayoutHelper.setMargin
|
public void setMargin(int leftMargin, int topMargin, int rightMargin, int bottomMargin) {
this.mMarginLeft = leftMargin;
this.mMarginTop = topMargin;
this.mMarginRight = rightMargin;
this.mMarginBottom = bottomMargin;
}
|
java
|
public void setMargin(int leftMargin, int topMargin, int rightMargin, int bottomMargin) {
this.mMarginLeft = leftMargin;
this.mMarginTop = topMargin;
this.mMarginRight = rightMargin;
this.mMarginBottom = bottomMargin;
}
|
[
"public",
"void",
"setMargin",
"(",
"int",
"leftMargin",
",",
"int",
"topMargin",
",",
"int",
"rightMargin",
",",
"int",
"bottomMargin",
")",
"{",
"this",
".",
"mMarginLeft",
"=",
"leftMargin",
";",
"this",
".",
"mMarginTop",
"=",
"topMargin",
";",
"this",
".",
"mMarginRight",
"=",
"rightMargin",
";",
"this",
".",
"mMarginBottom",
"=",
"bottomMargin",
";",
"}"
] |
Set margins for this layoutHelper
@param leftMargin left margin
@param topMargin top margin
@param rightMargin right margin
@param bottomMargin bottom margin
|
[
"Set",
"margins",
"for",
"this",
"layoutHelper"
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/layout/MarginLayoutHelper.java#L70-L75
|
13,332
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/OrientationHelperEx.java
|
OrientationHelperEx.createOrientationHelper
|
public static OrientationHelperEx createOrientationHelper(
ExposeLinearLayoutManagerEx layoutManager, int orientation) {
switch (orientation) {
case HORIZONTAL:
return createHorizontalHelper(layoutManager);
case VERTICAL:
return createVerticalHelper(layoutManager);
}
throw new IllegalArgumentException("invalid orientation");
}
|
java
|
public static OrientationHelperEx createOrientationHelper(
ExposeLinearLayoutManagerEx layoutManager, int orientation) {
switch (orientation) {
case HORIZONTAL:
return createHorizontalHelper(layoutManager);
case VERTICAL:
return createVerticalHelper(layoutManager);
}
throw new IllegalArgumentException("invalid orientation");
}
|
[
"public",
"static",
"OrientationHelperEx",
"createOrientationHelper",
"(",
"ExposeLinearLayoutManagerEx",
"layoutManager",
",",
"int",
"orientation",
")",
"{",
"switch",
"(",
"orientation",
")",
"{",
"case",
"HORIZONTAL",
":",
"return",
"createHorizontalHelper",
"(",
"layoutManager",
")",
";",
"case",
"VERTICAL",
":",
"return",
"createVerticalHelper",
"(",
"layoutManager",
")",
";",
"}",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"invalid orientation\"",
")",
";",
"}"
] |
Creates an OrientationHelper for the given LayoutManager and orientation.
@param layoutManager LayoutManager to attach to
@param orientation Desired orientation. Should be {@link #HORIZONTAL} or {@link #VERTICAL}
@return A new OrientationHelper
|
[
"Creates",
"an",
"OrientationHelper",
"for",
"the",
"given",
"LayoutManager",
"and",
"orientation",
"."
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/OrientationHelperEx.java#L157-L166
|
13,333
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/OrientationHelperEx.java
|
OrientationHelperEx.createHorizontalHelper
|
public static OrientationHelperEx createHorizontalHelper(
ExposeLinearLayoutManagerEx layoutManager) {
return new OrientationHelperEx(layoutManager) {
@Override
public int getEndAfterPadding() {
return mLayoutManager.getWidth() - mLayoutManager.getPaddingRight();
}
@Override
public int getEnd() {
return mLayoutManager.getWidth();
}
@Override
public void offsetChildren(int amount) {
mLayoutManager.offsetChildrenHorizontal(amount);
}
@Override
public int getStartAfterPadding() {
return mLayoutManager.getPaddingLeft();
}
@Override
public int getDecoratedMeasurement(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return !mLayoutManager.isEnableMarginOverLap() ? mLayoutManager.getDecoratedMeasuredWidth(view) + params.leftMargin
+ params.rightMargin : mLayoutManager.getDecoratedMeasuredWidth(view);
}
@Override
public int getDecoratedMeasurementInOther(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return mLayoutManager.getDecoratedMeasuredHeight(view) + params.topMargin + params.bottomMargin;
}
@Override
public int getDecoratedEnd(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return !mLayoutManager.isEnableMarginOverLap() ? mLayoutManager.getDecoratedRight(view)
+ params.rightMargin : mLayoutManager.getDecoratedRight(view);
}
@Override
public int getDecoratedStart(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return !mLayoutManager.isEnableMarginOverLap() ? mLayoutManager.getDecoratedLeft(view)
- params.leftMargin : mLayoutManager.getDecoratedLeft(view);
}
@Override
public int getTotalSpace() {
return mLayoutManager.getWidth() - mLayoutManager.getPaddingLeft()
- mLayoutManager.getPaddingRight();
}
@Override
public void offsetChild(View view, int offset) {
view.offsetLeftAndRight(offset);
}
@Override
public int getEndPadding() {
return mLayoutManager.getPaddingRight();
}
};
}
|
java
|
public static OrientationHelperEx createHorizontalHelper(
ExposeLinearLayoutManagerEx layoutManager) {
return new OrientationHelperEx(layoutManager) {
@Override
public int getEndAfterPadding() {
return mLayoutManager.getWidth() - mLayoutManager.getPaddingRight();
}
@Override
public int getEnd() {
return mLayoutManager.getWidth();
}
@Override
public void offsetChildren(int amount) {
mLayoutManager.offsetChildrenHorizontal(amount);
}
@Override
public int getStartAfterPadding() {
return mLayoutManager.getPaddingLeft();
}
@Override
public int getDecoratedMeasurement(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return !mLayoutManager.isEnableMarginOverLap() ? mLayoutManager.getDecoratedMeasuredWidth(view) + params.leftMargin
+ params.rightMargin : mLayoutManager.getDecoratedMeasuredWidth(view);
}
@Override
public int getDecoratedMeasurementInOther(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return mLayoutManager.getDecoratedMeasuredHeight(view) + params.topMargin + params.bottomMargin;
}
@Override
public int getDecoratedEnd(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return !mLayoutManager.isEnableMarginOverLap() ? mLayoutManager.getDecoratedRight(view)
+ params.rightMargin : mLayoutManager.getDecoratedRight(view);
}
@Override
public int getDecoratedStart(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return !mLayoutManager.isEnableMarginOverLap() ? mLayoutManager.getDecoratedLeft(view)
- params.leftMargin : mLayoutManager.getDecoratedLeft(view);
}
@Override
public int getTotalSpace() {
return mLayoutManager.getWidth() - mLayoutManager.getPaddingLeft()
- mLayoutManager.getPaddingRight();
}
@Override
public void offsetChild(View view, int offset) {
view.offsetLeftAndRight(offset);
}
@Override
public int getEndPadding() {
return mLayoutManager.getPaddingRight();
}
};
}
|
[
"public",
"static",
"OrientationHelperEx",
"createHorizontalHelper",
"(",
"ExposeLinearLayoutManagerEx",
"layoutManager",
")",
"{",
"return",
"new",
"OrientationHelperEx",
"(",
"layoutManager",
")",
"{",
"@",
"Override",
"public",
"int",
"getEndAfterPadding",
"(",
")",
"{",
"return",
"mLayoutManager",
".",
"getWidth",
"(",
")",
"-",
"mLayoutManager",
".",
"getPaddingRight",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getEnd",
"(",
")",
"{",
"return",
"mLayoutManager",
".",
"getWidth",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"offsetChildren",
"(",
"int",
"amount",
")",
"{",
"mLayoutManager",
".",
"offsetChildrenHorizontal",
"(",
"amount",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getStartAfterPadding",
"(",
")",
"{",
"return",
"mLayoutManager",
".",
"getPaddingLeft",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getDecoratedMeasurement",
"(",
"View",
"view",
")",
"{",
"final",
"RecyclerView",
".",
"LayoutParams",
"params",
"=",
"(",
"RecyclerView",
".",
"LayoutParams",
")",
"view",
".",
"getLayoutParams",
"(",
")",
";",
"return",
"!",
"mLayoutManager",
".",
"isEnableMarginOverLap",
"(",
")",
"?",
"mLayoutManager",
".",
"getDecoratedMeasuredWidth",
"(",
"view",
")",
"+",
"params",
".",
"leftMargin",
"+",
"params",
".",
"rightMargin",
":",
"mLayoutManager",
".",
"getDecoratedMeasuredWidth",
"(",
"view",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getDecoratedMeasurementInOther",
"(",
"View",
"view",
")",
"{",
"final",
"RecyclerView",
".",
"LayoutParams",
"params",
"=",
"(",
"RecyclerView",
".",
"LayoutParams",
")",
"view",
".",
"getLayoutParams",
"(",
")",
";",
"return",
"mLayoutManager",
".",
"getDecoratedMeasuredHeight",
"(",
"view",
")",
"+",
"params",
".",
"topMargin",
"+",
"params",
".",
"bottomMargin",
";",
"}",
"@",
"Override",
"public",
"int",
"getDecoratedEnd",
"(",
"View",
"view",
")",
"{",
"final",
"RecyclerView",
".",
"LayoutParams",
"params",
"=",
"(",
"RecyclerView",
".",
"LayoutParams",
")",
"view",
".",
"getLayoutParams",
"(",
")",
";",
"return",
"!",
"mLayoutManager",
".",
"isEnableMarginOverLap",
"(",
")",
"?",
"mLayoutManager",
".",
"getDecoratedRight",
"(",
"view",
")",
"+",
"params",
".",
"rightMargin",
":",
"mLayoutManager",
".",
"getDecoratedRight",
"(",
"view",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getDecoratedStart",
"(",
"View",
"view",
")",
"{",
"final",
"RecyclerView",
".",
"LayoutParams",
"params",
"=",
"(",
"RecyclerView",
".",
"LayoutParams",
")",
"view",
".",
"getLayoutParams",
"(",
")",
";",
"return",
"!",
"mLayoutManager",
".",
"isEnableMarginOverLap",
"(",
")",
"?",
"mLayoutManager",
".",
"getDecoratedLeft",
"(",
"view",
")",
"-",
"params",
".",
"leftMargin",
":",
"mLayoutManager",
".",
"getDecoratedLeft",
"(",
"view",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getTotalSpace",
"(",
")",
"{",
"return",
"mLayoutManager",
".",
"getWidth",
"(",
")",
"-",
"mLayoutManager",
".",
"getPaddingLeft",
"(",
")",
"-",
"mLayoutManager",
".",
"getPaddingRight",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"offsetChild",
"(",
"View",
"view",
",",
"int",
"offset",
")",
"{",
"view",
".",
"offsetLeftAndRight",
"(",
"offset",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getEndPadding",
"(",
")",
"{",
"return",
"mLayoutManager",
".",
"getPaddingRight",
"(",
")",
";",
"}",
"}",
";",
"}"
] |
Creates a horizontal OrientationHelper for the given LayoutManager.
@param layoutManager The LayoutManager to attach to.
@return A new OrientationHelper
|
[
"Creates",
"a",
"horizontal",
"OrientationHelper",
"for",
"the",
"given",
"LayoutManager",
"."
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/OrientationHelperEx.java#L174-L244
|
13,334
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/OrientationHelperEx.java
|
OrientationHelperEx.createVerticalHelper
|
public static OrientationHelperEx createVerticalHelper(ExposeLinearLayoutManagerEx layoutManager) {
return new OrientationHelperEx(layoutManager) {
@Override
public int getEndAfterPadding() {
return mLayoutManager.getHeight() - mLayoutManager.getPaddingBottom();
}
@Override
public int getEnd() {
return mLayoutManager.getHeight();
}
@Override
public void offsetChildren(int amount) {
mLayoutManager.offsetChildrenVertical(amount);
}
@Override
public int getStartAfterPadding() {
return mLayoutManager.getPaddingTop();
}
@Override
public int getDecoratedMeasurement(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return !mLayoutManager.isEnableMarginOverLap() ? mLayoutManager.getDecoratedMeasuredHeight(view) + params.topMargin
+ params.bottomMargin : mLayoutManager.getDecoratedMeasuredHeight(view);
}
@Override
public int getDecoratedMeasurementInOther(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return mLayoutManager.getDecoratedMeasuredWidth(view) + params.leftMargin + params.rightMargin ;
}
@Override
public int getDecoratedEnd(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return !mLayoutManager.isEnableMarginOverLap() ? mLayoutManager.getDecoratedBottom(view)
+ params.bottomMargin : mLayoutManager.getDecoratedBottom(view);
}
@Override
public int getDecoratedStart(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return !mLayoutManager.isEnableMarginOverLap() ? mLayoutManager.getDecoratedTop(view) - params.topMargin
: mLayoutManager.getDecoratedTop(view);
}
@Override
public int getTotalSpace() {
return mLayoutManager.getHeight() - mLayoutManager.getPaddingTop()
- mLayoutManager.getPaddingBottom();
}
@Override
public void offsetChild(View view, int offset) {
view.offsetTopAndBottom(offset);
}
@Override
public int getEndPadding() {
return mLayoutManager.getPaddingBottom();
}
};
}
|
java
|
public static OrientationHelperEx createVerticalHelper(ExposeLinearLayoutManagerEx layoutManager) {
return new OrientationHelperEx(layoutManager) {
@Override
public int getEndAfterPadding() {
return mLayoutManager.getHeight() - mLayoutManager.getPaddingBottom();
}
@Override
public int getEnd() {
return mLayoutManager.getHeight();
}
@Override
public void offsetChildren(int amount) {
mLayoutManager.offsetChildrenVertical(amount);
}
@Override
public int getStartAfterPadding() {
return mLayoutManager.getPaddingTop();
}
@Override
public int getDecoratedMeasurement(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return !mLayoutManager.isEnableMarginOverLap() ? mLayoutManager.getDecoratedMeasuredHeight(view) + params.topMargin
+ params.bottomMargin : mLayoutManager.getDecoratedMeasuredHeight(view);
}
@Override
public int getDecoratedMeasurementInOther(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return mLayoutManager.getDecoratedMeasuredWidth(view) + params.leftMargin + params.rightMargin ;
}
@Override
public int getDecoratedEnd(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return !mLayoutManager.isEnableMarginOverLap() ? mLayoutManager.getDecoratedBottom(view)
+ params.bottomMargin : mLayoutManager.getDecoratedBottom(view);
}
@Override
public int getDecoratedStart(View view) {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)
view.getLayoutParams();
return !mLayoutManager.isEnableMarginOverLap() ? mLayoutManager.getDecoratedTop(view) - params.topMargin
: mLayoutManager.getDecoratedTop(view);
}
@Override
public int getTotalSpace() {
return mLayoutManager.getHeight() - mLayoutManager.getPaddingTop()
- mLayoutManager.getPaddingBottom();
}
@Override
public void offsetChild(View view, int offset) {
view.offsetTopAndBottom(offset);
}
@Override
public int getEndPadding() {
return mLayoutManager.getPaddingBottom();
}
};
}
|
[
"public",
"static",
"OrientationHelperEx",
"createVerticalHelper",
"(",
"ExposeLinearLayoutManagerEx",
"layoutManager",
")",
"{",
"return",
"new",
"OrientationHelperEx",
"(",
"layoutManager",
")",
"{",
"@",
"Override",
"public",
"int",
"getEndAfterPadding",
"(",
")",
"{",
"return",
"mLayoutManager",
".",
"getHeight",
"(",
")",
"-",
"mLayoutManager",
".",
"getPaddingBottom",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getEnd",
"(",
")",
"{",
"return",
"mLayoutManager",
".",
"getHeight",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"offsetChildren",
"(",
"int",
"amount",
")",
"{",
"mLayoutManager",
".",
"offsetChildrenVertical",
"(",
"amount",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getStartAfterPadding",
"(",
")",
"{",
"return",
"mLayoutManager",
".",
"getPaddingTop",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getDecoratedMeasurement",
"(",
"View",
"view",
")",
"{",
"final",
"RecyclerView",
".",
"LayoutParams",
"params",
"=",
"(",
"RecyclerView",
".",
"LayoutParams",
")",
"view",
".",
"getLayoutParams",
"(",
")",
";",
"return",
"!",
"mLayoutManager",
".",
"isEnableMarginOverLap",
"(",
")",
"?",
"mLayoutManager",
".",
"getDecoratedMeasuredHeight",
"(",
"view",
")",
"+",
"params",
".",
"topMargin",
"+",
"params",
".",
"bottomMargin",
":",
"mLayoutManager",
".",
"getDecoratedMeasuredHeight",
"(",
"view",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getDecoratedMeasurementInOther",
"(",
"View",
"view",
")",
"{",
"final",
"RecyclerView",
".",
"LayoutParams",
"params",
"=",
"(",
"RecyclerView",
".",
"LayoutParams",
")",
"view",
".",
"getLayoutParams",
"(",
")",
";",
"return",
"mLayoutManager",
".",
"getDecoratedMeasuredWidth",
"(",
"view",
")",
"+",
"params",
".",
"leftMargin",
"+",
"params",
".",
"rightMargin",
";",
"}",
"@",
"Override",
"public",
"int",
"getDecoratedEnd",
"(",
"View",
"view",
")",
"{",
"final",
"RecyclerView",
".",
"LayoutParams",
"params",
"=",
"(",
"RecyclerView",
".",
"LayoutParams",
")",
"view",
".",
"getLayoutParams",
"(",
")",
";",
"return",
"!",
"mLayoutManager",
".",
"isEnableMarginOverLap",
"(",
")",
"?",
"mLayoutManager",
".",
"getDecoratedBottom",
"(",
"view",
")",
"+",
"params",
".",
"bottomMargin",
":",
"mLayoutManager",
".",
"getDecoratedBottom",
"(",
"view",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getDecoratedStart",
"(",
"View",
"view",
")",
"{",
"final",
"RecyclerView",
".",
"LayoutParams",
"params",
"=",
"(",
"RecyclerView",
".",
"LayoutParams",
")",
"view",
".",
"getLayoutParams",
"(",
")",
";",
"return",
"!",
"mLayoutManager",
".",
"isEnableMarginOverLap",
"(",
")",
"?",
"mLayoutManager",
".",
"getDecoratedTop",
"(",
"view",
")",
"-",
"params",
".",
"topMargin",
":",
"mLayoutManager",
".",
"getDecoratedTop",
"(",
"view",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getTotalSpace",
"(",
")",
"{",
"return",
"mLayoutManager",
".",
"getHeight",
"(",
")",
"-",
"mLayoutManager",
".",
"getPaddingTop",
"(",
")",
"-",
"mLayoutManager",
".",
"getPaddingBottom",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"offsetChild",
"(",
"View",
"view",
",",
"int",
"offset",
")",
"{",
"view",
".",
"offsetTopAndBottom",
"(",
"offset",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getEndPadding",
"(",
")",
"{",
"return",
"mLayoutManager",
".",
"getPaddingBottom",
"(",
")",
";",
"}",
"}",
";",
"}"
] |
Creates a vertical OrientationHelper for the given LayoutManager.
@param layoutManager The LayoutManager to attach to.
@return A new OrientationHelper
|
[
"Creates",
"a",
"vertical",
"OrientationHelper",
"for",
"the",
"given",
"LayoutManager",
"."
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/OrientationHelperEx.java#L252-L321
|
13,335
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/layout/BaseLayoutHelper.java
|
BaseLayoutHelper.nextView
|
@Nullable
public final View nextView(RecyclerView.Recycler recycler, LayoutStateWrapper layoutState, LayoutManagerHelper helper, LayoutChunkResult result) {
View view = layoutState.next(recycler);
if (view == null) {
// if we are laying out views in scrap, this may return null which means there is
// no more items to layout.
if (DEBUG && !layoutState.hasScrapList()) {
throw new RuntimeException("received null view when unexpected");
}
// if there is no more views can be retrieved, this layout process is finished
result.mFinished = true;
return null;
}
helper.addChildView(layoutState, view);
return view;
}
|
java
|
@Nullable
public final View nextView(RecyclerView.Recycler recycler, LayoutStateWrapper layoutState, LayoutManagerHelper helper, LayoutChunkResult result) {
View view = layoutState.next(recycler);
if (view == null) {
// if we are laying out views in scrap, this may return null which means there is
// no more items to layout.
if (DEBUG && !layoutState.hasScrapList()) {
throw new RuntimeException("received null view when unexpected");
}
// if there is no more views can be retrieved, this layout process is finished
result.mFinished = true;
return null;
}
helper.addChildView(layoutState, view);
return view;
}
|
[
"@",
"Nullable",
"public",
"final",
"View",
"nextView",
"(",
"RecyclerView",
".",
"Recycler",
"recycler",
",",
"LayoutStateWrapper",
"layoutState",
",",
"LayoutManagerHelper",
"helper",
",",
"LayoutChunkResult",
"result",
")",
"{",
"View",
"view",
"=",
"layoutState",
".",
"next",
"(",
"recycler",
")",
";",
"if",
"(",
"view",
"==",
"null",
")",
"{",
"// if we are laying out views in scrap, this may return null which means there is",
"// no more items to layout.",
"if",
"(",
"DEBUG",
"&&",
"!",
"layoutState",
".",
"hasScrapList",
"(",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"received null view when unexpected\"",
")",
";",
"}",
"// if there is no more views can be retrieved, this layout process is finished",
"result",
".",
"mFinished",
"=",
"true",
";",
"return",
"null",
";",
"}",
"helper",
".",
"addChildView",
"(",
"layoutState",
",",
"view",
")",
";",
"return",
"view",
";",
"}"
] |
Retrieve next view and add it into layout, this is to make sure that view are added by order
@param recycler recycler generate views
@param layoutState current layout state
@param helper helper to add views
@param result chunk result to tell layoutManager whether layout process goes end
@return next view to render, null if no more view available
|
[
"Retrieve",
"next",
"view",
"and",
"add",
"it",
"into",
"layout",
"this",
"is",
"to",
"make",
"sure",
"that",
"view",
"are",
"added",
"by",
"order"
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/layout/BaseLayoutHelper.java#L114-L130
|
13,336
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/layout/BaseLayoutHelper.java
|
BaseLayoutHelper.handleStateOnResult
|
protected void handleStateOnResult(LayoutChunkResult result, View[] views) {
if (views == null) return;
for (int i = 0; i < views.length; i++) {
View view = views[i];
if (view == null) {
continue;
}
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
// Consume the available space if the view is not removed OR changed
if (params.isItemRemoved() || params.isItemChanged()) {
result.mIgnoreConsumed = true;
}
// used when search a focusable view
result.mFocusable = result.mFocusable || view.isFocusable();
if (result.mFocusable && result.mIgnoreConsumed) {
break;
}
}
}
|
java
|
protected void handleStateOnResult(LayoutChunkResult result, View[] views) {
if (views == null) return;
for (int i = 0; i < views.length; i++) {
View view = views[i];
if (view == null) {
continue;
}
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
// Consume the available space if the view is not removed OR changed
if (params.isItemRemoved() || params.isItemChanged()) {
result.mIgnoreConsumed = true;
}
// used when search a focusable view
result.mFocusable = result.mFocusable || view.isFocusable();
if (result.mFocusable && result.mIgnoreConsumed) {
break;
}
}
}
|
[
"protected",
"void",
"handleStateOnResult",
"(",
"LayoutChunkResult",
"result",
",",
"View",
"[",
"]",
"views",
")",
"{",
"if",
"(",
"views",
"==",
"null",
")",
"return",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"views",
".",
"length",
";",
"i",
"++",
")",
"{",
"View",
"view",
"=",
"views",
"[",
"i",
"]",
";",
"if",
"(",
"view",
"==",
"null",
")",
"{",
"continue",
";",
"}",
"RecyclerView",
".",
"LayoutParams",
"params",
"=",
"(",
"RecyclerView",
".",
"LayoutParams",
")",
"view",
".",
"getLayoutParams",
"(",
")",
";",
"// Consume the available space if the view is not removed OR changed",
"if",
"(",
"params",
".",
"isItemRemoved",
"(",
")",
"||",
"params",
".",
"isItemChanged",
"(",
")",
")",
"{",
"result",
".",
"mIgnoreConsumed",
"=",
"true",
";",
"}",
"// used when search a focusable view",
"result",
".",
"mFocusable",
"=",
"result",
".",
"mFocusable",
"||",
"view",
".",
"isFocusable",
"(",
")",
";",
"if",
"(",
"result",
".",
"mFocusable",
"&&",
"result",
".",
"mIgnoreConsumed",
")",
"{",
"break",
";",
"}",
"}",
"}"
] |
Helper methods to handle focus states for views
@param result
@param views
|
[
"Helper",
"methods",
"to",
"handle",
"focus",
"states",
"for",
"views"
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/layout/BaseLayoutHelper.java#L513-L535
|
13,337
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/RecyclablePagerAdapter.java
|
RecyclablePagerAdapter.instantiateItem
|
@Override
public Object instantiateItem(ViewGroup container, int position) {
int itemViewType = getItemViewType(position);
RecyclerView.ViewHolder holder = mRecycledViewPool.getRecycledView(itemViewType);
if (holder == null) {
holder = mAdapter.createViewHolder(container, itemViewType);
}
onBindViewHolder((VH) holder, position);
//itemViews' layoutParam will be reused when there are more than one nested ViewPager in one page,
//so the attributes of layoutParam such as widthFactor and position will also be reused,
//while these attributes should be reset to default value during reused.
//Considering ViewPager.LayoutParams has a few inner attributes which could not be modify outside, we provide a new instance here
container.addView(holder.itemView, new ViewPager.LayoutParams());
return holder;
}
|
java
|
@Override
public Object instantiateItem(ViewGroup container, int position) {
int itemViewType = getItemViewType(position);
RecyclerView.ViewHolder holder = mRecycledViewPool.getRecycledView(itemViewType);
if (holder == null) {
holder = mAdapter.createViewHolder(container, itemViewType);
}
onBindViewHolder((VH) holder, position);
//itemViews' layoutParam will be reused when there are more than one nested ViewPager in one page,
//so the attributes of layoutParam such as widthFactor and position will also be reused,
//while these attributes should be reset to default value during reused.
//Considering ViewPager.LayoutParams has a few inner attributes which could not be modify outside, we provide a new instance here
container.addView(holder.itemView, new ViewPager.LayoutParams());
return holder;
}
|
[
"@",
"Override",
"public",
"Object",
"instantiateItem",
"(",
"ViewGroup",
"container",
",",
"int",
"position",
")",
"{",
"int",
"itemViewType",
"=",
"getItemViewType",
"(",
"position",
")",
";",
"RecyclerView",
".",
"ViewHolder",
"holder",
"=",
"mRecycledViewPool",
".",
"getRecycledView",
"(",
"itemViewType",
")",
";",
"if",
"(",
"holder",
"==",
"null",
")",
"{",
"holder",
"=",
"mAdapter",
".",
"createViewHolder",
"(",
"container",
",",
"itemViewType",
")",
";",
"}",
"onBindViewHolder",
"(",
"(",
"VH",
")",
"holder",
",",
"position",
")",
";",
"//itemViews' layoutParam will be reused when there are more than one nested ViewPager in one page,",
"//so the attributes of layoutParam such as widthFactor and position will also be reused,",
"//while these attributes should be reset to default value during reused.",
"//Considering ViewPager.LayoutParams has a few inner attributes which could not be modify outside, we provide a new instance here",
"container",
".",
"addView",
"(",
"holder",
".",
"itemView",
",",
"new",
"ViewPager",
".",
"LayoutParams",
"(",
")",
")",
";",
"return",
"holder",
";",
"}"
] |
Get view from position
@param container
@param position
@return
|
[
"Get",
"view",
"from",
"position"
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/RecyclablePagerAdapter.java#L69-L87
|
13,338
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/SortedList.java
|
SortedList.endBatchedUpdates
|
public void endBatchedUpdates() {
if (mCallback instanceof BatchedCallback) {
((BatchedCallback) mCallback).dispatchLastEvent();
}
if (mCallback == mBatchedCallback) {
mCallback = mBatchedCallback.mWrappedCallback;
}
}
|
java
|
public void endBatchedUpdates() {
if (mCallback instanceof BatchedCallback) {
((BatchedCallback) mCallback).dispatchLastEvent();
}
if (mCallback == mBatchedCallback) {
mCallback = mBatchedCallback.mWrappedCallback;
}
}
|
[
"public",
"void",
"endBatchedUpdates",
"(",
")",
"{",
"if",
"(",
"mCallback",
"instanceof",
"BatchedCallback",
")",
"{",
"(",
"(",
"BatchedCallback",
")",
"mCallback",
")",
".",
"dispatchLastEvent",
"(",
")",
";",
"}",
"if",
"(",
"mCallback",
"==",
"mBatchedCallback",
")",
"{",
"mCallback",
"=",
"mBatchedCallback",
".",
"mWrappedCallback",
";",
"}",
"}"
] |
Ends the update transaction and dispatches any remaining event to the callback.
|
[
"Ends",
"the",
"update",
"transaction",
"and",
"dispatches",
"any",
"remaining",
"event",
"to",
"the",
"callback",
"."
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/SortedList.java#L174-L181
|
13,339
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/SortedList.java
|
SortedList.get
|
public T get(int index) throws IndexOutOfBoundsException {
if (index >= mSize || index < 0) {
throw new IndexOutOfBoundsException("Asked to get item at " + index + " but size is "
+ mSize);
}
return mData[index];
}
|
java
|
public T get(int index) throws IndexOutOfBoundsException {
if (index >= mSize || index < 0) {
throw new IndexOutOfBoundsException("Asked to get item at " + index + " but size is "
+ mSize);
}
return mData[index];
}
|
[
"public",
"T",
"get",
"(",
"int",
"index",
")",
"throws",
"IndexOutOfBoundsException",
"{",
"if",
"(",
"index",
">=",
"mSize",
"||",
"index",
"<",
"0",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
"\"Asked to get item at \"",
"+",
"index",
"+",
"\" but size is \"",
"+",
"mSize",
")",
";",
"}",
"return",
"mData",
"[",
"index",
"]",
";",
"}"
] |
Returns the item at the given index.
@param index The index of the item to retrieve.
@return The item at the given index.
@throws java.lang.IndexOutOfBoundsException if provided index is negative or larger than the
size of the list.
|
[
"Returns",
"the",
"item",
"at",
"the",
"given",
"index",
"."
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/SortedList.java#L339-L345
|
13,340
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/layout/StaggeredGridLayoutHelper.java
|
StaggeredGridLayoutHelper.getNextSpan
|
private Span getNextSpan(int defaultLine, LayoutStateWrapper layoutState, LayoutManagerHelper helper) {
OrientationHelperEx orientationHelper = helper.getMainOrientationHelper();
boolean preferLastSpan = false;
if (helper.getOrientation() == HORIZONTAL) {
preferLastSpan = (layoutState.getLayoutDirection() == LAYOUT_START) != helper.getReverseLayout();
} else {
preferLastSpan = ((layoutState.getLayoutDirection() == LAYOUT_START) == helper.getReverseLayout()) == helper.isDoLayoutRTL();
}
final int startIndex, endIndex, diff;
if (preferLastSpan) {
startIndex = mNumLanes - 1;
endIndex = -1;
diff = -1;
} else {
startIndex = 0;
endIndex = mNumLanes;
diff = 1;
}
if (layoutState.getLayoutDirection() == LAYOUT_END) {
Span min = null;
int minLine = Integer.MAX_VALUE;
for (int i = startIndex; i != endIndex; i += diff) {
final Span other = mSpans[i];
int otherLine = other.getEndLine(defaultLine, orientationHelper);
if (BuildConfig.DEBUG) {
Log.d(TAG, "end starIndex " + i + " end otherLine " + otherLine);
}
if (otherLine < minLine) {
min = other;
minLine = otherLine;
}
if (BuildConfig.DEBUG) {
Log.d(TAG, "end min " + min + " end minLine " + minLine);
}
}
if (BuildConfig.DEBUG) {
Log.d(TAG, "final end min " + min + " final end minLine " + minLine);
}
return min;
} else {
Span max = null;
int maxLine = Integer.MIN_VALUE;
for (int i = startIndex; i != endIndex; i += diff) {
final Span other = mSpans[i];
int otherLine = other.getStartLine(defaultLine, orientationHelper);
if (BuildConfig.DEBUG) {
Log.d(TAG, "start starIndex " + i + " start otherLine " + otherLine);
}
if (otherLine > maxLine) {
max = other;
maxLine = otherLine;
}
if (BuildConfig.DEBUG) {
Log.d(TAG, "start max " + max + " start maxLine " + maxLine);
}
}
if (BuildConfig.DEBUG) {
Log.d(TAG, "final start max " + max + " final start maxLine " + maxLine);
}
return max;
}
}
|
java
|
private Span getNextSpan(int defaultLine, LayoutStateWrapper layoutState, LayoutManagerHelper helper) {
OrientationHelperEx orientationHelper = helper.getMainOrientationHelper();
boolean preferLastSpan = false;
if (helper.getOrientation() == HORIZONTAL) {
preferLastSpan = (layoutState.getLayoutDirection() == LAYOUT_START) != helper.getReverseLayout();
} else {
preferLastSpan = ((layoutState.getLayoutDirection() == LAYOUT_START) == helper.getReverseLayout()) == helper.isDoLayoutRTL();
}
final int startIndex, endIndex, diff;
if (preferLastSpan) {
startIndex = mNumLanes - 1;
endIndex = -1;
diff = -1;
} else {
startIndex = 0;
endIndex = mNumLanes;
diff = 1;
}
if (layoutState.getLayoutDirection() == LAYOUT_END) {
Span min = null;
int minLine = Integer.MAX_VALUE;
for (int i = startIndex; i != endIndex; i += diff) {
final Span other = mSpans[i];
int otherLine = other.getEndLine(defaultLine, orientationHelper);
if (BuildConfig.DEBUG) {
Log.d(TAG, "end starIndex " + i + " end otherLine " + otherLine);
}
if (otherLine < minLine) {
min = other;
minLine = otherLine;
}
if (BuildConfig.DEBUG) {
Log.d(TAG, "end min " + min + " end minLine " + minLine);
}
}
if (BuildConfig.DEBUG) {
Log.d(TAG, "final end min " + min + " final end minLine " + minLine);
}
return min;
} else {
Span max = null;
int maxLine = Integer.MIN_VALUE;
for (int i = startIndex; i != endIndex; i += diff) {
final Span other = mSpans[i];
int otherLine = other.getStartLine(defaultLine, orientationHelper);
if (BuildConfig.DEBUG) {
Log.d(TAG, "start starIndex " + i + " start otherLine " + otherLine);
}
if (otherLine > maxLine) {
max = other;
maxLine = otherLine;
}
if (BuildConfig.DEBUG) {
Log.d(TAG, "start max " + max + " start maxLine " + maxLine);
}
}
if (BuildConfig.DEBUG) {
Log.d(TAG, "final start max " + max + " final start maxLine " + maxLine);
}
return max;
}
}
|
[
"private",
"Span",
"getNextSpan",
"(",
"int",
"defaultLine",
",",
"LayoutStateWrapper",
"layoutState",
",",
"LayoutManagerHelper",
"helper",
")",
"{",
"OrientationHelperEx",
"orientationHelper",
"=",
"helper",
".",
"getMainOrientationHelper",
"(",
")",
";",
"boolean",
"preferLastSpan",
"=",
"false",
";",
"if",
"(",
"helper",
".",
"getOrientation",
"(",
")",
"==",
"HORIZONTAL",
")",
"{",
"preferLastSpan",
"=",
"(",
"layoutState",
".",
"getLayoutDirection",
"(",
")",
"==",
"LAYOUT_START",
")",
"!=",
"helper",
".",
"getReverseLayout",
"(",
")",
";",
"}",
"else",
"{",
"preferLastSpan",
"=",
"(",
"(",
"layoutState",
".",
"getLayoutDirection",
"(",
")",
"==",
"LAYOUT_START",
")",
"==",
"helper",
".",
"getReverseLayout",
"(",
")",
")",
"==",
"helper",
".",
"isDoLayoutRTL",
"(",
")",
";",
"}",
"final",
"int",
"startIndex",
",",
"endIndex",
",",
"diff",
";",
"if",
"(",
"preferLastSpan",
")",
"{",
"startIndex",
"=",
"mNumLanes",
"-",
"1",
";",
"endIndex",
"=",
"-",
"1",
";",
"diff",
"=",
"-",
"1",
";",
"}",
"else",
"{",
"startIndex",
"=",
"0",
";",
"endIndex",
"=",
"mNumLanes",
";",
"diff",
"=",
"1",
";",
"}",
"if",
"(",
"layoutState",
".",
"getLayoutDirection",
"(",
")",
"==",
"LAYOUT_END",
")",
"{",
"Span",
"min",
"=",
"null",
";",
"int",
"minLine",
"=",
"Integer",
".",
"MAX_VALUE",
";",
"for",
"(",
"int",
"i",
"=",
"startIndex",
";",
"i",
"!=",
"endIndex",
";",
"i",
"+=",
"diff",
")",
"{",
"final",
"Span",
"other",
"=",
"mSpans",
"[",
"i",
"]",
";",
"int",
"otherLine",
"=",
"other",
".",
"getEndLine",
"(",
"defaultLine",
",",
"orientationHelper",
")",
";",
"if",
"(",
"BuildConfig",
".",
"DEBUG",
")",
"{",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"end starIndex \"",
"+",
"i",
"+",
"\" end otherLine \"",
"+",
"otherLine",
")",
";",
"}",
"if",
"(",
"otherLine",
"<",
"minLine",
")",
"{",
"min",
"=",
"other",
";",
"minLine",
"=",
"otherLine",
";",
"}",
"if",
"(",
"BuildConfig",
".",
"DEBUG",
")",
"{",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"end min \"",
"+",
"min",
"+",
"\" end minLine \"",
"+",
"minLine",
")",
";",
"}",
"}",
"if",
"(",
"BuildConfig",
".",
"DEBUG",
")",
"{",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"final end min \"",
"+",
"min",
"+",
"\" final end minLine \"",
"+",
"minLine",
")",
";",
"}",
"return",
"min",
";",
"}",
"else",
"{",
"Span",
"max",
"=",
"null",
";",
"int",
"maxLine",
"=",
"Integer",
".",
"MIN_VALUE",
";",
"for",
"(",
"int",
"i",
"=",
"startIndex",
";",
"i",
"!=",
"endIndex",
";",
"i",
"+=",
"diff",
")",
"{",
"final",
"Span",
"other",
"=",
"mSpans",
"[",
"i",
"]",
";",
"int",
"otherLine",
"=",
"other",
".",
"getStartLine",
"(",
"defaultLine",
",",
"orientationHelper",
")",
";",
"if",
"(",
"BuildConfig",
".",
"DEBUG",
")",
"{",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"start starIndex \"",
"+",
"i",
"+",
"\" start otherLine \"",
"+",
"otherLine",
")",
";",
"}",
"if",
"(",
"otherLine",
">",
"maxLine",
")",
"{",
"max",
"=",
"other",
";",
"maxLine",
"=",
"otherLine",
";",
"}",
"if",
"(",
"BuildConfig",
".",
"DEBUG",
")",
"{",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"start max \"",
"+",
"max",
"+",
"\" start maxLine \"",
"+",
"maxLine",
")",
";",
"}",
"}",
"if",
"(",
"BuildConfig",
".",
"DEBUG",
")",
"{",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"final start max \"",
"+",
"max",
"+",
"\" final start maxLine \"",
"+",
"maxLine",
")",
";",
"}",
"return",
"max",
";",
"}",
"}"
] |
Finds the span for the next view.
|
[
"Finds",
"the",
"span",
"for",
"the",
"next",
"view",
"."
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/layout/StaggeredGridLayoutHelper.java#L812-L876
|
13,341
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/ExposeLinearLayoutManagerEx.java
|
ExposeLinearLayoutManagerEx.scrollInternalBy
|
protected int scrollInternalBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
if (getChildCount() == 0 || dy == 0) {
return 0;
}
// indicate whether need recycle in this pass, true when scrolling, false when layout
mLayoutState.mRecycle = true;
ensureLayoutStateExpose();
final int layoutDirection = dy > 0 ? LayoutState.LAYOUT_END : LayoutState.LAYOUT_START;
final int absDy = Math.abs(dy);
updateLayoutStateExpose(layoutDirection, absDy, true, state);
final int freeScroll = mLayoutState.mScrollingOffset;
mLayoutState.mOnRefresLayout = false;
final int consumed = freeScroll + fill(recycler, mLayoutState, state, false);
if (consumed < 0) {
if (DEBUG) {
Log.d(TAG, "Don't have any more elements to scroll");
}
return 0;
}
final int scrolled = absDy > consumed ? layoutDirection * consumed : dy;
mOrientationHelper.offsetChildren(-scrolled);
if (DEBUG) {
Log.d(TAG, "scroll req: " + dy + " scrolled: " + scrolled);
}
return scrolled;
}
|
java
|
protected int scrollInternalBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
if (getChildCount() == 0 || dy == 0) {
return 0;
}
// indicate whether need recycle in this pass, true when scrolling, false when layout
mLayoutState.mRecycle = true;
ensureLayoutStateExpose();
final int layoutDirection = dy > 0 ? LayoutState.LAYOUT_END : LayoutState.LAYOUT_START;
final int absDy = Math.abs(dy);
updateLayoutStateExpose(layoutDirection, absDy, true, state);
final int freeScroll = mLayoutState.mScrollingOffset;
mLayoutState.mOnRefresLayout = false;
final int consumed = freeScroll + fill(recycler, mLayoutState, state, false);
if (consumed < 0) {
if (DEBUG) {
Log.d(TAG, "Don't have any more elements to scroll");
}
return 0;
}
final int scrolled = absDy > consumed ? layoutDirection * consumed : dy;
mOrientationHelper.offsetChildren(-scrolled);
if (DEBUG) {
Log.d(TAG, "scroll req: " + dy + " scrolled: " + scrolled);
}
return scrolled;
}
|
[
"protected",
"int",
"scrollInternalBy",
"(",
"int",
"dy",
",",
"RecyclerView",
".",
"Recycler",
"recycler",
",",
"RecyclerView",
".",
"State",
"state",
")",
"{",
"if",
"(",
"getChildCount",
"(",
")",
"==",
"0",
"||",
"dy",
"==",
"0",
")",
"{",
"return",
"0",
";",
"}",
"// indicate whether need recycle in this pass, true when scrolling, false when layout",
"mLayoutState",
".",
"mRecycle",
"=",
"true",
";",
"ensureLayoutStateExpose",
"(",
")",
";",
"final",
"int",
"layoutDirection",
"=",
"dy",
">",
"0",
"?",
"LayoutState",
".",
"LAYOUT_END",
":",
"LayoutState",
".",
"LAYOUT_START",
";",
"final",
"int",
"absDy",
"=",
"Math",
".",
"abs",
"(",
"dy",
")",
";",
"updateLayoutStateExpose",
"(",
"layoutDirection",
",",
"absDy",
",",
"true",
",",
"state",
")",
";",
"final",
"int",
"freeScroll",
"=",
"mLayoutState",
".",
"mScrollingOffset",
";",
"mLayoutState",
".",
"mOnRefresLayout",
"=",
"false",
";",
"final",
"int",
"consumed",
"=",
"freeScroll",
"+",
"fill",
"(",
"recycler",
",",
"mLayoutState",
",",
"state",
",",
"false",
")",
";",
"if",
"(",
"consumed",
"<",
"0",
")",
"{",
"if",
"(",
"DEBUG",
")",
"{",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"Don't have any more elements to scroll\"",
")",
";",
"}",
"return",
"0",
";",
"}",
"final",
"int",
"scrolled",
"=",
"absDy",
">",
"consumed",
"?",
"layoutDirection",
"*",
"consumed",
":",
"dy",
";",
"mOrientationHelper",
".",
"offsetChildren",
"(",
"-",
"scrolled",
")",
";",
"if",
"(",
"DEBUG",
")",
"{",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"scroll req: \"",
"+",
"dy",
"+",
"\" scrolled: \"",
"+",
"scrolled",
")",
";",
"}",
"return",
"scrolled",
";",
"}"
] |
Handle scroll event internally, cover both horizontal and vertical
@param dy Pixel that will be scrolled
@param recycler Recycler hold recycled views
@param state Current {@link RecyclerView} state, hold whether in preLayout, etc.
@return The actual scrolled pixel, it may not be the same as {@code dy}, like when reaching the edge of view
|
[
"Handle",
"scroll",
"event",
"internally",
"cover",
"both",
"horizontal",
"and",
"vertical"
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/ExposeLinearLayoutManagerEx.java#L970-L1000
|
13,342
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/ExposeLinearLayoutManagerEx.java
|
ExposeLinearLayoutManagerEx.recycleChildren
|
protected void recycleChildren(RecyclerView.Recycler recycler, int startIndex, int endIndex) {
if (startIndex == endIndex) {
return;
}
if (DEBUG) {
Log.d(TAG, "Recycling " + Math.abs(startIndex - endIndex) + " items");
}
if (endIndex > startIndex) {
for (int i = endIndex - 1; i >= startIndex; i--) {
removeAndRecycleViewAt(i, recycler);
}
} else {
for (int i = startIndex; i > endIndex; i--) {
removeAndRecycleViewAt(i, recycler);
}
}
}
|
java
|
protected void recycleChildren(RecyclerView.Recycler recycler, int startIndex, int endIndex) {
if (startIndex == endIndex) {
return;
}
if (DEBUG) {
Log.d(TAG, "Recycling " + Math.abs(startIndex - endIndex) + " items");
}
if (endIndex > startIndex) {
for (int i = endIndex - 1; i >= startIndex; i--) {
removeAndRecycleViewAt(i, recycler);
}
} else {
for (int i = startIndex; i > endIndex; i--) {
removeAndRecycleViewAt(i, recycler);
}
}
}
|
[
"protected",
"void",
"recycleChildren",
"(",
"RecyclerView",
".",
"Recycler",
"recycler",
",",
"int",
"startIndex",
",",
"int",
"endIndex",
")",
"{",
"if",
"(",
"startIndex",
"==",
"endIndex",
")",
"{",
"return",
";",
"}",
"if",
"(",
"DEBUG",
")",
"{",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"Recycling \"",
"+",
"Math",
".",
"abs",
"(",
"startIndex",
"-",
"endIndex",
")",
"+",
"\" items\"",
")",
";",
"}",
"if",
"(",
"endIndex",
">",
"startIndex",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"endIndex",
"-",
"1",
";",
"i",
">=",
"startIndex",
";",
"i",
"--",
")",
"{",
"removeAndRecycleViewAt",
"(",
"i",
",",
"recycler",
")",
";",
"}",
"}",
"else",
"{",
"for",
"(",
"int",
"i",
"=",
"startIndex",
";",
"i",
">",
"endIndex",
";",
"i",
"--",
")",
"{",
"removeAndRecycleViewAt",
"(",
"i",
",",
"recycler",
")",
";",
"}",
"}",
"}"
] |
Recycles children between given indices.
@param startIndex inclusive
@param endIndex exclusive
|
[
"Recycles",
"children",
"between",
"given",
"indices",
"."
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/ExposeLinearLayoutManagerEx.java#L1015-L1031
|
13,343
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/ExposeLinearLayoutManagerEx.java
|
ExposeLinearLayoutManagerEx.logChildren
|
private void logChildren() {
Log.d(TAG, "internal representation of views on the screen");
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
Log.d(TAG, "item " + getPosition(child) + ", coord:"
+ mOrientationHelper.getDecoratedStart(child));
}
Log.d(TAG, "==============");
}
|
java
|
private void logChildren() {
Log.d(TAG, "internal representation of views on the screen");
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
Log.d(TAG, "item " + getPosition(child) + ", coord:"
+ mOrientationHelper.getDecoratedStart(child));
}
Log.d(TAG, "==============");
}
|
[
"private",
"void",
"logChildren",
"(",
")",
"{",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"internal representation of views on the screen\"",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"getChildCount",
"(",
")",
";",
"i",
"++",
")",
"{",
"View",
"child",
"=",
"getChildAt",
"(",
"i",
")",
";",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"item \"",
"+",
"getPosition",
"(",
"child",
")",
"+",
"\", coord:\"",
"+",
"mOrientationHelper",
".",
"getDecoratedStart",
"(",
"child",
")",
")",
";",
"}",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"==============\"",
")",
";",
"}"
] |
Used for debugging.
Logs the internal representation of children to default logger.
|
[
"Used",
"for",
"debugging",
".",
"Logs",
"the",
"internal",
"representation",
"of",
"children",
"to",
"default",
"logger",
"."
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/ExposeLinearLayoutManagerEx.java#L1382-L1390
|
13,344
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/extend/InnerRecycledViewPool.java
|
InnerRecycledViewPool.size
|
public int size() {
int count = 0;
for (int i = 0, size = mScrapLength.size(); i < size; i++) {
int val = mScrapLength.valueAt(i);
count += val;
}
return count;
}
|
java
|
public int size() {
int count = 0;
for (int i = 0, size = mScrapLength.size(); i < size; i++) {
int val = mScrapLength.valueAt(i);
count += val;
}
return count;
}
|
[
"public",
"int",
"size",
"(",
")",
"{",
"int",
"count",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"size",
"=",
"mScrapLength",
".",
"size",
"(",
")",
";",
"i",
"<",
"size",
";",
"i",
"++",
")",
"{",
"int",
"val",
"=",
"mScrapLength",
".",
"valueAt",
"(",
"i",
")",
";",
"count",
"+=",
"val",
";",
"}",
"return",
"count",
";",
"}"
] |
Get all items size in current pool
@return the size of items in ViewPool
|
[
"Get",
"all",
"items",
"size",
"in",
"current",
"pool"
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/extend/InnerRecycledViewPool.java#L121-L130
|
13,345
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/extend/InnerRecycledViewPool.java
|
InnerRecycledViewPool.putRecycledView
|
@SuppressWarnings("unchecked")
public void putRecycledView(RecyclerView.ViewHolder scrap) {
int viewType = scrap.getItemViewType();
if (mMaxScrap.indexOfKey(viewType) < 0) {
// does't contains this viewType, initial scrap list
mMaxScrap.put(viewType, DEFAULT_MAX_SIZE);
setMaxRecycledViews(viewType, DEFAULT_MAX_SIZE);
}
// get current heap size
int scrapHeapSize = mScrapLength.indexOfKey(viewType) >= 0 ? this.mScrapLength.get(viewType) : 0;
if (this.mMaxScrap.get(viewType) > scrapHeapSize) {
// if exceed current heap size
mInnerPool.putRecycledView(scrap);
mScrapLength.put(viewType, scrapHeapSize + 1);
} else {
// destroy viewHolder
destroyViewHolder(scrap);
}
}
|
java
|
@SuppressWarnings("unchecked")
public void putRecycledView(RecyclerView.ViewHolder scrap) {
int viewType = scrap.getItemViewType();
if (mMaxScrap.indexOfKey(viewType) < 0) {
// does't contains this viewType, initial scrap list
mMaxScrap.put(viewType, DEFAULT_MAX_SIZE);
setMaxRecycledViews(viewType, DEFAULT_MAX_SIZE);
}
// get current heap size
int scrapHeapSize = mScrapLength.indexOfKey(viewType) >= 0 ? this.mScrapLength.get(viewType) : 0;
if (this.mMaxScrap.get(viewType) > scrapHeapSize) {
// if exceed current heap size
mInnerPool.putRecycledView(scrap);
mScrapLength.put(viewType, scrapHeapSize + 1);
} else {
// destroy viewHolder
destroyViewHolder(scrap);
}
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"void",
"putRecycledView",
"(",
"RecyclerView",
".",
"ViewHolder",
"scrap",
")",
"{",
"int",
"viewType",
"=",
"scrap",
".",
"getItemViewType",
"(",
")",
";",
"if",
"(",
"mMaxScrap",
".",
"indexOfKey",
"(",
"viewType",
")",
"<",
"0",
")",
"{",
"// does't contains this viewType, initial scrap list",
"mMaxScrap",
".",
"put",
"(",
"viewType",
",",
"DEFAULT_MAX_SIZE",
")",
";",
"setMaxRecycledViews",
"(",
"viewType",
",",
"DEFAULT_MAX_SIZE",
")",
";",
"}",
"// get current heap size",
"int",
"scrapHeapSize",
"=",
"mScrapLength",
".",
"indexOfKey",
"(",
"viewType",
")",
">=",
"0",
"?",
"this",
".",
"mScrapLength",
".",
"get",
"(",
"viewType",
")",
":",
"0",
";",
"if",
"(",
"this",
".",
"mMaxScrap",
".",
"get",
"(",
"viewType",
")",
">",
"scrapHeapSize",
")",
"{",
"// if exceed current heap size",
"mInnerPool",
".",
"putRecycledView",
"(",
"scrap",
")",
";",
"mScrapLength",
".",
"put",
"(",
"viewType",
",",
"scrapHeapSize",
"+",
"1",
")",
";",
"}",
"else",
"{",
"// destroy viewHolder",
"destroyViewHolder",
"(",
"scrap",
")",
";",
"}",
"}"
] |
This will be only run in UI Thread
@param scrap ViewHolder scrap that will be recycled
|
[
"This",
"will",
"be",
"only",
"run",
"in",
"UI",
"Thread"
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/extend/InnerRecycledViewPool.java#L137-L158
|
13,346
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/VirtualLayoutManager.java
|
VirtualLayoutManager.getOffsetToStart
|
public int getOffsetToStart() {
if (getChildCount() == 0) return -1;
final View view = getChildAt(0);
if (view == null) {
//in some conditions, for exapmle, calling this method when outter activity destroy, may cause npe
return -1;
}
int position = getPosition(view);
final int idx = findRangeLength(Range.create(position, position));
if (idx < 0 || idx >= mRangeLengths.size()) {
return -1;
}
int offset = -mOrientationHelper.getDecoratedStart(view);
for (int i = 0; i < idx; i++) {
Pair<Range<Integer>, Integer> pair = mRangeLengths.get(i);
if (pair != null) {
offset += pair.second;
}
}
return offset;
}
|
java
|
public int getOffsetToStart() {
if (getChildCount() == 0) return -1;
final View view = getChildAt(0);
if (view == null) {
//in some conditions, for exapmle, calling this method when outter activity destroy, may cause npe
return -1;
}
int position = getPosition(view);
final int idx = findRangeLength(Range.create(position, position));
if (idx < 0 || idx >= mRangeLengths.size()) {
return -1;
}
int offset = -mOrientationHelper.getDecoratedStart(view);
for (int i = 0; i < idx; i++) {
Pair<Range<Integer>, Integer> pair = mRangeLengths.get(i);
if (pair != null) {
offset += pair.second;
}
}
return offset;
}
|
[
"public",
"int",
"getOffsetToStart",
"(",
")",
"{",
"if",
"(",
"getChildCount",
"(",
")",
"==",
"0",
")",
"return",
"-",
"1",
";",
"final",
"View",
"view",
"=",
"getChildAt",
"(",
"0",
")",
";",
"if",
"(",
"view",
"==",
"null",
")",
"{",
"//in some conditions, for exapmle, calling this method when outter activity destroy, may cause npe",
"return",
"-",
"1",
";",
"}",
"int",
"position",
"=",
"getPosition",
"(",
"view",
")",
";",
"final",
"int",
"idx",
"=",
"findRangeLength",
"(",
"Range",
".",
"create",
"(",
"position",
",",
"position",
")",
")",
";",
"if",
"(",
"idx",
"<",
"0",
"||",
"idx",
">=",
"mRangeLengths",
".",
"size",
"(",
")",
")",
"{",
"return",
"-",
"1",
";",
"}",
"int",
"offset",
"=",
"-",
"mOrientationHelper",
".",
"getDecoratedStart",
"(",
"view",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"idx",
";",
"i",
"++",
")",
"{",
"Pair",
"<",
"Range",
"<",
"Integer",
">",
",",
"Integer",
">",
"pair",
"=",
"mRangeLengths",
".",
"get",
"(",
"i",
")",
";",
"if",
"(",
"pair",
"!=",
"null",
")",
"{",
"offset",
"+=",
"pair",
".",
"second",
";",
"}",
"}",
"return",
"offset",
";",
"}"
] |
Return current position related to the top, only works when scrolling from the top
@return offset from current position to original top of RecycledView
|
[
"Return",
"current",
"position",
"related",
"to",
"the",
"top",
"only",
"works",
"when",
"scrolling",
"from",
"the",
"top"
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/VirtualLayoutManager.java#L782-L807
|
13,347
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/VirtualLayoutManager.java
|
VirtualLayoutManager.updateSpecWithExtra
|
private int updateSpecWithExtra(int spec, int startInset, int endInset) {
if (startInset == 0 && endInset == 0) {
return spec;
}
final int mode = View.MeasureSpec.getMode(spec);
if (mode == View.MeasureSpec.AT_MOST || mode == View.MeasureSpec.EXACTLY) {
int size = View.MeasureSpec.getSize(spec);
if (size - startInset - endInset < 0) {
return View.MeasureSpec.makeMeasureSpec(0, mode);
} else {
return View.MeasureSpec.makeMeasureSpec(
View.MeasureSpec.getSize(spec) - startInset - endInset, mode);
}
}
return spec;
}
|
java
|
private int updateSpecWithExtra(int spec, int startInset, int endInset) {
if (startInset == 0 && endInset == 0) {
return spec;
}
final int mode = View.MeasureSpec.getMode(spec);
if (mode == View.MeasureSpec.AT_MOST || mode == View.MeasureSpec.EXACTLY) {
int size = View.MeasureSpec.getSize(spec);
if (size - startInset - endInset < 0) {
return View.MeasureSpec.makeMeasureSpec(0, mode);
} else {
return View.MeasureSpec.makeMeasureSpec(
View.MeasureSpec.getSize(spec) - startInset - endInset, mode);
}
}
return spec;
}
|
[
"private",
"int",
"updateSpecWithExtra",
"(",
"int",
"spec",
",",
"int",
"startInset",
",",
"int",
"endInset",
")",
"{",
"if",
"(",
"startInset",
"==",
"0",
"&&",
"endInset",
"==",
"0",
")",
"{",
"return",
"spec",
";",
"}",
"final",
"int",
"mode",
"=",
"View",
".",
"MeasureSpec",
".",
"getMode",
"(",
"spec",
")",
";",
"if",
"(",
"mode",
"==",
"View",
".",
"MeasureSpec",
".",
"AT_MOST",
"||",
"mode",
"==",
"View",
".",
"MeasureSpec",
".",
"EXACTLY",
")",
"{",
"int",
"size",
"=",
"View",
".",
"MeasureSpec",
".",
"getSize",
"(",
"spec",
")",
";",
"if",
"(",
"size",
"-",
"startInset",
"-",
"endInset",
"<",
"0",
")",
"{",
"return",
"View",
".",
"MeasureSpec",
".",
"makeMeasureSpec",
"(",
"0",
",",
"mode",
")",
";",
"}",
"else",
"{",
"return",
"View",
".",
"MeasureSpec",
".",
"makeMeasureSpec",
"(",
"View",
".",
"MeasureSpec",
".",
"getSize",
"(",
"spec",
")",
"-",
"startInset",
"-",
"endInset",
",",
"mode",
")",
";",
"}",
"}",
"return",
"spec",
";",
"}"
] |
Update measure spec with insets
@param spec
@param startInset
@param endInset
@return
|
[
"Update",
"measure",
"spec",
"with",
"insets"
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/VirtualLayoutManager.java#L1531-L1546
|
13,348
|
alibaba/vlayout
|
vlayout/src/main/java/com/alibaba/android/vlayout/DelegateAdapter.java
|
DelegateAdapter.getItemViewType
|
@Override
public int getItemViewType(int position) {
Pair<AdapterDataObserver, Adapter> p = findAdapterByPosition(position);
if (p == null) {
return RecyclerView.INVALID_TYPE;
}
int subItemType = p.second.getItemViewType(position - p.first.mStartPosition);
if (subItemType < 0) {
// negative integer, invalid, just return
return subItemType;
}
if (mHasConsistItemType) {
mItemTypeAry.put(subItemType, p.second);
return subItemType;
}
int index = p.first.mIndex;
return (int) Cantor.getCantor(subItemType, index);
}
|
java
|
@Override
public int getItemViewType(int position) {
Pair<AdapterDataObserver, Adapter> p = findAdapterByPosition(position);
if (p == null) {
return RecyclerView.INVALID_TYPE;
}
int subItemType = p.second.getItemViewType(position - p.first.mStartPosition);
if (subItemType < 0) {
// negative integer, invalid, just return
return subItemType;
}
if (mHasConsistItemType) {
mItemTypeAry.put(subItemType, p.second);
return subItemType;
}
int index = p.first.mIndex;
return (int) Cantor.getCantor(subItemType, index);
}
|
[
"@",
"Override",
"public",
"int",
"getItemViewType",
"(",
"int",
"position",
")",
"{",
"Pair",
"<",
"AdapterDataObserver",
",",
"Adapter",
">",
"p",
"=",
"findAdapterByPosition",
"(",
"position",
")",
";",
"if",
"(",
"p",
"==",
"null",
")",
"{",
"return",
"RecyclerView",
".",
"INVALID_TYPE",
";",
"}",
"int",
"subItemType",
"=",
"p",
".",
"second",
".",
"getItemViewType",
"(",
"position",
"-",
"p",
".",
"first",
".",
"mStartPosition",
")",
";",
"if",
"(",
"subItemType",
"<",
"0",
")",
"{",
"// negative integer, invalid, just return",
"return",
"subItemType",
";",
"}",
"if",
"(",
"mHasConsistItemType",
")",
"{",
"mItemTypeAry",
".",
"put",
"(",
"subItemType",
",",
"p",
".",
"second",
")",
";",
"return",
"subItemType",
";",
"}",
"int",
"index",
"=",
"p",
".",
"first",
".",
"mIndex",
";",
"return",
"(",
"int",
")",
"Cantor",
".",
"getCantor",
"(",
"subItemType",
",",
"index",
")",
";",
"}"
] |
Big integer of itemType returned by delegated adapter may lead to failed
@param position item position
@return integer represent item view type
|
[
"Big",
"integer",
"of",
"itemType",
"returned",
"by",
"delegated",
"adapter",
"may",
"lead",
"to",
"failed"
] |
8a5a51d9d2eeb91fed2ee331a4cf3496282452ce
|
https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/DelegateAdapter.java#L166-L189
|
13,349
|
dropwizard/metrics
|
metrics-core/src/main/java/com/codahale/metrics/ChunkedAssociativeLongArray.java
|
ChunkedAssociativeLongArray.trim
|
synchronized void trim(long startKey, long endKey) {
/*
* [3, 4, 5, 9] -> [10, 13, 14, 15] -> [21, 24, 29, 30] -> [31] :: start layout
* |5______________________________23| :: trim(5, 23)
* [5, 9] -> [10, 13, 14, 15] -> [21] :: result layout
*/
final Iterator<Chunk> descendingIterator = chunks.descendingIterator();
while (descendingIterator.hasNext()) {
final Chunk currentTail = descendingIterator.next();
if (isFirstElementIsEmptyOrGreaterEqualThanKey(currentTail, endKey)) {
freeChunk(currentTail);
descendingIterator.remove();
} else {
currentTail.cursor = findFirstIndexOfGreaterEqualElements(currentTail.keys, currentTail.startIndex,
currentTail.cursor, endKey);
break;
}
}
final Iterator<Chunk> iterator = chunks.iterator();
while (iterator.hasNext()) {
final Chunk currentHead = iterator.next();
if (isLastElementIsLessThanKey(currentHead, startKey)) {
freeChunk(currentHead);
iterator.remove();
} else {
final int newStartIndex = findFirstIndexOfGreaterEqualElements(currentHead.keys, currentHead.startIndex,
currentHead.cursor, startKey);
if (currentHead.startIndex != newStartIndex) {
currentHead.startIndex = newStartIndex;
currentHead.chunkSize = currentHead.cursor - currentHead.startIndex;
}
break;
}
}
}
|
java
|
synchronized void trim(long startKey, long endKey) {
/*
* [3, 4, 5, 9] -> [10, 13, 14, 15] -> [21, 24, 29, 30] -> [31] :: start layout
* |5______________________________23| :: trim(5, 23)
* [5, 9] -> [10, 13, 14, 15] -> [21] :: result layout
*/
final Iterator<Chunk> descendingIterator = chunks.descendingIterator();
while (descendingIterator.hasNext()) {
final Chunk currentTail = descendingIterator.next();
if (isFirstElementIsEmptyOrGreaterEqualThanKey(currentTail, endKey)) {
freeChunk(currentTail);
descendingIterator.remove();
} else {
currentTail.cursor = findFirstIndexOfGreaterEqualElements(currentTail.keys, currentTail.startIndex,
currentTail.cursor, endKey);
break;
}
}
final Iterator<Chunk> iterator = chunks.iterator();
while (iterator.hasNext()) {
final Chunk currentHead = iterator.next();
if (isLastElementIsLessThanKey(currentHead, startKey)) {
freeChunk(currentHead);
iterator.remove();
} else {
final int newStartIndex = findFirstIndexOfGreaterEqualElements(currentHead.keys, currentHead.startIndex,
currentHead.cursor, startKey);
if (currentHead.startIndex != newStartIndex) {
currentHead.startIndex = newStartIndex;
currentHead.chunkSize = currentHead.cursor - currentHead.startIndex;
}
break;
}
}
}
|
[
"synchronized",
"void",
"trim",
"(",
"long",
"startKey",
",",
"long",
"endKey",
")",
"{",
"/*\n * [3, 4, 5, 9] -> [10, 13, 14, 15] -> [21, 24, 29, 30] -> [31] :: start layout\n * |5______________________________23| :: trim(5, 23)\n * [5, 9] -> [10, 13, 14, 15] -> [21] :: result layout\n */",
"final",
"Iterator",
"<",
"Chunk",
">",
"descendingIterator",
"=",
"chunks",
".",
"descendingIterator",
"(",
")",
";",
"while",
"(",
"descendingIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"final",
"Chunk",
"currentTail",
"=",
"descendingIterator",
".",
"next",
"(",
")",
";",
"if",
"(",
"isFirstElementIsEmptyOrGreaterEqualThanKey",
"(",
"currentTail",
",",
"endKey",
")",
")",
"{",
"freeChunk",
"(",
"currentTail",
")",
";",
"descendingIterator",
".",
"remove",
"(",
")",
";",
"}",
"else",
"{",
"currentTail",
".",
"cursor",
"=",
"findFirstIndexOfGreaterEqualElements",
"(",
"currentTail",
".",
"keys",
",",
"currentTail",
".",
"startIndex",
",",
"currentTail",
".",
"cursor",
",",
"endKey",
")",
";",
"break",
";",
"}",
"}",
"final",
"Iterator",
"<",
"Chunk",
">",
"iterator",
"=",
"chunks",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"iterator",
".",
"hasNext",
"(",
")",
")",
"{",
"final",
"Chunk",
"currentHead",
"=",
"iterator",
".",
"next",
"(",
")",
";",
"if",
"(",
"isLastElementIsLessThanKey",
"(",
"currentHead",
",",
"startKey",
")",
")",
"{",
"freeChunk",
"(",
"currentHead",
")",
";",
"iterator",
".",
"remove",
"(",
")",
";",
"}",
"else",
"{",
"final",
"int",
"newStartIndex",
"=",
"findFirstIndexOfGreaterEqualElements",
"(",
"currentHead",
".",
"keys",
",",
"currentHead",
".",
"startIndex",
",",
"currentHead",
".",
"cursor",
",",
"startKey",
")",
";",
"if",
"(",
"currentHead",
".",
"startIndex",
"!=",
"newStartIndex",
")",
"{",
"currentHead",
".",
"startIndex",
"=",
"newStartIndex",
";",
"currentHead",
".",
"chunkSize",
"=",
"currentHead",
".",
"cursor",
"-",
"currentHead",
".",
"startIndex",
";",
"}",
"break",
";",
"}",
"}",
"}"
] |
Try to trim all beyond specified boundaries.
@param startKey the start value for which all elements less than it should be removed.
@param endKey the end value for which all elements greater/equals than it should be removed.
|
[
"Try",
"to",
"trim",
"all",
"beyond",
"specified",
"boundaries",
"."
] |
3c6105a0b9b4416c59e16b6b841b123052d6f57d
|
https://github.com/dropwizard/metrics/blob/3c6105a0b9b4416c59e16b6b841b123052d6f57d/metrics-core/src/main/java/com/codahale/metrics/ChunkedAssociativeLongArray.java#L122-L157
|
13,350
|
dropwizard/metrics
|
metrics-core/src/main/java/com/codahale/metrics/ExponentiallyDecayingReservoir.java
|
ExponentiallyDecayingReservoir.update
|
public void update(long value, long timestamp) {
rescaleIfNeeded();
lockForRegularUsage();
try {
final double itemWeight = weight(timestamp - startTime);
final WeightedSample sample = new WeightedSample(value, itemWeight);
final double priority = itemWeight / ThreadLocalRandom.current().nextDouble();
final long newCount = count.incrementAndGet();
if (newCount <= size) {
values.put(priority, sample);
} else {
Double first = values.firstKey();
if (first < priority && values.putIfAbsent(priority, sample) == null) {
// ensure we always remove an item
while (values.remove(first) == null) {
first = values.firstKey();
}
}
}
} finally {
unlockForRegularUsage();
}
}
|
java
|
public void update(long value, long timestamp) {
rescaleIfNeeded();
lockForRegularUsage();
try {
final double itemWeight = weight(timestamp - startTime);
final WeightedSample sample = new WeightedSample(value, itemWeight);
final double priority = itemWeight / ThreadLocalRandom.current().nextDouble();
final long newCount = count.incrementAndGet();
if (newCount <= size) {
values.put(priority, sample);
} else {
Double first = values.firstKey();
if (first < priority && values.putIfAbsent(priority, sample) == null) {
// ensure we always remove an item
while (values.remove(first) == null) {
first = values.firstKey();
}
}
}
} finally {
unlockForRegularUsage();
}
}
|
[
"public",
"void",
"update",
"(",
"long",
"value",
",",
"long",
"timestamp",
")",
"{",
"rescaleIfNeeded",
"(",
")",
";",
"lockForRegularUsage",
"(",
")",
";",
"try",
"{",
"final",
"double",
"itemWeight",
"=",
"weight",
"(",
"timestamp",
"-",
"startTime",
")",
";",
"final",
"WeightedSample",
"sample",
"=",
"new",
"WeightedSample",
"(",
"value",
",",
"itemWeight",
")",
";",
"final",
"double",
"priority",
"=",
"itemWeight",
"/",
"ThreadLocalRandom",
".",
"current",
"(",
")",
".",
"nextDouble",
"(",
")",
";",
"final",
"long",
"newCount",
"=",
"count",
".",
"incrementAndGet",
"(",
")",
";",
"if",
"(",
"newCount",
"<=",
"size",
")",
"{",
"values",
".",
"put",
"(",
"priority",
",",
"sample",
")",
";",
"}",
"else",
"{",
"Double",
"first",
"=",
"values",
".",
"firstKey",
"(",
")",
";",
"if",
"(",
"first",
"<",
"priority",
"&&",
"values",
".",
"putIfAbsent",
"(",
"priority",
",",
"sample",
")",
"==",
"null",
")",
"{",
"// ensure we always remove an item",
"while",
"(",
"values",
".",
"remove",
"(",
"first",
")",
"==",
"null",
")",
"{",
"first",
"=",
"values",
".",
"firstKey",
"(",
")",
";",
"}",
"}",
"}",
"}",
"finally",
"{",
"unlockForRegularUsage",
"(",
")",
";",
"}",
"}"
] |
Adds an old value with a fixed timestamp to the reservoir.
@param value the value to be added
@param timestamp the epoch timestamp of {@code value} in seconds
|
[
"Adds",
"an",
"old",
"value",
"with",
"a",
"fixed",
"timestamp",
"to",
"the",
"reservoir",
"."
] |
3c6105a0b9b4416c59e16b6b841b123052d6f57d
|
https://github.com/dropwizard/metrics/blob/3c6105a0b9b4416c59e16b6b841b123052d6f57d/metrics-core/src/main/java/com/codahale/metrics/ExponentiallyDecayingReservoir.java#L93-L116
|
13,351
|
dropwizard/metrics
|
metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java
|
MetricRegistry.name
|
public static String name(Class<?> klass, String... names) {
return name(klass.getName(), names);
}
|
java
|
public static String name(Class<?> klass, String... names) {
return name(klass.getName(), names);
}
|
[
"public",
"static",
"String",
"name",
"(",
"Class",
"<",
"?",
">",
"klass",
",",
"String",
"...",
"names",
")",
"{",
"return",
"name",
"(",
"klass",
".",
"getName",
"(",
")",
",",
"names",
")",
";",
"}"
] |
Concatenates a class name and elements to form a dotted name, eliding any null values or
empty strings.
@param klass the first element of the name
@param names the remaining elements of the name
@return {@code klass} and {@code names} concatenated by periods
|
[
"Concatenates",
"a",
"class",
"name",
"and",
"elements",
"to",
"form",
"a",
"dotted",
"name",
"eliding",
"any",
"null",
"values",
"or",
"empty",
"strings",
"."
] |
3c6105a0b9b4416c59e16b6b841b123052d6f57d
|
https://github.com/dropwizard/metrics/blob/3c6105a0b9b4416c59e16b6b841b123052d6f57d/metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java#L44-L46
|
13,352
|
dropwizard/metrics
|
metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java
|
MetricRegistry.registerAll
|
public void registerAll(String prefix, MetricSet metrics) throws IllegalArgumentException {
for (Map.Entry<String, Metric> entry : metrics.getMetrics().entrySet()) {
if (entry.getValue() instanceof MetricSet) {
registerAll(name(prefix, entry.getKey()), (MetricSet) entry.getValue());
} else {
register(name(prefix, entry.getKey()), entry.getValue());
}
}
}
|
java
|
public void registerAll(String prefix, MetricSet metrics) throws IllegalArgumentException {
for (Map.Entry<String, Metric> entry : metrics.getMetrics().entrySet()) {
if (entry.getValue() instanceof MetricSet) {
registerAll(name(prefix, entry.getKey()), (MetricSet) entry.getValue());
} else {
register(name(prefix, entry.getKey()), entry.getValue());
}
}
}
|
[
"public",
"void",
"registerAll",
"(",
"String",
"prefix",
",",
"MetricSet",
"metrics",
")",
"throws",
"IllegalArgumentException",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Metric",
">",
"entry",
":",
"metrics",
".",
"getMetrics",
"(",
")",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"entry",
".",
"getValue",
"(",
")",
"instanceof",
"MetricSet",
")",
"{",
"registerAll",
"(",
"name",
"(",
"prefix",
",",
"entry",
".",
"getKey",
"(",
")",
")",
",",
"(",
"MetricSet",
")",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"else",
"{",
"register",
"(",
"name",
"(",
"prefix",
",",
"entry",
".",
"getKey",
"(",
")",
")",
",",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}",
"}"
] |
Given a metric set, registers them with the given prefix prepended to their names.
@param prefix a name prefix
@param metrics a set of metrics
@throws IllegalArgumentException if any of the names are already registered
|
[
"Given",
"a",
"metric",
"set",
"registers",
"them",
"with",
"the",
"given",
"prefix",
"prepended",
"to",
"their",
"names",
"."
] |
3c6105a0b9b4416c59e16b6b841b123052d6f57d
|
https://github.com/dropwizard/metrics/blob/3c6105a0b9b4416c59e16b6b841b123052d6f57d/metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java#L511-L519
|
13,353
|
dropwizard/metrics
|
metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java
|
ConsoleReporter.printIfEnabled
|
private void printIfEnabled(MetricAttribute type, String status) {
if (getDisabledMetricAttributes().contains(type)) {
return;
}
output.println(status);
}
|
java
|
private void printIfEnabled(MetricAttribute type, String status) {
if (getDisabledMetricAttributes().contains(type)) {
return;
}
output.println(status);
}
|
[
"private",
"void",
"printIfEnabled",
"(",
"MetricAttribute",
"type",
",",
"String",
"status",
")",
"{",
"if",
"(",
"getDisabledMetricAttributes",
"(",
")",
".",
"contains",
"(",
"type",
")",
")",
"{",
"return",
";",
"}",
"output",
".",
"println",
"(",
"status",
")",
";",
"}"
] |
Print only if the attribute is enabled
@param type Metric attribute
@param status Status to be logged
|
[
"Print",
"only",
"if",
"the",
"attribute",
"is",
"enabled"
] |
3c6105a0b9b4416c59e16b6b841b123052d6f57d
|
https://github.com/dropwizard/metrics/blob/3c6105a0b9b4416c59e16b6b841b123052d6f57d/metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java#L350-L356
|
13,354
|
dropwizard/metrics
|
metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteSanitize.java
|
GraphiteSanitize.sanitize
|
static String sanitize(String string) {
return WHITESPACE.matcher(string.trim()).replaceAll(DASH);
}
|
java
|
static String sanitize(String string) {
return WHITESPACE.matcher(string.trim()).replaceAll(DASH);
}
|
[
"static",
"String",
"sanitize",
"(",
"String",
"string",
")",
"{",
"return",
"WHITESPACE",
".",
"matcher",
"(",
"string",
".",
"trim",
"(",
")",
")",
".",
"replaceAll",
"(",
"DASH",
")",
";",
"}"
] |
Trims the string and replaces all whitespace characters with the provided symbol
|
[
"Trims",
"the",
"string",
"and",
"replaces",
"all",
"whitespace",
"characters",
"with",
"the",
"provided",
"symbol"
] |
3c6105a0b9b4416c59e16b6b841b123052d6f57d
|
https://github.com/dropwizard/metrics/blob/3c6105a0b9b4416c59e16b6b841b123052d6f57d/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteSanitize.java#L13-L15
|
13,355
|
dropwizard/metrics
|
metrics-healthchecks/src/main/java/com/codahale/metrics/health/SharedHealthCheckRegistries.java
|
SharedHealthCheckRegistries.setDefault
|
public synchronized static HealthCheckRegistry setDefault(String name) {
final HealthCheckRegistry registry = getOrCreate(name);
return setDefault(name, registry);
}
|
java
|
public synchronized static HealthCheckRegistry setDefault(String name) {
final HealthCheckRegistry registry = getOrCreate(name);
return setDefault(name, registry);
}
|
[
"public",
"synchronized",
"static",
"HealthCheckRegistry",
"setDefault",
"(",
"String",
"name",
")",
"{",
"final",
"HealthCheckRegistry",
"registry",
"=",
"getOrCreate",
"(",
"name",
")",
";",
"return",
"setDefault",
"(",
"name",
",",
"registry",
")",
";",
"}"
] |
Creates a new registry and sets it as the default one under the provided name.
@param name the registry name
@return the default registry
@throws IllegalStateException if the name has already been set
|
[
"Creates",
"a",
"new",
"registry",
"and",
"sets",
"it",
"as",
"the",
"default",
"one",
"under",
"the",
"provided",
"name",
"."
] |
3c6105a0b9b4416c59e16b6b841b123052d6f57d
|
https://github.com/dropwizard/metrics/blob/3c6105a0b9b4416c59e16b6b841b123052d6f57d/metrics-healthchecks/src/main/java/com/codahale/metrics/health/SharedHealthCheckRegistries.java#L60-L63
|
13,356
|
dropwizard/metrics
|
metrics-healthchecks/src/main/java/com/codahale/metrics/health/SharedHealthCheckRegistries.java
|
SharedHealthCheckRegistries.setDefault
|
public static HealthCheckRegistry setDefault(String name, HealthCheckRegistry healthCheckRegistry) {
if (defaultRegistryName.compareAndSet(null, name)) {
add(name, healthCheckRegistry);
return healthCheckRegistry;
}
throw new IllegalStateException("Default health check registry is already set.");
}
|
java
|
public static HealthCheckRegistry setDefault(String name, HealthCheckRegistry healthCheckRegistry) {
if (defaultRegistryName.compareAndSet(null, name)) {
add(name, healthCheckRegistry);
return healthCheckRegistry;
}
throw new IllegalStateException("Default health check registry is already set.");
}
|
[
"public",
"static",
"HealthCheckRegistry",
"setDefault",
"(",
"String",
"name",
",",
"HealthCheckRegistry",
"healthCheckRegistry",
")",
"{",
"if",
"(",
"defaultRegistryName",
".",
"compareAndSet",
"(",
"null",
",",
"name",
")",
")",
"{",
"add",
"(",
"name",
",",
"healthCheckRegistry",
")",
";",
"return",
"healthCheckRegistry",
";",
"}",
"throw",
"new",
"IllegalStateException",
"(",
"\"Default health check registry is already set.\"",
")",
";",
"}"
] |
Sets the provided registry as the default one under the provided name
@param name the default registry name
@param healthCheckRegistry the default registry
@throws IllegalStateException if the default registry has already been set
|
[
"Sets",
"the",
"provided",
"registry",
"as",
"the",
"default",
"one",
"under",
"the",
"provided",
"name"
] |
3c6105a0b9b4416c59e16b6b841b123052d6f57d
|
https://github.com/dropwizard/metrics/blob/3c6105a0b9b4416c59e16b6b841b123052d6f57d/metrics-healthchecks/src/main/java/com/codahale/metrics/health/SharedHealthCheckRegistries.java#L72-L78
|
13,357
|
dropwizard/metrics
|
metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java
|
ScheduledReporter.start
|
synchronized void start(long initialDelay, long period, TimeUnit unit, Runnable runnable) {
if (this.scheduledFuture != null) {
throw new IllegalArgumentException("Reporter already started");
}
this.scheduledFuture = executor.scheduleAtFixedRate(runnable, initialDelay, period, unit);
}
|
java
|
synchronized void start(long initialDelay, long period, TimeUnit unit, Runnable runnable) {
if (this.scheduledFuture != null) {
throw new IllegalArgumentException("Reporter already started");
}
this.scheduledFuture = executor.scheduleAtFixedRate(runnable, initialDelay, period, unit);
}
|
[
"synchronized",
"void",
"start",
"(",
"long",
"initialDelay",
",",
"long",
"period",
",",
"TimeUnit",
"unit",
",",
"Runnable",
"runnable",
")",
"{",
"if",
"(",
"this",
".",
"scheduledFuture",
"!=",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Reporter already started\"",
")",
";",
"}",
"this",
".",
"scheduledFuture",
"=",
"executor",
".",
"scheduleAtFixedRate",
"(",
"runnable",
",",
"initialDelay",
",",
"period",
",",
"unit",
")",
";",
"}"
] |
Starts the reporter polling at the given period with the specific runnable action.
Visible only for testing.
|
[
"Starts",
"the",
"reporter",
"polling",
"at",
"the",
"given",
"period",
"with",
"the",
"specific",
"runnable",
"action",
".",
"Visible",
"only",
"for",
"testing",
"."
] |
3c6105a0b9b4416c59e16b6b841b123052d6f57d
|
https://github.com/dropwizard/metrics/blob/3c6105a0b9b4416c59e16b6b841b123052d6f57d/metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java#L159-L165
|
13,358
|
dropwizard/metrics
|
metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java
|
HealthCheckRegistry.runHealthCheck
|
public HealthCheck.Result runHealthCheck(String name) throws NoSuchElementException {
final HealthCheck healthCheck = healthChecks.get(name);
if (healthCheck == null) {
throw new NoSuchElementException("No health check named " + name + " exists");
}
return healthCheck.execute();
}
|
java
|
public HealthCheck.Result runHealthCheck(String name) throws NoSuchElementException {
final HealthCheck healthCheck = healthChecks.get(name);
if (healthCheck == null) {
throw new NoSuchElementException("No health check named " + name + " exists");
}
return healthCheck.execute();
}
|
[
"public",
"HealthCheck",
".",
"Result",
"runHealthCheck",
"(",
"String",
"name",
")",
"throws",
"NoSuchElementException",
"{",
"final",
"HealthCheck",
"healthCheck",
"=",
"healthChecks",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"healthCheck",
"==",
"null",
")",
"{",
"throw",
"new",
"NoSuchElementException",
"(",
"\"No health check named \"",
"+",
"name",
"+",
"\" exists\"",
")",
";",
"}",
"return",
"healthCheck",
".",
"execute",
"(",
")",
";",
"}"
] |
Runs the health check with the given name.
@param name the health check's name
@return the result of the health check
@throws NoSuchElementException if there is no health check with the given name
|
[
"Runs",
"the",
"health",
"check",
"with",
"the",
"given",
"name",
"."
] |
3c6105a0b9b4416c59e16b6b841b123052d6f57d
|
https://github.com/dropwizard/metrics/blob/3c6105a0b9b4416c59e16b6b841b123052d6f57d/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java#L155-L161
|
13,359
|
dropwizard/metrics
|
metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java
|
HealthCheckRegistry.runHealthChecks
|
public SortedMap<String, HealthCheck.Result> runHealthChecks(HealthCheckFilter filter) {
final SortedMap<String, HealthCheck.Result> results = new TreeMap<>();
for (Map.Entry<String, HealthCheck> entry : healthChecks.entrySet()) {
final String name = entry.getKey();
final HealthCheck healthCheck = entry.getValue();
if (filter.matches(name, healthCheck)) {
final Result result = entry.getValue().execute();
results.put(entry.getKey(), result);
}
}
return Collections.unmodifiableSortedMap(results);
}
|
java
|
public SortedMap<String, HealthCheck.Result> runHealthChecks(HealthCheckFilter filter) {
final SortedMap<String, HealthCheck.Result> results = new TreeMap<>();
for (Map.Entry<String, HealthCheck> entry : healthChecks.entrySet()) {
final String name = entry.getKey();
final HealthCheck healthCheck = entry.getValue();
if (filter.matches(name, healthCheck)) {
final Result result = entry.getValue().execute();
results.put(entry.getKey(), result);
}
}
return Collections.unmodifiableSortedMap(results);
}
|
[
"public",
"SortedMap",
"<",
"String",
",",
"HealthCheck",
".",
"Result",
">",
"runHealthChecks",
"(",
"HealthCheckFilter",
"filter",
")",
"{",
"final",
"SortedMap",
"<",
"String",
",",
"HealthCheck",
".",
"Result",
">",
"results",
"=",
"new",
"TreeMap",
"<>",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"HealthCheck",
">",
"entry",
":",
"healthChecks",
".",
"entrySet",
"(",
")",
")",
"{",
"final",
"String",
"name",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"final",
"HealthCheck",
"healthCheck",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"filter",
".",
"matches",
"(",
"name",
",",
"healthCheck",
")",
")",
"{",
"final",
"Result",
"result",
"=",
"entry",
".",
"getValue",
"(",
")",
".",
"execute",
"(",
")",
";",
"results",
".",
"put",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"result",
")",
";",
"}",
"}",
"return",
"Collections",
".",
"unmodifiableSortedMap",
"(",
"results",
")",
";",
"}"
] |
Runs the registered health checks matching the filter and returns a map of the results.
@param filter health check filter
@return a map of the health check results
|
[
"Runs",
"the",
"registered",
"health",
"checks",
"matching",
"the",
"filter",
"and",
"returns",
"a",
"map",
"of",
"the",
"results",
"."
] |
3c6105a0b9b4416c59e16b6b841b123052d6f57d
|
https://github.com/dropwizard/metrics/blob/3c6105a0b9b4416c59e16b6b841b123052d6f57d/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java#L178-L189
|
13,360
|
dropwizard/metrics
|
metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java
|
HealthCheckRegistry.runHealthChecks
|
public SortedMap<String, HealthCheck.Result> runHealthChecks(ExecutorService executor) {
return runHealthChecks(executor, HealthCheckFilter.ALL);
}
|
java
|
public SortedMap<String, HealthCheck.Result> runHealthChecks(ExecutorService executor) {
return runHealthChecks(executor, HealthCheckFilter.ALL);
}
|
[
"public",
"SortedMap",
"<",
"String",
",",
"HealthCheck",
".",
"Result",
">",
"runHealthChecks",
"(",
"ExecutorService",
"executor",
")",
"{",
"return",
"runHealthChecks",
"(",
"executor",
",",
"HealthCheckFilter",
".",
"ALL",
")",
";",
"}"
] |
Runs the registered health checks in parallel and returns a map of the results.
@param executor object to launch and track health checks progress
@return a map of the health check results
|
[
"Runs",
"the",
"registered",
"health",
"checks",
"in",
"parallel",
"and",
"returns",
"a",
"map",
"of",
"the",
"results",
"."
] |
3c6105a0b9b4416c59e16b6b841b123052d6f57d
|
https://github.com/dropwizard/metrics/blob/3c6105a0b9b4416c59e16b6b841b123052d6f57d/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java#L197-L199
|
13,361
|
dropwizard/metrics
|
metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java
|
HealthCheckRegistry.runHealthChecks
|
public SortedMap<String, HealthCheck.Result> runHealthChecks(ExecutorService executor, HealthCheckFilter filter) {
final Map<String, Future<HealthCheck.Result>> futures = new HashMap<>();
for (final Map.Entry<String, HealthCheck> entry : healthChecks.entrySet()) {
final String name = entry.getKey();
final HealthCheck healthCheck = entry.getValue();
if (filter.matches(name, healthCheck)) {
futures.put(name, executor.submit(() -> healthCheck.execute()));
}
}
final SortedMap<String, HealthCheck.Result> results = new TreeMap<>();
for (Map.Entry<String, Future<Result>> entry : futures.entrySet()) {
try {
results.put(entry.getKey(), entry.getValue().get());
} catch (Exception e) {
LOGGER.warn("Error executing health check {}", entry.getKey(), e);
results.put(entry.getKey(), HealthCheck.Result.unhealthy(e));
}
}
return Collections.unmodifiableSortedMap(results);
}
|
java
|
public SortedMap<String, HealthCheck.Result> runHealthChecks(ExecutorService executor, HealthCheckFilter filter) {
final Map<String, Future<HealthCheck.Result>> futures = new HashMap<>();
for (final Map.Entry<String, HealthCheck> entry : healthChecks.entrySet()) {
final String name = entry.getKey();
final HealthCheck healthCheck = entry.getValue();
if (filter.matches(name, healthCheck)) {
futures.put(name, executor.submit(() -> healthCheck.execute()));
}
}
final SortedMap<String, HealthCheck.Result> results = new TreeMap<>();
for (Map.Entry<String, Future<Result>> entry : futures.entrySet()) {
try {
results.put(entry.getKey(), entry.getValue().get());
} catch (Exception e) {
LOGGER.warn("Error executing health check {}", entry.getKey(), e);
results.put(entry.getKey(), HealthCheck.Result.unhealthy(e));
}
}
return Collections.unmodifiableSortedMap(results);
}
|
[
"public",
"SortedMap",
"<",
"String",
",",
"HealthCheck",
".",
"Result",
">",
"runHealthChecks",
"(",
"ExecutorService",
"executor",
",",
"HealthCheckFilter",
"filter",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"Future",
"<",
"HealthCheck",
".",
"Result",
">",
">",
"futures",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"for",
"(",
"final",
"Map",
".",
"Entry",
"<",
"String",
",",
"HealthCheck",
">",
"entry",
":",
"healthChecks",
".",
"entrySet",
"(",
")",
")",
"{",
"final",
"String",
"name",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"final",
"HealthCheck",
"healthCheck",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"filter",
".",
"matches",
"(",
"name",
",",
"healthCheck",
")",
")",
"{",
"futures",
".",
"put",
"(",
"name",
",",
"executor",
".",
"submit",
"(",
"(",
")",
"->",
"healthCheck",
".",
"execute",
"(",
")",
")",
")",
";",
"}",
"}",
"final",
"SortedMap",
"<",
"String",
",",
"HealthCheck",
".",
"Result",
">",
"results",
"=",
"new",
"TreeMap",
"<>",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Future",
"<",
"Result",
">",
">",
"entry",
":",
"futures",
".",
"entrySet",
"(",
")",
")",
"{",
"try",
"{",
"results",
".",
"put",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"entry",
".",
"getValue",
"(",
")",
".",
"get",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Error executing health check {}\"",
",",
"entry",
".",
"getKey",
"(",
")",
",",
"e",
")",
";",
"results",
".",
"put",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"HealthCheck",
".",
"Result",
".",
"unhealthy",
"(",
"e",
")",
")",
";",
"}",
"}",
"return",
"Collections",
".",
"unmodifiableSortedMap",
"(",
"results",
")",
";",
"}"
] |
Runs the registered health checks matching the filter in parallel and returns a map of the results.
@param executor object to launch and track health checks progress
@param filter health check filter
@return a map of the health check results
|
[
"Runs",
"the",
"registered",
"health",
"checks",
"matching",
"the",
"filter",
"in",
"parallel",
"and",
"returns",
"a",
"map",
"of",
"the",
"results",
"."
] |
3c6105a0b9b4416c59e16b6b841b123052d6f57d
|
https://github.com/dropwizard/metrics/blob/3c6105a0b9b4416c59e16b6b841b123052d6f57d/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java#L208-L229
|
13,362
|
dropwizard/metrics
|
metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java
|
HealthCheckRegistry.shutdown
|
public void shutdown() {
asyncExecutorService.shutdown(); // Disable new health checks from being submitted
try {
// Give some time to the current healtch checks to finish gracefully
if (!asyncExecutorService.awaitTermination(1, TimeUnit.SECONDS)) {
asyncExecutorService.shutdownNow();
}
} catch (InterruptedException ie) {
asyncExecutorService.shutdownNow();
Thread.currentThread().interrupt();
}
}
|
java
|
public void shutdown() {
asyncExecutorService.shutdown(); // Disable new health checks from being submitted
try {
// Give some time to the current healtch checks to finish gracefully
if (!asyncExecutorService.awaitTermination(1, TimeUnit.SECONDS)) {
asyncExecutorService.shutdownNow();
}
} catch (InterruptedException ie) {
asyncExecutorService.shutdownNow();
Thread.currentThread().interrupt();
}
}
|
[
"public",
"void",
"shutdown",
"(",
")",
"{",
"asyncExecutorService",
".",
"shutdown",
"(",
")",
";",
"// Disable new health checks from being submitted",
"try",
"{",
"// Give some time to the current healtch checks to finish gracefully",
"if",
"(",
"!",
"asyncExecutorService",
".",
"awaitTermination",
"(",
"1",
",",
"TimeUnit",
".",
"SECONDS",
")",
")",
"{",
"asyncExecutorService",
".",
"shutdownNow",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"InterruptedException",
"ie",
")",
"{",
"asyncExecutorService",
".",
"shutdownNow",
"(",
")",
";",
"Thread",
".",
"currentThread",
"(",
")",
".",
"interrupt",
"(",
")",
";",
"}",
"}"
] |
Shuts down the scheduled executor for async health checks
|
[
"Shuts",
"down",
"the",
"scheduled",
"executor",
"for",
"async",
"health",
"checks"
] |
3c6105a0b9b4416c59e16b6b841b123052d6f57d
|
https://github.com/dropwizard/metrics/blob/3c6105a0b9b4416c59e16b6b841b123052d6f57d/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java#L247-L258
|
13,363
|
square/picasso
|
picasso/src/main/java/com/squareup/picasso3/RequestCreator.java
|
RequestCreator.resizeDimen
|
@NonNull
public RequestCreator resizeDimen(int targetWidthResId, int targetHeightResId) {
Resources resources = picasso.context.getResources();
int targetWidth = resources.getDimensionPixelSize(targetWidthResId);
int targetHeight = resources.getDimensionPixelSize(targetHeightResId);
return resize(targetWidth, targetHeight);
}
|
java
|
@NonNull
public RequestCreator resizeDimen(int targetWidthResId, int targetHeightResId) {
Resources resources = picasso.context.getResources();
int targetWidth = resources.getDimensionPixelSize(targetWidthResId);
int targetHeight = resources.getDimensionPixelSize(targetHeightResId);
return resize(targetWidth, targetHeight);
}
|
[
"@",
"NonNull",
"public",
"RequestCreator",
"resizeDimen",
"(",
"int",
"targetWidthResId",
",",
"int",
"targetHeightResId",
")",
"{",
"Resources",
"resources",
"=",
"picasso",
".",
"context",
".",
"getResources",
"(",
")",
";",
"int",
"targetWidth",
"=",
"resources",
".",
"getDimensionPixelSize",
"(",
"targetWidthResId",
")",
";",
"int",
"targetHeight",
"=",
"resources",
".",
"getDimensionPixelSize",
"(",
"targetHeightResId",
")",
";",
"return",
"resize",
"(",
"targetWidth",
",",
"targetHeight",
")",
";",
"}"
] |
Resize the image to the specified dimension size.
Use 0 as desired dimension to resize keeping aspect ratio.
|
[
"Resize",
"the",
"image",
"to",
"the",
"specified",
"dimension",
"size",
".",
"Use",
"0",
"as",
"desired",
"dimension",
"to",
"resize",
"keeping",
"aspect",
"ratio",
"."
] |
89f55b76e3be2b65e5997b7698f782f16f8547e3
|
https://github.com/square/picasso/blob/89f55b76e3be2b65e5997b7698f782f16f8547e3/picasso/src/main/java/com/squareup/picasso3/RequestCreator.java#L228-L234
|
13,364
|
square/picasso
|
picasso/src/main/java/com/squareup/picasso3/RequestCreator.java
|
RequestCreator.rotate
|
@NonNull
public RequestCreator rotate(float degrees, float pivotX, float pivotY) {
data.rotate(degrees, pivotX, pivotY);
return this;
}
|
java
|
@NonNull
public RequestCreator rotate(float degrees, float pivotX, float pivotY) {
data.rotate(degrees, pivotX, pivotY);
return this;
}
|
[
"@",
"NonNull",
"public",
"RequestCreator",
"rotate",
"(",
"float",
"degrees",
",",
"float",
"pivotX",
",",
"float",
"pivotY",
")",
"{",
"data",
".",
"rotate",
"(",
"degrees",
",",
"pivotX",
",",
"pivotY",
")",
";",
"return",
"this",
";",
"}"
] |
Rotate the image by the specified degrees around a pivot point.
|
[
"Rotate",
"the",
"image",
"by",
"the",
"specified",
"degrees",
"around",
"a",
"pivot",
"point",
"."
] |
89f55b76e3be2b65e5997b7698f782f16f8547e3
|
https://github.com/square/picasso/blob/89f55b76e3be2b65e5997b7698f782f16f8547e3/picasso/src/main/java/com/squareup/picasso3/RequestCreator.java#L296-L300
|
13,365
|
square/picasso
|
picasso/src/main/java/com/squareup/picasso3/RequestCreator.java
|
RequestCreator.get
|
@Nullable // TODO make non-null and always throw?
public Bitmap get() throws IOException {
long started = System.nanoTime();
checkNotMain();
if (deferred) {
throw new IllegalStateException("Fit cannot be used with get.");
}
if (!data.hasImage()) {
return null;
}
Request request = createRequest(started);
Action action = new GetAction(picasso, request);
RequestHandler.Result result =
forRequest(picasso, picasso.dispatcher, picasso.cache, picasso.stats, action).hunt();
Bitmap bitmap = result.getBitmap();
if (bitmap != null && shouldWriteToMemoryCache(request.memoryPolicy)) {
picasso.cache.set(request.key, bitmap);
}
return bitmap;
}
|
java
|
@Nullable // TODO make non-null and always throw?
public Bitmap get() throws IOException {
long started = System.nanoTime();
checkNotMain();
if (deferred) {
throw new IllegalStateException("Fit cannot be used with get.");
}
if (!data.hasImage()) {
return null;
}
Request request = createRequest(started);
Action action = new GetAction(picasso, request);
RequestHandler.Result result =
forRequest(picasso, picasso.dispatcher, picasso.cache, picasso.stats, action).hunt();
Bitmap bitmap = result.getBitmap();
if (bitmap != null && shouldWriteToMemoryCache(request.memoryPolicy)) {
picasso.cache.set(request.key, bitmap);
}
return bitmap;
}
|
[
"@",
"Nullable",
"// TODO make non-null and always throw?",
"public",
"Bitmap",
"get",
"(",
")",
"throws",
"IOException",
"{",
"long",
"started",
"=",
"System",
".",
"nanoTime",
"(",
")",
";",
"checkNotMain",
"(",
")",
";",
"if",
"(",
"deferred",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Fit cannot be used with get.\"",
")",
";",
"}",
"if",
"(",
"!",
"data",
".",
"hasImage",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"Request",
"request",
"=",
"createRequest",
"(",
"started",
")",
";",
"Action",
"action",
"=",
"new",
"GetAction",
"(",
"picasso",
",",
"request",
")",
";",
"RequestHandler",
".",
"Result",
"result",
"=",
"forRequest",
"(",
"picasso",
",",
"picasso",
".",
"dispatcher",
",",
"picasso",
".",
"cache",
",",
"picasso",
".",
"stats",
",",
"action",
")",
".",
"hunt",
"(",
")",
";",
"Bitmap",
"bitmap",
"=",
"result",
".",
"getBitmap",
"(",
")",
";",
"if",
"(",
"bitmap",
"!=",
"null",
"&&",
"shouldWriteToMemoryCache",
"(",
"request",
".",
"memoryPolicy",
")",
")",
"{",
"picasso",
".",
"cache",
".",
"set",
"(",
"request",
".",
"key",
",",
"bitmap",
")",
";",
"}",
"return",
"bitmap",
";",
"}"
] |
Synchronously fulfill this request. Must not be called from the main thread.
|
[
"Synchronously",
"fulfill",
"this",
"request",
".",
"Must",
"not",
"be",
"called",
"from",
"the",
"main",
"thread",
"."
] |
89f55b76e3be2b65e5997b7698f782f16f8547e3
|
https://github.com/square/picasso/blob/89f55b76e3be2b65e5997b7698f782f16f8547e3/picasso/src/main/java/com/squareup/picasso3/RequestCreator.java#L405-L427
|
13,366
|
square/picasso
|
picasso/src/main/java/com/squareup/picasso3/RequestCreator.java
|
RequestCreator.createRequest
|
private Request createRequest(long started) {
int id = nextId.getAndIncrement();
Request request = data.build();
request.id = id;
request.started = started;
boolean loggingEnabled = picasso.loggingEnabled;
if (loggingEnabled) {
log(OWNER_MAIN, VERB_CREATED, request.plainId(), request.toString());
}
Request transformed = picasso.transformRequest(request);
if (transformed != request) {
// If the request was changed, copy over the id and timestamp from the original.
transformed.id = id;
transformed.started = started;
if (loggingEnabled) {
log(OWNER_MAIN, VERB_CHANGED, transformed.logId(), "into " + transformed);
}
}
return transformed;
}
|
java
|
private Request createRequest(long started) {
int id = nextId.getAndIncrement();
Request request = data.build();
request.id = id;
request.started = started;
boolean loggingEnabled = picasso.loggingEnabled;
if (loggingEnabled) {
log(OWNER_MAIN, VERB_CREATED, request.plainId(), request.toString());
}
Request transformed = picasso.transformRequest(request);
if (transformed != request) {
// If the request was changed, copy over the id and timestamp from the original.
transformed.id = id;
transformed.started = started;
if (loggingEnabled) {
log(OWNER_MAIN, VERB_CHANGED, transformed.logId(), "into " + transformed);
}
}
return transformed;
}
|
[
"private",
"Request",
"createRequest",
"(",
"long",
"started",
")",
"{",
"int",
"id",
"=",
"nextId",
".",
"getAndIncrement",
"(",
")",
";",
"Request",
"request",
"=",
"data",
".",
"build",
"(",
")",
";",
"request",
".",
"id",
"=",
"id",
";",
"request",
".",
"started",
"=",
"started",
";",
"boolean",
"loggingEnabled",
"=",
"picasso",
".",
"loggingEnabled",
";",
"if",
"(",
"loggingEnabled",
")",
"{",
"log",
"(",
"OWNER_MAIN",
",",
"VERB_CREATED",
",",
"request",
".",
"plainId",
"(",
")",
",",
"request",
".",
"toString",
"(",
")",
")",
";",
"}",
"Request",
"transformed",
"=",
"picasso",
".",
"transformRequest",
"(",
"request",
")",
";",
"if",
"(",
"transformed",
"!=",
"request",
")",
"{",
"// If the request was changed, copy over the id and timestamp from the original.",
"transformed",
".",
"id",
"=",
"id",
";",
"transformed",
".",
"started",
"=",
"started",
";",
"if",
"(",
"loggingEnabled",
")",
"{",
"log",
"(",
"OWNER_MAIN",
",",
"VERB_CHANGED",
",",
"transformed",
".",
"logId",
"(",
")",
",",
"\"into \"",
"+",
"transformed",
")",
";",
"}",
"}",
"return",
"transformed",
";",
"}"
] |
Create the request optionally passing it through the request transformer.
|
[
"Create",
"the",
"request",
"optionally",
"passing",
"it",
"through",
"the",
"request",
"transformer",
"."
] |
89f55b76e3be2b65e5997b7698f782f16f8547e3
|
https://github.com/square/picasso/blob/89f55b76e3be2b65e5997b7698f782f16f8547e3/picasso/src/main/java/com/squareup/picasso3/RequestCreator.java#L748-L772
|
13,367
|
square/picasso
|
picasso/src/main/java/com/squareup/picasso3/Utils.java
|
Utils.flushStackLocalLeaks
|
static void flushStackLocalLeaks(Looper looper) {
Handler handler = new Handler(looper) {
@Override public void handleMessage(Message msg) {
sendMessageDelayed(obtainMessage(), THREAD_LEAK_CLEANING_MS);
}
};
handler.sendMessageDelayed(handler.obtainMessage(), THREAD_LEAK_CLEANING_MS);
}
|
java
|
static void flushStackLocalLeaks(Looper looper) {
Handler handler = new Handler(looper) {
@Override public void handleMessage(Message msg) {
sendMessageDelayed(obtainMessage(), THREAD_LEAK_CLEANING_MS);
}
};
handler.sendMessageDelayed(handler.obtainMessage(), THREAD_LEAK_CLEANING_MS);
}
|
[
"static",
"void",
"flushStackLocalLeaks",
"(",
"Looper",
"looper",
")",
"{",
"Handler",
"handler",
"=",
"new",
"Handler",
"(",
"looper",
")",
"{",
"@",
"Override",
"public",
"void",
"handleMessage",
"(",
"Message",
"msg",
")",
"{",
"sendMessageDelayed",
"(",
"obtainMessage",
"(",
")",
",",
"THREAD_LEAK_CLEANING_MS",
")",
";",
"}",
"}",
";",
"handler",
".",
"sendMessageDelayed",
"(",
"handler",
".",
"obtainMessage",
"(",
")",
",",
"THREAD_LEAK_CLEANING_MS",
")",
";",
"}"
] |
Prior to Android 5, HandlerThread always keeps a stack local reference to the last message
that was sent to it. This method makes sure that stack local reference never stays there
for too long by sending new messages to it every second.
|
[
"Prior",
"to",
"Android",
"5",
"HandlerThread",
"always",
"keeps",
"a",
"stack",
"local",
"reference",
"to",
"the",
"last",
"message",
"that",
"was",
"sent",
"to",
"it",
".",
"This",
"method",
"makes",
"sure",
"that",
"stack",
"local",
"reference",
"never",
"stays",
"there",
"for",
"too",
"long",
"by",
"sending",
"new",
"messages",
"to",
"it",
"every",
"second",
"."
] |
89f55b76e3be2b65e5997b7698f782f16f8547e3
|
https://github.com/square/picasso/blob/89f55b76e3be2b65e5997b7698f782f16f8547e3/picasso/src/main/java/com/squareup/picasso3/Utils.java#L268-L275
|
13,368
|
ltsopensource/light-task-scheduler
|
lts-jobtracker/src/main/java/com/github/ltsopensource/jobtracker/support/checker/ExecutableDeadJobChecker.java
|
ExecutableDeadJobChecker.fix
|
private void fix() {
Set<String> nodeGroups = appContext.getTaskTrackerManager().getNodeGroups();
if (CollectionUtils.isEmpty(nodeGroups)) {
return;
}
for (String nodeGroup : nodeGroups) {
List<JobPo> deadJobPo = appContext.getExecutableJobQueue().getDeadJob(nodeGroup, SystemClock.now() - MAX_TIME_OUT);
if (CollectionUtils.isNotEmpty(deadJobPo)) {
for (JobPo jobPo : deadJobPo) {
appContext.getExecutableJobQueue().resume(jobPo);
LOGGER.info("Fix executable job : {} ", JSON.toJSONString(jobPo));
}
}
}
}
|
java
|
private void fix() {
Set<String> nodeGroups = appContext.getTaskTrackerManager().getNodeGroups();
if (CollectionUtils.isEmpty(nodeGroups)) {
return;
}
for (String nodeGroup : nodeGroups) {
List<JobPo> deadJobPo = appContext.getExecutableJobQueue().getDeadJob(nodeGroup, SystemClock.now() - MAX_TIME_OUT);
if (CollectionUtils.isNotEmpty(deadJobPo)) {
for (JobPo jobPo : deadJobPo) {
appContext.getExecutableJobQueue().resume(jobPo);
LOGGER.info("Fix executable job : {} ", JSON.toJSONString(jobPo));
}
}
}
}
|
[
"private",
"void",
"fix",
"(",
")",
"{",
"Set",
"<",
"String",
">",
"nodeGroups",
"=",
"appContext",
".",
"getTaskTrackerManager",
"(",
")",
".",
"getNodeGroups",
"(",
")",
";",
"if",
"(",
"CollectionUtils",
".",
"isEmpty",
"(",
"nodeGroups",
")",
")",
"{",
"return",
";",
"}",
"for",
"(",
"String",
"nodeGroup",
":",
"nodeGroups",
")",
"{",
"List",
"<",
"JobPo",
">",
"deadJobPo",
"=",
"appContext",
".",
"getExecutableJobQueue",
"(",
")",
".",
"getDeadJob",
"(",
"nodeGroup",
",",
"SystemClock",
".",
"now",
"(",
")",
"-",
"MAX_TIME_OUT",
")",
";",
"if",
"(",
"CollectionUtils",
".",
"isNotEmpty",
"(",
"deadJobPo",
")",
")",
"{",
"for",
"(",
"JobPo",
"jobPo",
":",
"deadJobPo",
")",
"{",
"appContext",
".",
"getExecutableJobQueue",
"(",
")",
".",
"resume",
"(",
"jobPo",
")",
";",
"LOGGER",
".",
"info",
"(",
"\"Fix executable job : {} \"",
",",
"JSON",
".",
"toJSONString",
"(",
"jobPo",
")",
")",
";",
"}",
"}",
"}",
"}"
] |
fix the job that running is true and gmtModified too old
|
[
"fix",
"the",
"job",
"that",
"running",
"is",
"true",
"and",
"gmtModified",
"too",
"old"
] |
64d3aa000ff5022be5e94f511b58f405e5f4c8eb
|
https://github.com/ltsopensource/light-task-scheduler/blob/64d3aa000ff5022be5e94f511b58f405e5f4c8eb/lts-jobtracker/src/main/java/com/github/ltsopensource/jobtracker/support/checker/ExecutableDeadJobChecker.java#L70-L84
|
13,369
|
OpenTSDB/opentsdb
|
src/tree/TreeRule.java
|
TreeRule.copyChanges
|
public boolean copyChanges(final TreeRule rule, final boolean overwrite) {
if (rule == null) {
throw new IllegalArgumentException("Cannot copy a null rule");
}
if (tree_id != rule.tree_id) {
throw new IllegalArgumentException("Tree IDs do not match");
}
if (level != rule.level) {
throw new IllegalArgumentException("Levels do not match");
}
if (order != rule.order) {
throw new IllegalArgumentException("Orders do not match");
}
if (overwrite || (rule.changed.get("type") && type != rule.type)) {
type = rule.type;
changed.put("type", true);
}
if (overwrite || (rule.changed.get("field") && !field.equals(rule.field))) {
field = rule.field;
changed.put("field", true);
}
if (overwrite || (rule.changed.get("custom_field") &&
!custom_field.equals(rule.custom_field))) {
custom_field = rule.custom_field;
changed.put("custom_field", true);
}
if (overwrite || (rule.changed.get("regex") && !regex.equals(rule.regex))) {
// validate and compile via the setter
setRegex(rule.regex);
}
if (overwrite || (rule.changed.get("separator") &&
!separator.equals(rule.separator))) {
separator = rule.separator;
changed.put("separator", true);
}
if (overwrite || (rule.changed.get("description") &&
!description.equals(rule.description))) {
description = rule.description;
changed.put("description", true);
}
if (overwrite || (rule.changed.get("notes") && !notes.equals(rule.notes))) {
notes = rule.notes;
changed.put("notes", true);
}
if (overwrite || (rule.changed.get("regex_group_idx") &&
regex_group_idx != rule.regex_group_idx)) {
regex_group_idx = rule.regex_group_idx;
changed.put("regex_group_idx", true);
}
if (overwrite || (rule.changed.get("display_format") &&
!display_format.equals(rule.display_format))) {
display_format = rule.display_format;
changed.put("display_format", true);
}
for (boolean has_changes : changed.values()) {
if (has_changes) {
return true;
}
}
return false;
}
|
java
|
public boolean copyChanges(final TreeRule rule, final boolean overwrite) {
if (rule == null) {
throw new IllegalArgumentException("Cannot copy a null rule");
}
if (tree_id != rule.tree_id) {
throw new IllegalArgumentException("Tree IDs do not match");
}
if (level != rule.level) {
throw new IllegalArgumentException("Levels do not match");
}
if (order != rule.order) {
throw new IllegalArgumentException("Orders do not match");
}
if (overwrite || (rule.changed.get("type") && type != rule.type)) {
type = rule.type;
changed.put("type", true);
}
if (overwrite || (rule.changed.get("field") && !field.equals(rule.field))) {
field = rule.field;
changed.put("field", true);
}
if (overwrite || (rule.changed.get("custom_field") &&
!custom_field.equals(rule.custom_field))) {
custom_field = rule.custom_field;
changed.put("custom_field", true);
}
if (overwrite || (rule.changed.get("regex") && !regex.equals(rule.regex))) {
// validate and compile via the setter
setRegex(rule.regex);
}
if (overwrite || (rule.changed.get("separator") &&
!separator.equals(rule.separator))) {
separator = rule.separator;
changed.put("separator", true);
}
if (overwrite || (rule.changed.get("description") &&
!description.equals(rule.description))) {
description = rule.description;
changed.put("description", true);
}
if (overwrite || (rule.changed.get("notes") && !notes.equals(rule.notes))) {
notes = rule.notes;
changed.put("notes", true);
}
if (overwrite || (rule.changed.get("regex_group_idx") &&
regex_group_idx != rule.regex_group_idx)) {
regex_group_idx = rule.regex_group_idx;
changed.put("regex_group_idx", true);
}
if (overwrite || (rule.changed.get("display_format") &&
!display_format.equals(rule.display_format))) {
display_format = rule.display_format;
changed.put("display_format", true);
}
for (boolean has_changes : changed.values()) {
if (has_changes) {
return true;
}
}
return false;
}
|
[
"public",
"boolean",
"copyChanges",
"(",
"final",
"TreeRule",
"rule",
",",
"final",
"boolean",
"overwrite",
")",
"{",
"if",
"(",
"rule",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Cannot copy a null rule\"",
")",
";",
"}",
"if",
"(",
"tree_id",
"!=",
"rule",
".",
"tree_id",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Tree IDs do not match\"",
")",
";",
"}",
"if",
"(",
"level",
"!=",
"rule",
".",
"level",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Levels do not match\"",
")",
";",
"}",
"if",
"(",
"order",
"!=",
"rule",
".",
"order",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Orders do not match\"",
")",
";",
"}",
"if",
"(",
"overwrite",
"||",
"(",
"rule",
".",
"changed",
".",
"get",
"(",
"\"type\"",
")",
"&&",
"type",
"!=",
"rule",
".",
"type",
")",
")",
"{",
"type",
"=",
"rule",
".",
"type",
";",
"changed",
".",
"put",
"(",
"\"type\"",
",",
"true",
")",
";",
"}",
"if",
"(",
"overwrite",
"||",
"(",
"rule",
".",
"changed",
".",
"get",
"(",
"\"field\"",
")",
"&&",
"!",
"field",
".",
"equals",
"(",
"rule",
".",
"field",
")",
")",
")",
"{",
"field",
"=",
"rule",
".",
"field",
";",
"changed",
".",
"put",
"(",
"\"field\"",
",",
"true",
")",
";",
"}",
"if",
"(",
"overwrite",
"||",
"(",
"rule",
".",
"changed",
".",
"get",
"(",
"\"custom_field\"",
")",
"&&",
"!",
"custom_field",
".",
"equals",
"(",
"rule",
".",
"custom_field",
")",
")",
")",
"{",
"custom_field",
"=",
"rule",
".",
"custom_field",
";",
"changed",
".",
"put",
"(",
"\"custom_field\"",
",",
"true",
")",
";",
"}",
"if",
"(",
"overwrite",
"||",
"(",
"rule",
".",
"changed",
".",
"get",
"(",
"\"regex\"",
")",
"&&",
"!",
"regex",
".",
"equals",
"(",
"rule",
".",
"regex",
")",
")",
")",
"{",
"// validate and compile via the setter",
"setRegex",
"(",
"rule",
".",
"regex",
")",
";",
"}",
"if",
"(",
"overwrite",
"||",
"(",
"rule",
".",
"changed",
".",
"get",
"(",
"\"separator\"",
")",
"&&",
"!",
"separator",
".",
"equals",
"(",
"rule",
".",
"separator",
")",
")",
")",
"{",
"separator",
"=",
"rule",
".",
"separator",
";",
"changed",
".",
"put",
"(",
"\"separator\"",
",",
"true",
")",
";",
"}",
"if",
"(",
"overwrite",
"||",
"(",
"rule",
".",
"changed",
".",
"get",
"(",
"\"description\"",
")",
"&&",
"!",
"description",
".",
"equals",
"(",
"rule",
".",
"description",
")",
")",
")",
"{",
"description",
"=",
"rule",
".",
"description",
";",
"changed",
".",
"put",
"(",
"\"description\"",
",",
"true",
")",
";",
"}",
"if",
"(",
"overwrite",
"||",
"(",
"rule",
".",
"changed",
".",
"get",
"(",
"\"notes\"",
")",
"&&",
"!",
"notes",
".",
"equals",
"(",
"rule",
".",
"notes",
")",
")",
")",
"{",
"notes",
"=",
"rule",
".",
"notes",
";",
"changed",
".",
"put",
"(",
"\"notes\"",
",",
"true",
")",
";",
"}",
"if",
"(",
"overwrite",
"||",
"(",
"rule",
".",
"changed",
".",
"get",
"(",
"\"regex_group_idx\"",
")",
"&&",
"regex_group_idx",
"!=",
"rule",
".",
"regex_group_idx",
")",
")",
"{",
"regex_group_idx",
"=",
"rule",
".",
"regex_group_idx",
";",
"changed",
".",
"put",
"(",
"\"regex_group_idx\"",
",",
"true",
")",
";",
"}",
"if",
"(",
"overwrite",
"||",
"(",
"rule",
".",
"changed",
".",
"get",
"(",
"\"display_format\"",
")",
"&&",
"!",
"display_format",
".",
"equals",
"(",
"rule",
".",
"display_format",
")",
")",
")",
"{",
"display_format",
"=",
"rule",
".",
"display_format",
";",
"changed",
".",
"put",
"(",
"\"display_format\"",
",",
"true",
")",
";",
"}",
"for",
"(",
"boolean",
"has_changes",
":",
"changed",
".",
"values",
"(",
")",
")",
"{",
"if",
"(",
"has_changes",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Copies changed fields from the incoming rule to the local rule
@param rule The rule to copy from
@param overwrite Whether or not to replace all fields in the local object
@return True if there were changes, false if everything was identical
|
[
"Copies",
"changed",
"fields",
"from",
"the",
"incoming",
"rule",
"to",
"the",
"local",
"rule"
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tree/TreeRule.java#L162-L223
|
13,370
|
OpenTSDB/opentsdb
|
src/tree/TreeRule.java
|
TreeRule.parseFromStorage
|
public static TreeRule parseFromStorage(final KeyValue column) {
if (column.value() == null) {
throw new IllegalArgumentException("Tree rule column value was null");
}
final TreeRule rule = JSON.parseToObject(column.value(), TreeRule.class);
rule.initializeChangedMap();
return rule;
}
|
java
|
public static TreeRule parseFromStorage(final KeyValue column) {
if (column.value() == null) {
throw new IllegalArgumentException("Tree rule column value was null");
}
final TreeRule rule = JSON.parseToObject(column.value(), TreeRule.class);
rule.initializeChangedMap();
return rule;
}
|
[
"public",
"static",
"TreeRule",
"parseFromStorage",
"(",
"final",
"KeyValue",
"column",
")",
"{",
"if",
"(",
"column",
".",
"value",
"(",
")",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Tree rule column value was null\"",
")",
";",
"}",
"final",
"TreeRule",
"rule",
"=",
"JSON",
".",
"parseToObject",
"(",
"column",
".",
"value",
"(",
")",
",",
"TreeRule",
".",
"class",
")",
";",
"rule",
".",
"initializeChangedMap",
"(",
")",
";",
"return",
"rule",
";",
"}"
] |
Parses a rule from the given column. Used by the Tree class when scanning
a row for rules.
@param column The column to parse
@return A valid TreeRule object if parsed successfully
@throws IllegalArgumentException if the column was empty
@throws JSONException if the object could not be serialized
|
[
"Parses",
"a",
"rule",
"from",
"the",
"given",
"column",
".",
"Used",
"by",
"the",
"Tree",
"class",
"when",
"scanning",
"a",
"row",
"for",
"rules",
"."
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tree/TreeRule.java#L328-L336
|
13,371
|
OpenTSDB/opentsdb
|
src/tree/TreeRule.java
|
TreeRule.fetchRule
|
public static Deferred<TreeRule> fetchRule(final TSDB tsdb, final int tree_id,
final int level, final int order) {
if (tree_id < 1 || tree_id > 65535) {
throw new IllegalArgumentException("Invalid Tree ID");
}
if (level < 0) {
throw new IllegalArgumentException("Invalid rule level");
}
if (order < 0) {
throw new IllegalArgumentException("Invalid rule order");
}
// fetch the whole row
final GetRequest get = new GetRequest(tsdb.treeTable(),
Tree.idToBytes(tree_id));
get.family(Tree.TREE_FAMILY());
get.qualifier(getQualifier(level, order));
/**
* Called after fetching to parse the results
*/
final class FetchCB implements Callback<Deferred<TreeRule>,
ArrayList<KeyValue>> {
@Override
public Deferred<TreeRule> call(final ArrayList<KeyValue> row) {
if (row == null || row.isEmpty()) {
return Deferred.fromResult(null);
}
return Deferred.fromResult(parseFromStorage(row.get(0)));
}
}
return tsdb.getClient().get(get).addCallbackDeferring(new FetchCB());
}
|
java
|
public static Deferred<TreeRule> fetchRule(final TSDB tsdb, final int tree_id,
final int level, final int order) {
if (tree_id < 1 || tree_id > 65535) {
throw new IllegalArgumentException("Invalid Tree ID");
}
if (level < 0) {
throw new IllegalArgumentException("Invalid rule level");
}
if (order < 0) {
throw new IllegalArgumentException("Invalid rule order");
}
// fetch the whole row
final GetRequest get = new GetRequest(tsdb.treeTable(),
Tree.idToBytes(tree_id));
get.family(Tree.TREE_FAMILY());
get.qualifier(getQualifier(level, order));
/**
* Called after fetching to parse the results
*/
final class FetchCB implements Callback<Deferred<TreeRule>,
ArrayList<KeyValue>> {
@Override
public Deferred<TreeRule> call(final ArrayList<KeyValue> row) {
if (row == null || row.isEmpty()) {
return Deferred.fromResult(null);
}
return Deferred.fromResult(parseFromStorage(row.get(0)));
}
}
return tsdb.getClient().get(get).addCallbackDeferring(new FetchCB());
}
|
[
"public",
"static",
"Deferred",
"<",
"TreeRule",
">",
"fetchRule",
"(",
"final",
"TSDB",
"tsdb",
",",
"final",
"int",
"tree_id",
",",
"final",
"int",
"level",
",",
"final",
"int",
"order",
")",
"{",
"if",
"(",
"tree_id",
"<",
"1",
"||",
"tree_id",
">",
"65535",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid Tree ID\"",
")",
";",
"}",
"if",
"(",
"level",
"<",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid rule level\"",
")",
";",
"}",
"if",
"(",
"order",
"<",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid rule order\"",
")",
";",
"}",
"// fetch the whole row",
"final",
"GetRequest",
"get",
"=",
"new",
"GetRequest",
"(",
"tsdb",
".",
"treeTable",
"(",
")",
",",
"Tree",
".",
"idToBytes",
"(",
"tree_id",
")",
")",
";",
"get",
".",
"family",
"(",
"Tree",
".",
"TREE_FAMILY",
"(",
")",
")",
";",
"get",
".",
"qualifier",
"(",
"getQualifier",
"(",
"level",
",",
"order",
")",
")",
";",
"/**\n * Called after fetching to parse the results\n */",
"final",
"class",
"FetchCB",
"implements",
"Callback",
"<",
"Deferred",
"<",
"TreeRule",
">",
",",
"ArrayList",
"<",
"KeyValue",
">",
">",
"{",
"@",
"Override",
"public",
"Deferred",
"<",
"TreeRule",
">",
"call",
"(",
"final",
"ArrayList",
"<",
"KeyValue",
">",
"row",
")",
"{",
"if",
"(",
"row",
"==",
"null",
"||",
"row",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"Deferred",
".",
"fromResult",
"(",
"null",
")",
";",
"}",
"return",
"Deferred",
".",
"fromResult",
"(",
"parseFromStorage",
"(",
"row",
".",
"get",
"(",
"0",
")",
")",
")",
";",
"}",
"}",
"return",
"tsdb",
".",
"getClient",
"(",
")",
".",
"get",
"(",
"get",
")",
".",
"addCallbackDeferring",
"(",
"new",
"FetchCB",
"(",
")",
")",
";",
"}"
] |
Attempts to retrieve the specified tree rule from storage.
@param tsdb The TSDB to use for storage access
@param tree_id ID of the tree the rule belongs to
@param level Level where the rule resides
@param order Order where the rule resides
@return A TreeRule object if found, null if it does not exist
@throws HBaseException if there was an issue
@throws IllegalArgumentException if the one of the required parameters was
missing
@throws JSONException if the object could not be serialized
|
[
"Attempts",
"to",
"retrieve",
"the",
"specified",
"tree",
"rule",
"from",
"storage",
"."
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tree/TreeRule.java#L350-L384
|
13,372
|
OpenTSDB/opentsdb
|
src/tree/TreeRule.java
|
TreeRule.deleteRule
|
public static Deferred<Object> deleteRule(final TSDB tsdb, final int tree_id,
final int level, final int order) {
if (tree_id < 1 || tree_id > 65535) {
throw new IllegalArgumentException("Invalid Tree ID");
}
if (level < 0) {
throw new IllegalArgumentException("Invalid rule level");
}
if (order < 0) {
throw new IllegalArgumentException("Invalid rule order");
}
final DeleteRequest delete = new DeleteRequest(tsdb.treeTable(),
Tree.idToBytes(tree_id), Tree.TREE_FAMILY(), getQualifier(level, order));
return tsdb.getClient().delete(delete);
}
|
java
|
public static Deferred<Object> deleteRule(final TSDB tsdb, final int tree_id,
final int level, final int order) {
if (tree_id < 1 || tree_id > 65535) {
throw new IllegalArgumentException("Invalid Tree ID");
}
if (level < 0) {
throw new IllegalArgumentException("Invalid rule level");
}
if (order < 0) {
throw new IllegalArgumentException("Invalid rule order");
}
final DeleteRequest delete = new DeleteRequest(tsdb.treeTable(),
Tree.idToBytes(tree_id), Tree.TREE_FAMILY(), getQualifier(level, order));
return tsdb.getClient().delete(delete);
}
|
[
"public",
"static",
"Deferred",
"<",
"Object",
">",
"deleteRule",
"(",
"final",
"TSDB",
"tsdb",
",",
"final",
"int",
"tree_id",
",",
"final",
"int",
"level",
",",
"final",
"int",
"order",
")",
"{",
"if",
"(",
"tree_id",
"<",
"1",
"||",
"tree_id",
">",
"65535",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid Tree ID\"",
")",
";",
"}",
"if",
"(",
"level",
"<",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid rule level\"",
")",
";",
"}",
"if",
"(",
"order",
"<",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid rule order\"",
")",
";",
"}",
"final",
"DeleteRequest",
"delete",
"=",
"new",
"DeleteRequest",
"(",
"tsdb",
".",
"treeTable",
"(",
")",
",",
"Tree",
".",
"idToBytes",
"(",
"tree_id",
")",
",",
"Tree",
".",
"TREE_FAMILY",
"(",
")",
",",
"getQualifier",
"(",
"level",
",",
"order",
")",
")",
";",
"return",
"tsdb",
".",
"getClient",
"(",
")",
".",
"delete",
"(",
"delete",
")",
";",
"}"
] |
Attempts to delete the specified rule from storage
@param tsdb The TSDB to use for storage access
@param tree_id ID of the tree the rule belongs to
@param level Level where the rule resides
@param order Order where the rule resides
@return A deferred without meaning. The response may be null and should
only be used to track completion.
@throws HBaseException if there was an issue
@throws IllegalArgumentException if the one of the required parameters was
missing
|
[
"Attempts",
"to",
"delete",
"the",
"specified",
"rule",
"from",
"storage"
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tree/TreeRule.java#L398-L413
|
13,373
|
OpenTSDB/opentsdb
|
src/tree/TreeRule.java
|
TreeRule.deleteAllRules
|
public static Deferred<Object> deleteAllRules(final TSDB tsdb,
final int tree_id) {
if (tree_id < 1 || tree_id > 65535) {
throw new IllegalArgumentException("Invalid Tree ID");
}
// fetch the whole row
final GetRequest get = new GetRequest(tsdb.treeTable(),
Tree.idToBytes(tree_id));
get.family(Tree.TREE_FAMILY());
/**
* Called after fetching the requested row. If the row is empty, we just
* return, otherwise we compile a list of qualifiers to delete and submit
* a single delete request to storage.
*/
final class GetCB implements Callback<Deferred<Object>,
ArrayList<KeyValue>> {
@Override
public Deferred<Object> call(final ArrayList<KeyValue> row)
throws Exception {
if (row == null || row.isEmpty()) {
return Deferred.fromResult(null);
}
final ArrayList<byte[]> qualifiers = new ArrayList<byte[]>(row.size());
for (KeyValue column : row) {
if (column.qualifier().length > RULE_PREFIX.length &&
Bytes.memcmp(RULE_PREFIX, column.qualifier(), 0,
RULE_PREFIX.length) == 0) {
qualifiers.add(column.qualifier());
}
}
final DeleteRequest delete = new DeleteRequest(tsdb.treeTable(),
Tree.idToBytes(tree_id), Tree.TREE_FAMILY(),
qualifiers.toArray(new byte[qualifiers.size()][]));
return tsdb.getClient().delete(delete);
}
}
return tsdb.getClient().get(get).addCallbackDeferring(new GetCB());
}
|
java
|
public static Deferred<Object> deleteAllRules(final TSDB tsdb,
final int tree_id) {
if (tree_id < 1 || tree_id > 65535) {
throw new IllegalArgumentException("Invalid Tree ID");
}
// fetch the whole row
final GetRequest get = new GetRequest(tsdb.treeTable(),
Tree.idToBytes(tree_id));
get.family(Tree.TREE_FAMILY());
/**
* Called after fetching the requested row. If the row is empty, we just
* return, otherwise we compile a list of qualifiers to delete and submit
* a single delete request to storage.
*/
final class GetCB implements Callback<Deferred<Object>,
ArrayList<KeyValue>> {
@Override
public Deferred<Object> call(final ArrayList<KeyValue> row)
throws Exception {
if (row == null || row.isEmpty()) {
return Deferred.fromResult(null);
}
final ArrayList<byte[]> qualifiers = new ArrayList<byte[]>(row.size());
for (KeyValue column : row) {
if (column.qualifier().length > RULE_PREFIX.length &&
Bytes.memcmp(RULE_PREFIX, column.qualifier(), 0,
RULE_PREFIX.length) == 0) {
qualifiers.add(column.qualifier());
}
}
final DeleteRequest delete = new DeleteRequest(tsdb.treeTable(),
Tree.idToBytes(tree_id), Tree.TREE_FAMILY(),
qualifiers.toArray(new byte[qualifiers.size()][]));
return tsdb.getClient().delete(delete);
}
}
return tsdb.getClient().get(get).addCallbackDeferring(new GetCB());
}
|
[
"public",
"static",
"Deferred",
"<",
"Object",
">",
"deleteAllRules",
"(",
"final",
"TSDB",
"tsdb",
",",
"final",
"int",
"tree_id",
")",
"{",
"if",
"(",
"tree_id",
"<",
"1",
"||",
"tree_id",
">",
"65535",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid Tree ID\"",
")",
";",
"}",
"// fetch the whole row",
"final",
"GetRequest",
"get",
"=",
"new",
"GetRequest",
"(",
"tsdb",
".",
"treeTable",
"(",
")",
",",
"Tree",
".",
"idToBytes",
"(",
"tree_id",
")",
")",
";",
"get",
".",
"family",
"(",
"Tree",
".",
"TREE_FAMILY",
"(",
")",
")",
";",
"/**\n * Called after fetching the requested row. If the row is empty, we just\n * return, otherwise we compile a list of qualifiers to delete and submit\n * a single delete request to storage.\n */",
"final",
"class",
"GetCB",
"implements",
"Callback",
"<",
"Deferred",
"<",
"Object",
">",
",",
"ArrayList",
"<",
"KeyValue",
">",
">",
"{",
"@",
"Override",
"public",
"Deferred",
"<",
"Object",
">",
"call",
"(",
"final",
"ArrayList",
"<",
"KeyValue",
">",
"row",
")",
"throws",
"Exception",
"{",
"if",
"(",
"row",
"==",
"null",
"||",
"row",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"Deferred",
".",
"fromResult",
"(",
"null",
")",
";",
"}",
"final",
"ArrayList",
"<",
"byte",
"[",
"]",
">",
"qualifiers",
"=",
"new",
"ArrayList",
"<",
"byte",
"[",
"]",
">",
"(",
"row",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"KeyValue",
"column",
":",
"row",
")",
"{",
"if",
"(",
"column",
".",
"qualifier",
"(",
")",
".",
"length",
">",
"RULE_PREFIX",
".",
"length",
"&&",
"Bytes",
".",
"memcmp",
"(",
"RULE_PREFIX",
",",
"column",
".",
"qualifier",
"(",
")",
",",
"0",
",",
"RULE_PREFIX",
".",
"length",
")",
"==",
"0",
")",
"{",
"qualifiers",
".",
"add",
"(",
"column",
".",
"qualifier",
"(",
")",
")",
";",
"}",
"}",
"final",
"DeleteRequest",
"delete",
"=",
"new",
"DeleteRequest",
"(",
"tsdb",
".",
"treeTable",
"(",
")",
",",
"Tree",
".",
"idToBytes",
"(",
"tree_id",
")",
",",
"Tree",
".",
"TREE_FAMILY",
"(",
")",
",",
"qualifiers",
".",
"toArray",
"(",
"new",
"byte",
"[",
"qualifiers",
".",
"size",
"(",
")",
"]",
"[",
"",
"]",
")",
")",
";",
"return",
"tsdb",
".",
"getClient",
"(",
")",
".",
"delete",
"(",
"delete",
")",
";",
"}",
"}",
"return",
"tsdb",
".",
"getClient",
"(",
")",
".",
"get",
"(",
"get",
")",
".",
"addCallbackDeferring",
"(",
"new",
"GetCB",
"(",
")",
")",
";",
"}"
] |
Attempts to delete all rules belonging to the given tree.
@param tsdb The TSDB to use for storage access
@param tree_id ID of the tree the rules belongs to
@return A deferred to wait on for completion. The value has no meaning and
may be null.
@throws HBaseException if there was an issue
@throws IllegalArgumentException if the one of the required parameters was
missing
|
[
"Attempts",
"to",
"delete",
"all",
"rules",
"belonging",
"to",
"the",
"given",
"tree",
"."
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tree/TreeRule.java#L425-L470
|
13,374
|
OpenTSDB/opentsdb
|
src/tree/TreeRule.java
|
TreeRule.stringToType
|
public static TreeRuleType stringToType(final String type) {
if (type == null || type.isEmpty()) {
throw new IllegalArgumentException("Rule type was empty");
} else if (type.toLowerCase().equals("metric")) {
return TreeRuleType.METRIC;
} else if (type.toLowerCase().equals("metric_custom")) {
return TreeRuleType.METRIC_CUSTOM;
} else if (type.toLowerCase().equals("tagk")) {
return TreeRuleType.TAGK;
} else if (type.toLowerCase().equals("tagk_custom")) {
return TreeRuleType.TAGK_CUSTOM;
} else if (type.toLowerCase().equals("tagv_custom")) {
return TreeRuleType.TAGV_CUSTOM;
} else {
throw new IllegalArgumentException("Unrecognized rule type");
}
}
|
java
|
public static TreeRuleType stringToType(final String type) {
if (type == null || type.isEmpty()) {
throw new IllegalArgumentException("Rule type was empty");
} else if (type.toLowerCase().equals("metric")) {
return TreeRuleType.METRIC;
} else if (type.toLowerCase().equals("metric_custom")) {
return TreeRuleType.METRIC_CUSTOM;
} else if (type.toLowerCase().equals("tagk")) {
return TreeRuleType.TAGK;
} else if (type.toLowerCase().equals("tagk_custom")) {
return TreeRuleType.TAGK_CUSTOM;
} else if (type.toLowerCase().equals("tagv_custom")) {
return TreeRuleType.TAGV_CUSTOM;
} else {
throw new IllegalArgumentException("Unrecognized rule type");
}
}
|
[
"public",
"static",
"TreeRuleType",
"stringToType",
"(",
"final",
"String",
"type",
")",
"{",
"if",
"(",
"type",
"==",
"null",
"||",
"type",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Rule type was empty\"",
")",
";",
"}",
"else",
"if",
"(",
"type",
".",
"toLowerCase",
"(",
")",
".",
"equals",
"(",
"\"metric\"",
")",
")",
"{",
"return",
"TreeRuleType",
".",
"METRIC",
";",
"}",
"else",
"if",
"(",
"type",
".",
"toLowerCase",
"(",
")",
".",
"equals",
"(",
"\"metric_custom\"",
")",
")",
"{",
"return",
"TreeRuleType",
".",
"METRIC_CUSTOM",
";",
"}",
"else",
"if",
"(",
"type",
".",
"toLowerCase",
"(",
")",
".",
"equals",
"(",
"\"tagk\"",
")",
")",
"{",
"return",
"TreeRuleType",
".",
"TAGK",
";",
"}",
"else",
"if",
"(",
"type",
".",
"toLowerCase",
"(",
")",
".",
"equals",
"(",
"\"tagk_custom\"",
")",
")",
"{",
"return",
"TreeRuleType",
".",
"TAGK_CUSTOM",
";",
"}",
"else",
"if",
"(",
"type",
".",
"toLowerCase",
"(",
")",
".",
"equals",
"(",
"\"tagv_custom\"",
")",
")",
"{",
"return",
"TreeRuleType",
".",
"TAGV_CUSTOM",
";",
"}",
"else",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Unrecognized rule type\"",
")",
";",
"}",
"}"
] |
Parses a string into a rule type enumerator
@param type The string to parse
@return The type enumerator
@throws IllegalArgumentException if the type was empty or invalid
|
[
"Parses",
"a",
"string",
"into",
"a",
"rule",
"type",
"enumerator"
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tree/TreeRule.java#L478-L494
|
13,375
|
OpenTSDB/opentsdb
|
src/tree/TreeRule.java
|
TreeRule.getQualifier
|
public static byte[] getQualifier(final int level, final int order) {
final byte[] suffix = (level + ":" + order).getBytes(CHARSET);
final byte[] qualifier = new byte[RULE_PREFIX.length + suffix.length];
System.arraycopy(RULE_PREFIX, 0, qualifier, 0, RULE_PREFIX.length);
System.arraycopy(suffix, 0, qualifier, RULE_PREFIX.length, suffix.length);
return qualifier;
}
|
java
|
public static byte[] getQualifier(final int level, final int order) {
final byte[] suffix = (level + ":" + order).getBytes(CHARSET);
final byte[] qualifier = new byte[RULE_PREFIX.length + suffix.length];
System.arraycopy(RULE_PREFIX, 0, qualifier, 0, RULE_PREFIX.length);
System.arraycopy(suffix, 0, qualifier, RULE_PREFIX.length, suffix.length);
return qualifier;
}
|
[
"public",
"static",
"byte",
"[",
"]",
"getQualifier",
"(",
"final",
"int",
"level",
",",
"final",
"int",
"order",
")",
"{",
"final",
"byte",
"[",
"]",
"suffix",
"=",
"(",
"level",
"+",
"\":\"",
"+",
"order",
")",
".",
"getBytes",
"(",
"CHARSET",
")",
";",
"final",
"byte",
"[",
"]",
"qualifier",
"=",
"new",
"byte",
"[",
"RULE_PREFIX",
".",
"length",
"+",
"suffix",
".",
"length",
"]",
";",
"System",
".",
"arraycopy",
"(",
"RULE_PREFIX",
",",
"0",
",",
"qualifier",
",",
"0",
",",
"RULE_PREFIX",
".",
"length",
")",
";",
"System",
".",
"arraycopy",
"(",
"suffix",
",",
"0",
",",
"qualifier",
",",
"RULE_PREFIX",
".",
"length",
",",
"suffix",
".",
"length",
")",
";",
"return",
"qualifier",
";",
"}"
] |
Completes the column qualifier given a level and order using the configured
prefix
@param level The level of the rule
@param order The order of the rule
@return A byte array with the column qualifier
|
[
"Completes",
"the",
"column",
"qualifier",
"given",
"a",
"level",
"and",
"order",
"using",
"the",
"configured",
"prefix"
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tree/TreeRule.java#L508-L514
|
13,376
|
OpenTSDB/opentsdb
|
src/query/expression/TimeShift.java
|
TimeShift.evaluate
|
@Override
public DataPoints[] evaluate(TSQuery data_query, List<DataPoints[]> results, List<String> params) {
//not 100% sure what to do here -> do I need to think of the case where I have no data points
if (results == null || results.isEmpty()) {
return new DataPoints[]{};
}
if (params == null || params.isEmpty()) {
throw new IllegalArgumentException("Need amount of timeshift to perform timeshift");
}
String param = params.get(0);
if (param == null || param.length() == 0) {
throw new IllegalArgumentException("Invalid timeshift='" + param + "'");
}
param = param.trim();
long timeshift = -1;
if (param.startsWith("'") && param.endsWith("'")) {
timeshift = parseParam(param);
} else {
throw new RuntimeException("Invalid timeshift parameter: eg '10min'");
}
if (timeshift <= 0) {
throw new RuntimeException("timeshift <= 0");
}
return performShift(results.get(0), timeshift);
}
|
java
|
@Override
public DataPoints[] evaluate(TSQuery data_query, List<DataPoints[]> results, List<String> params) {
//not 100% sure what to do here -> do I need to think of the case where I have no data points
if (results == null || results.isEmpty()) {
return new DataPoints[]{};
}
if (params == null || params.isEmpty()) {
throw new IllegalArgumentException("Need amount of timeshift to perform timeshift");
}
String param = params.get(0);
if (param == null || param.length() == 0) {
throw new IllegalArgumentException("Invalid timeshift='" + param + "'");
}
param = param.trim();
long timeshift = -1;
if (param.startsWith("'") && param.endsWith("'")) {
timeshift = parseParam(param);
} else {
throw new RuntimeException("Invalid timeshift parameter: eg '10min'");
}
if (timeshift <= 0) {
throw new RuntimeException("timeshift <= 0");
}
return performShift(results.get(0), timeshift);
}
|
[
"@",
"Override",
"public",
"DataPoints",
"[",
"]",
"evaluate",
"(",
"TSQuery",
"data_query",
",",
"List",
"<",
"DataPoints",
"[",
"]",
">",
"results",
",",
"List",
"<",
"String",
">",
"params",
")",
"{",
"//not 100% sure what to do here -> do I need to think of the case where I have no data points",
"if",
"(",
"results",
"==",
"null",
"||",
"results",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"new",
"DataPoints",
"[",
"]",
"{",
"}",
";",
"}",
"if",
"(",
"params",
"==",
"null",
"||",
"params",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Need amount of timeshift to perform timeshift\"",
")",
";",
"}",
"String",
"param",
"=",
"params",
".",
"get",
"(",
"0",
")",
";",
"if",
"(",
"param",
"==",
"null",
"||",
"param",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid timeshift='\"",
"+",
"param",
"+",
"\"'\"",
")",
";",
"}",
"param",
"=",
"param",
".",
"trim",
"(",
")",
";",
"long",
"timeshift",
"=",
"-",
"1",
";",
"if",
"(",
"param",
".",
"startsWith",
"(",
"\"'\"",
")",
"&&",
"param",
".",
"endsWith",
"(",
"\"'\"",
")",
")",
"{",
"timeshift",
"=",
"parseParam",
"(",
"param",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Invalid timeshift parameter: eg '10min'\"",
")",
";",
"}",
"if",
"(",
"timeshift",
"<=",
"0",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"timeshift <= 0\"",
")",
";",
"}",
"return",
"performShift",
"(",
"results",
".",
"get",
"(",
"0",
")",
",",
"timeshift",
")",
";",
"}"
] |
in place modify of TsdbResult array to increase timestamps by timeshift
@param data_query
@param results
@param params
@return
|
[
"in",
"place",
"modify",
"of",
"TsdbResult",
"array",
"to",
"increase",
"timestamps",
"by",
"timeshift"
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/query/expression/TimeShift.java#L33-L62
|
13,377
|
OpenTSDB/opentsdb
|
src/query/expression/TimeShift.java
|
TimeShift.shift
|
DataPoints shift(final DataPoints points, final long timeshift) {
// TODO(cl) - Using an array as the size function may not return the exact
// results and we should figure a way to avoid copying data anyway.
final List<DataPoint> dps = new ArrayList<DataPoint>();
for (DataPoint pt : points) {
dps.add(shift(pt, timeshift));
}
final DataPoint[] results = new DataPoint[dps.size()];
dps.toArray(results);
return new PostAggregatedDataPoints(points, results);
}
|
java
|
DataPoints shift(final DataPoints points, final long timeshift) {
// TODO(cl) - Using an array as the size function may not return the exact
// results and we should figure a way to avoid copying data anyway.
final List<DataPoint> dps = new ArrayList<DataPoint>();
for (DataPoint pt : points) {
dps.add(shift(pt, timeshift));
}
final DataPoint[] results = new DataPoint[dps.size()];
dps.toArray(results);
return new PostAggregatedDataPoints(points, results);
}
|
[
"DataPoints",
"shift",
"(",
"final",
"DataPoints",
"points",
",",
"final",
"long",
"timeshift",
")",
"{",
"// TODO(cl) - Using an array as the size function may not return the exact",
"// results and we should figure a way to avoid copying data anyway.",
"final",
"List",
"<",
"DataPoint",
">",
"dps",
"=",
"new",
"ArrayList",
"<",
"DataPoint",
">",
"(",
")",
";",
"for",
"(",
"DataPoint",
"pt",
":",
"points",
")",
"{",
"dps",
".",
"add",
"(",
"shift",
"(",
"pt",
",",
"timeshift",
")",
")",
";",
"}",
"final",
"DataPoint",
"[",
"]",
"results",
"=",
"new",
"DataPoint",
"[",
"dps",
".",
"size",
"(",
")",
"]",
";",
"dps",
".",
"toArray",
"(",
"results",
")",
";",
"return",
"new",
"PostAggregatedDataPoints",
"(",
"points",
",",
"results",
")",
";",
"}"
] |
Adjusts the timestamp of each datapoint by timeshift
@param points The data points to factor
@param timeshift The factor to multiply by
@return The resulting data points
|
[
"Adjusts",
"the",
"timestamp",
"of",
"each",
"datapoint",
"by",
"timeshift"
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/query/expression/TimeShift.java#L117-L129
|
13,378
|
OpenTSDB/opentsdb
|
src/core/RowKey.java
|
RowKey.rowKeyFromTSUID
|
public static byte[] rowKeyFromTSUID(final TSDB tsdb, final byte[] tsuid,
final long timestamp) {
if (tsuid.length < tsdb.metrics.width()) {
throw new IllegalArgumentException("TSUID appears to be missing the metric");
}
final long base_time;
if ((timestamp & Const.SECOND_MASK) != 0) {
// drop the ms timestamp to seconds to calculate the base timestamp
base_time = ((timestamp / 1000) -
((timestamp / 1000) % Const.MAX_TIMESPAN));
} else {
base_time = (timestamp - (timestamp % Const.MAX_TIMESPAN));
}
final byte[] row =
new byte[Const.SALT_WIDTH() + tsuid.length + Const.TIMESTAMP_BYTES];
System.arraycopy(tsuid, 0, row, Const.SALT_WIDTH(), tsdb.metrics.width());
Bytes.setInt(row, (int) base_time, Const.SALT_WIDTH() + tsdb.metrics.width());
System.arraycopy(tsuid, tsdb.metrics.width(), row,
Const.SALT_WIDTH() + tsdb.metrics.width() + Const.TIMESTAMP_BYTES,
tsuid.length - tsdb.metrics.width());
RowKey.prefixKeyWithSalt(row);
return row;
}
|
java
|
public static byte[] rowKeyFromTSUID(final TSDB tsdb, final byte[] tsuid,
final long timestamp) {
if (tsuid.length < tsdb.metrics.width()) {
throw new IllegalArgumentException("TSUID appears to be missing the metric");
}
final long base_time;
if ((timestamp & Const.SECOND_MASK) != 0) {
// drop the ms timestamp to seconds to calculate the base timestamp
base_time = ((timestamp / 1000) -
((timestamp / 1000) % Const.MAX_TIMESPAN));
} else {
base_time = (timestamp - (timestamp % Const.MAX_TIMESPAN));
}
final byte[] row =
new byte[Const.SALT_WIDTH() + tsuid.length + Const.TIMESTAMP_BYTES];
System.arraycopy(tsuid, 0, row, Const.SALT_WIDTH(), tsdb.metrics.width());
Bytes.setInt(row, (int) base_time, Const.SALT_WIDTH() + tsdb.metrics.width());
System.arraycopy(tsuid, tsdb.metrics.width(), row,
Const.SALT_WIDTH() + tsdb.metrics.width() + Const.TIMESTAMP_BYTES,
tsuid.length - tsdb.metrics.width());
RowKey.prefixKeyWithSalt(row);
return row;
}
|
[
"public",
"static",
"byte",
"[",
"]",
"rowKeyFromTSUID",
"(",
"final",
"TSDB",
"tsdb",
",",
"final",
"byte",
"[",
"]",
"tsuid",
",",
"final",
"long",
"timestamp",
")",
"{",
"if",
"(",
"tsuid",
".",
"length",
"<",
"tsdb",
".",
"metrics",
".",
"width",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"TSUID appears to be missing the metric\"",
")",
";",
"}",
"final",
"long",
"base_time",
";",
"if",
"(",
"(",
"timestamp",
"&",
"Const",
".",
"SECOND_MASK",
")",
"!=",
"0",
")",
"{",
"// drop the ms timestamp to seconds to calculate the base timestamp",
"base_time",
"=",
"(",
"(",
"timestamp",
"/",
"1000",
")",
"-",
"(",
"(",
"timestamp",
"/",
"1000",
")",
"%",
"Const",
".",
"MAX_TIMESPAN",
")",
")",
";",
"}",
"else",
"{",
"base_time",
"=",
"(",
"timestamp",
"-",
"(",
"timestamp",
"%",
"Const",
".",
"MAX_TIMESPAN",
")",
")",
";",
"}",
"final",
"byte",
"[",
"]",
"row",
"=",
"new",
"byte",
"[",
"Const",
".",
"SALT_WIDTH",
"(",
")",
"+",
"tsuid",
".",
"length",
"+",
"Const",
".",
"TIMESTAMP_BYTES",
"]",
";",
"System",
".",
"arraycopy",
"(",
"tsuid",
",",
"0",
",",
"row",
",",
"Const",
".",
"SALT_WIDTH",
"(",
")",
",",
"tsdb",
".",
"metrics",
".",
"width",
"(",
")",
")",
";",
"Bytes",
".",
"setInt",
"(",
"row",
",",
"(",
"int",
")",
"base_time",
",",
"Const",
".",
"SALT_WIDTH",
"(",
")",
"+",
"tsdb",
".",
"metrics",
".",
"width",
"(",
")",
")",
";",
"System",
".",
"arraycopy",
"(",
"tsuid",
",",
"tsdb",
".",
"metrics",
".",
"width",
"(",
")",
",",
"row",
",",
"Const",
".",
"SALT_WIDTH",
"(",
")",
"+",
"tsdb",
".",
"metrics",
".",
"width",
"(",
")",
"+",
"Const",
".",
"TIMESTAMP_BYTES",
",",
"tsuid",
".",
"length",
"-",
"tsdb",
".",
"metrics",
".",
"width",
"(",
")",
")",
";",
"RowKey",
".",
"prefixKeyWithSalt",
"(",
"row",
")",
";",
"return",
"row",
";",
"}"
] |
Generates a row key given a TSUID and an absolute timestamp. The timestamp
will be normalized to an hourly base time. If salting is enabled then
empty salt bytes will be prepended to the key and must be filled in later.
@param tsdb The TSDB to use for fetching tag widths
@param tsuid The TSUID to use for the key
@param timestamp An absolute time from which we generate the row base time
@return A row key for use in fetching data from OpenTSDB
@throws IllegalArgumentException if the TSUID is too short, i.e. doesn't
contain a metric
@since 2.0
|
[
"Generates",
"a",
"row",
"key",
"given",
"a",
"TSUID",
"and",
"an",
"absolute",
"timestamp",
".",
"The",
"timestamp",
"will",
"be",
"normalized",
"to",
"an",
"hourly",
"base",
"time",
".",
"If",
"salting",
"is",
"enabled",
"then",
"empty",
"salt",
"bytes",
"will",
"be",
"prepended",
"to",
"the",
"key",
"and",
"must",
"be",
"filled",
"in",
"later",
"."
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/core/RowKey.java#L83-L105
|
13,379
|
OpenTSDB/opentsdb
|
src/core/RowKey.java
|
RowKey.prefixKeyWithSalt
|
public static void prefixKeyWithSalt(final byte[] row_key) {
if (Const.SALT_WIDTH() > 0) {
if (row_key.length < (Const.SALT_WIDTH() + TSDB.metrics_width()) ||
(Bytes.memcmp(row_key, new byte[Const.SALT_WIDTH() + TSDB.metrics_width()],
Const.SALT_WIDTH(), TSDB.metrics_width()) == 0)) {
// ^ Don't salt the global annotation row, leave it at zero
return;
}
final int tags_start = Const.SALT_WIDTH() + TSDB.metrics_width() +
Const.TIMESTAMP_BYTES;
// we want the metric and tags, not the timestamp
final byte[] salt_base =
new byte[row_key.length - Const.SALT_WIDTH() - Const.TIMESTAMP_BYTES];
System.arraycopy(row_key, Const.SALT_WIDTH(), salt_base, 0, TSDB.metrics_width());
System.arraycopy(row_key, tags_start,salt_base, TSDB.metrics_width(),
row_key.length - tags_start);
int modulo = Arrays.hashCode(salt_base) % Const.SALT_BUCKETS();
if (modulo < 0) {
// make sure we return a positive salt.
modulo = modulo * -1;
}
final byte[] salt = getSaltBytes(modulo);
System.arraycopy(salt, 0, row_key, 0, Const.SALT_WIDTH());
} // else salting is disabled so it's a no-op
}
|
java
|
public static void prefixKeyWithSalt(final byte[] row_key) {
if (Const.SALT_WIDTH() > 0) {
if (row_key.length < (Const.SALT_WIDTH() + TSDB.metrics_width()) ||
(Bytes.memcmp(row_key, new byte[Const.SALT_WIDTH() + TSDB.metrics_width()],
Const.SALT_WIDTH(), TSDB.metrics_width()) == 0)) {
// ^ Don't salt the global annotation row, leave it at zero
return;
}
final int tags_start = Const.SALT_WIDTH() + TSDB.metrics_width() +
Const.TIMESTAMP_BYTES;
// we want the metric and tags, not the timestamp
final byte[] salt_base =
new byte[row_key.length - Const.SALT_WIDTH() - Const.TIMESTAMP_BYTES];
System.arraycopy(row_key, Const.SALT_WIDTH(), salt_base, 0, TSDB.metrics_width());
System.arraycopy(row_key, tags_start,salt_base, TSDB.metrics_width(),
row_key.length - tags_start);
int modulo = Arrays.hashCode(salt_base) % Const.SALT_BUCKETS();
if (modulo < 0) {
// make sure we return a positive salt.
modulo = modulo * -1;
}
final byte[] salt = getSaltBytes(modulo);
System.arraycopy(salt, 0, row_key, 0, Const.SALT_WIDTH());
} // else salting is disabled so it's a no-op
}
|
[
"public",
"static",
"void",
"prefixKeyWithSalt",
"(",
"final",
"byte",
"[",
"]",
"row_key",
")",
"{",
"if",
"(",
"Const",
".",
"SALT_WIDTH",
"(",
")",
">",
"0",
")",
"{",
"if",
"(",
"row_key",
".",
"length",
"<",
"(",
"Const",
".",
"SALT_WIDTH",
"(",
")",
"+",
"TSDB",
".",
"metrics_width",
"(",
")",
")",
"||",
"(",
"Bytes",
".",
"memcmp",
"(",
"row_key",
",",
"new",
"byte",
"[",
"Const",
".",
"SALT_WIDTH",
"(",
")",
"+",
"TSDB",
".",
"metrics_width",
"(",
")",
"]",
",",
"Const",
".",
"SALT_WIDTH",
"(",
")",
",",
"TSDB",
".",
"metrics_width",
"(",
")",
")",
"==",
"0",
")",
")",
"{",
"// ^ Don't salt the global annotation row, leave it at zero",
"return",
";",
"}",
"final",
"int",
"tags_start",
"=",
"Const",
".",
"SALT_WIDTH",
"(",
")",
"+",
"TSDB",
".",
"metrics_width",
"(",
")",
"+",
"Const",
".",
"TIMESTAMP_BYTES",
";",
"// we want the metric and tags, not the timestamp",
"final",
"byte",
"[",
"]",
"salt_base",
"=",
"new",
"byte",
"[",
"row_key",
".",
"length",
"-",
"Const",
".",
"SALT_WIDTH",
"(",
")",
"-",
"Const",
".",
"TIMESTAMP_BYTES",
"]",
";",
"System",
".",
"arraycopy",
"(",
"row_key",
",",
"Const",
".",
"SALT_WIDTH",
"(",
")",
",",
"salt_base",
",",
"0",
",",
"TSDB",
".",
"metrics_width",
"(",
")",
")",
";",
"System",
".",
"arraycopy",
"(",
"row_key",
",",
"tags_start",
",",
"salt_base",
",",
"TSDB",
".",
"metrics_width",
"(",
")",
",",
"row_key",
".",
"length",
"-",
"tags_start",
")",
";",
"int",
"modulo",
"=",
"Arrays",
".",
"hashCode",
"(",
"salt_base",
")",
"%",
"Const",
".",
"SALT_BUCKETS",
"(",
")",
";",
"if",
"(",
"modulo",
"<",
"0",
")",
"{",
"// make sure we return a positive salt.",
"modulo",
"=",
"modulo",
"*",
"-",
"1",
";",
"}",
"final",
"byte",
"[",
"]",
"salt",
"=",
"getSaltBytes",
"(",
"modulo",
")",
";",
"System",
".",
"arraycopy",
"(",
"salt",
",",
"0",
",",
"row_key",
",",
"0",
",",
"Const",
".",
"SALT_WIDTH",
"(",
")",
")",
";",
"}",
"// else salting is disabled so it's a no-op",
"}"
] |
Calculates and writes an array of one or more salt bytes at the front of
the given row key.
The salt is calculated by taking the Java hash code of the metric and
tag UIDs and returning a modulo based on the number of salt buckets.
The result will always be a positive integer from 0 to salt buckets.
NOTE: The row key passed in MUST have allocated the {@code width} number of
bytes at the front of the row key or this call will overwrite data.
WARNING: If the width is set to a positive value, then the bucket must be
at least 1 or greater.
@param row_key The pre-allocated row key to write the salt to
@since 2.2
|
[
"Calculates",
"and",
"writes",
"an",
"array",
"of",
"one",
"or",
"more",
"salt",
"bytes",
"at",
"the",
"front",
"of",
"the",
"given",
"row",
"key",
"."
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/core/RowKey.java#L141-L167
|
13,380
|
OpenTSDB/opentsdb
|
src/core/RowKey.java
|
RowKey.rowKeyContainsMetric
|
public static int rowKeyContainsMetric(final byte[] metric,
final byte[] row_key) {
int idx = Const.SALT_WIDTH();
for (int i = 0; i < metric.length; i++, idx++) {
if (metric[i] != row_key[idx]) {
return (metric[i] & 0xFF) - (row_key[idx] & 0xFF); // "promote" to unsigned.
}
}
return 0;
}
|
java
|
public static int rowKeyContainsMetric(final byte[] metric,
final byte[] row_key) {
int idx = Const.SALT_WIDTH();
for (int i = 0; i < metric.length; i++, idx++) {
if (metric[i] != row_key[idx]) {
return (metric[i] & 0xFF) - (row_key[idx] & 0xFF); // "promote" to unsigned.
}
}
return 0;
}
|
[
"public",
"static",
"int",
"rowKeyContainsMetric",
"(",
"final",
"byte",
"[",
"]",
"metric",
",",
"final",
"byte",
"[",
"]",
"row_key",
")",
"{",
"int",
"idx",
"=",
"Const",
".",
"SALT_WIDTH",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"metric",
".",
"length",
";",
"i",
"++",
",",
"idx",
"++",
")",
"{",
"if",
"(",
"metric",
"[",
"i",
"]",
"!=",
"row_key",
"[",
"idx",
"]",
")",
"{",
"return",
"(",
"metric",
"[",
"i",
"]",
"&",
"0xFF",
")",
"-",
"(",
"row_key",
"[",
"idx",
"]",
"&",
"0xFF",
")",
";",
"// \"promote\" to unsigned.",
"}",
"}",
"return",
"0",
";",
"}"
] |
Checks a row key to determine if it contains the metric UID. If salting is
enabled, we skip the salt bytes.
@param metric The metric UID to match
@param row_key The row key to match on
@return 0 if the two arrays are identical, otherwise the difference
between the first two different bytes (treated as unsigned), otherwise
the different between their lengths.
@throws IndexOutOfBoundsException if either array isn't large enough.
|
[
"Checks",
"a",
"row",
"key",
"to",
"determine",
"if",
"it",
"contains",
"the",
"metric",
"UID",
".",
"If",
"salting",
"is",
"enabled",
"we",
"skip",
"the",
"salt",
"bytes",
"."
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/core/RowKey.java#L179-L188
|
13,381
|
OpenTSDB/opentsdb
|
src/uid/RandomUniqueId.java
|
RandomUniqueId.getRandomUID
|
public static long getRandomUID(final int width) {
if (width > MAX_WIDTH) {
throw new IllegalArgumentException("Expecting to return an unsigned long "
+ "random integer, it can not be larger than " + MAX_WIDTH +
" bytes wide");
}
final byte[] bytes = new byte[width];
random_generator.nextBytes(bytes);
long value = 0;
for (int i = 0; i<bytes.length; i++){
value <<= 8;
value |= bytes[i] & 0xFF;
}
// make sure we never return 0 as a UID
return value != 0 ? value : value + 1;
}
|
java
|
public static long getRandomUID(final int width) {
if (width > MAX_WIDTH) {
throw new IllegalArgumentException("Expecting to return an unsigned long "
+ "random integer, it can not be larger than " + MAX_WIDTH +
" bytes wide");
}
final byte[] bytes = new byte[width];
random_generator.nextBytes(bytes);
long value = 0;
for (int i = 0; i<bytes.length; i++){
value <<= 8;
value |= bytes[i] & 0xFF;
}
// make sure we never return 0 as a UID
return value != 0 ? value : value + 1;
}
|
[
"public",
"static",
"long",
"getRandomUID",
"(",
"final",
"int",
"width",
")",
"{",
"if",
"(",
"width",
">",
"MAX_WIDTH",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Expecting to return an unsigned long \"",
"+",
"\"random integer, it can not be larger than \"",
"+",
"MAX_WIDTH",
"+",
"\" bytes wide\"",
")",
";",
"}",
"final",
"byte",
"[",
"]",
"bytes",
"=",
"new",
"byte",
"[",
"width",
"]",
";",
"random_generator",
".",
"nextBytes",
"(",
"bytes",
")",
";",
"long",
"value",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"bytes",
".",
"length",
";",
"i",
"++",
")",
"{",
"value",
"<<=",
"8",
";",
"value",
"|=",
"bytes",
"[",
"i",
"]",
"&",
"0xFF",
";",
"}",
"// make sure we never return 0 as a UID",
"return",
"value",
"!=",
"0",
"?",
"value",
":",
"value",
"+",
"1",
";",
"}"
] |
Get the next random UID. It creates random bytes, then convert it to an
unsigned long.
@param width Number of bytes to randomize, it can not be larger
than {@link MAX_WIDTH} bytes wide
@return a randomly UID
@throws IllegalArgumentException if the width is larger than
{@link MAX_WIDTH} bytes
|
[
"Get",
"the",
"next",
"random",
"UID",
".",
"It",
"creates",
"random",
"bytes",
"then",
"convert",
"it",
"to",
"an",
"unsigned",
"long",
"."
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/uid/RandomUniqueId.java#L58-L75
|
13,382
|
OpenTSDB/opentsdb
|
src/query/expression/Expressions.java
|
Expressions.parse
|
public static ExpressionTree parse(final String expression,
final List<String> metric_queries,
final TSQuery data_query) {
if (expression == null || expression.isEmpty()) {
throw new IllegalArgumentException("Expression may not be null or empty");
}
if (expression.indexOf('(') == -1 || expression.indexOf(')') == -1) {
throw new IllegalArgumentException("Invalid Expression: " + expression);
}
final ExpressionReader reader = new ExpressionReader(expression.toCharArray());
// consume any whitespace ahead of the expression
reader.skipWhitespaces();
final String function_name = reader.readFuncName();
final Expression root_expression = ExpressionFactory.getByName(function_name);
final ExpressionTree root = new ExpressionTree(root_expression, data_query);
reader.skipWhitespaces();
if (reader.peek() == '(') {
reader.next();
parse(reader, metric_queries, root, data_query);
}
return root;
}
|
java
|
public static ExpressionTree parse(final String expression,
final List<String> metric_queries,
final TSQuery data_query) {
if (expression == null || expression.isEmpty()) {
throw new IllegalArgumentException("Expression may not be null or empty");
}
if (expression.indexOf('(') == -1 || expression.indexOf(')') == -1) {
throw new IllegalArgumentException("Invalid Expression: " + expression);
}
final ExpressionReader reader = new ExpressionReader(expression.toCharArray());
// consume any whitespace ahead of the expression
reader.skipWhitespaces();
final String function_name = reader.readFuncName();
final Expression root_expression = ExpressionFactory.getByName(function_name);
final ExpressionTree root = new ExpressionTree(root_expression, data_query);
reader.skipWhitespaces();
if (reader.peek() == '(') {
reader.next();
parse(reader, metric_queries, root, data_query);
}
return root;
}
|
[
"public",
"static",
"ExpressionTree",
"parse",
"(",
"final",
"String",
"expression",
",",
"final",
"List",
"<",
"String",
">",
"metric_queries",
",",
"final",
"TSQuery",
"data_query",
")",
"{",
"if",
"(",
"expression",
"==",
"null",
"||",
"expression",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Expression may not be null or empty\"",
")",
";",
"}",
"if",
"(",
"expression",
".",
"indexOf",
"(",
"'",
"'",
")",
"==",
"-",
"1",
"||",
"expression",
".",
"indexOf",
"(",
"'",
"'",
")",
"==",
"-",
"1",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid Expression: \"",
"+",
"expression",
")",
";",
"}",
"final",
"ExpressionReader",
"reader",
"=",
"new",
"ExpressionReader",
"(",
"expression",
".",
"toCharArray",
"(",
")",
")",
";",
"// consume any whitespace ahead of the expression",
"reader",
".",
"skipWhitespaces",
"(",
")",
";",
"final",
"String",
"function_name",
"=",
"reader",
".",
"readFuncName",
"(",
")",
";",
"final",
"Expression",
"root_expression",
"=",
"ExpressionFactory",
".",
"getByName",
"(",
"function_name",
")",
";",
"final",
"ExpressionTree",
"root",
"=",
"new",
"ExpressionTree",
"(",
"root_expression",
",",
"data_query",
")",
";",
"reader",
".",
"skipWhitespaces",
"(",
")",
";",
"if",
"(",
"reader",
".",
"peek",
"(",
")",
"==",
"'",
"'",
")",
"{",
"reader",
".",
"next",
"(",
")",
";",
"parse",
"(",
"reader",
",",
"metric_queries",
",",
"root",
",",
"data_query",
")",
";",
"}",
"return",
"root",
";",
"}"
] |
Parses an expression into a tree
@param expression The expression to parse (as a string)
@param metric_queries A list to store the parsed metrics in
@param data_query The time series query
@return The parsed tree ready for evaluation
@throws IllegalArgumentException if the expression was null, empty or
invalid.
@throws UnsupportedOperationException if the requested function couldn't
be found.
|
[
"Parses",
"an",
"expression",
"into",
"a",
"tree"
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/query/expression/Expressions.java#L43-L69
|
13,383
|
OpenTSDB/opentsdb
|
src/query/expression/Expressions.java
|
Expressions.parseParam
|
private static void parseParam(final String param,
final List<String> metric_queries,
final ExpressionTree root,
final TSQuery data_query,
final int index) {
if (param == null || param.length() == 0) {
throw new IllegalArgumentException("Parameter cannot be null or empty");
}
if (param.indexOf('(') > 0 && param.indexOf(')') > 0) {
// sub expression
final ExpressionTree sub_tree = parse(param, metric_queries, data_query);
root.addSubExpression(sub_tree, index);
} else if (param.indexOf(':') >= 0) {
// metric query
metric_queries.add(param);
root.addSubMetricQuery(param, metric_queries.size() - 1, index);
} else {
// expression parameter
root.addFunctionParameter(param);
}
}
|
java
|
private static void parseParam(final String param,
final List<String> metric_queries,
final ExpressionTree root,
final TSQuery data_query,
final int index) {
if (param == null || param.length() == 0) {
throw new IllegalArgumentException("Parameter cannot be null or empty");
}
if (param.indexOf('(') > 0 && param.indexOf(')') > 0) {
// sub expression
final ExpressionTree sub_tree = parse(param, metric_queries, data_query);
root.addSubExpression(sub_tree, index);
} else if (param.indexOf(':') >= 0) {
// metric query
metric_queries.add(param);
root.addSubMetricQuery(param, metric_queries.size() - 1, index);
} else {
// expression parameter
root.addFunctionParameter(param);
}
}
|
[
"private",
"static",
"void",
"parseParam",
"(",
"final",
"String",
"param",
",",
"final",
"List",
"<",
"String",
">",
"metric_queries",
",",
"final",
"ExpressionTree",
"root",
",",
"final",
"TSQuery",
"data_query",
",",
"final",
"int",
"index",
")",
"{",
"if",
"(",
"param",
"==",
"null",
"||",
"param",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Parameter cannot be null or empty\"",
")",
";",
"}",
"if",
"(",
"param",
".",
"indexOf",
"(",
"'",
"'",
")",
">",
"0",
"&&",
"param",
".",
"indexOf",
"(",
"'",
"'",
")",
">",
"0",
")",
"{",
"// sub expression",
"final",
"ExpressionTree",
"sub_tree",
"=",
"parse",
"(",
"param",
",",
"metric_queries",
",",
"data_query",
")",
";",
"root",
".",
"addSubExpression",
"(",
"sub_tree",
",",
"index",
")",
";",
"}",
"else",
"if",
"(",
"param",
".",
"indexOf",
"(",
"'",
"'",
")",
">=",
"0",
")",
"{",
"// metric query",
"metric_queries",
".",
"add",
"(",
"param",
")",
";",
"root",
".",
"addSubMetricQuery",
"(",
"param",
",",
"metric_queries",
".",
"size",
"(",
")",
"-",
"1",
",",
"index",
")",
";",
"}",
"else",
"{",
"// expression parameter",
"root",
".",
"addFunctionParameter",
"(",
"param",
")",
";",
"}",
"}"
] |
Helper that parses out the parameter from the expression
@param param The parameter to parse
@param metric_queries A list to store the parsed metrics in
@param root The root tree
@param data_query The time series query
@param index Index of the parameter
|
[
"Helper",
"that",
"parses",
"out",
"the",
"parameter",
"from",
"the",
"expression"
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/query/expression/Expressions.java#L142-L163
|
13,384
|
OpenTSDB/opentsdb
|
src/core/SpanGroup.java
|
SpanGroup.resolveAggTags
|
private Deferred<List<String>> resolveAggTags(final Set<byte[]> tagks) {
if (aggregated_tags != null) {
return Deferred.fromResult(null);
}
aggregated_tags = new ArrayList<String>(tagks.size());
final List<Deferred<String>> names =
new ArrayList<Deferred<String>>(tagks.size());
for (final byte[] tagk : tagks) {
names.add(tsdb.tag_names.getNameAsync(tagk));
}
/** Adds the names to the aggregated_tags list */
final class ResolveCB implements Callback<List<String>, ArrayList<String>> {
@Override
public List<String> call(final ArrayList<String> names) throws Exception {
for (final String name : names) {
aggregated_tags.add(name);
}
return aggregated_tags;
}
}
return Deferred.group(names).addCallback(new ResolveCB());
}
|
java
|
private Deferred<List<String>> resolveAggTags(final Set<byte[]> tagks) {
if (aggregated_tags != null) {
return Deferred.fromResult(null);
}
aggregated_tags = new ArrayList<String>(tagks.size());
final List<Deferred<String>> names =
new ArrayList<Deferred<String>>(tagks.size());
for (final byte[] tagk : tagks) {
names.add(tsdb.tag_names.getNameAsync(tagk));
}
/** Adds the names to the aggregated_tags list */
final class ResolveCB implements Callback<List<String>, ArrayList<String>> {
@Override
public List<String> call(final ArrayList<String> names) throws Exception {
for (final String name : names) {
aggregated_tags.add(name);
}
return aggregated_tags;
}
}
return Deferred.group(names).addCallback(new ResolveCB());
}
|
[
"private",
"Deferred",
"<",
"List",
"<",
"String",
">",
">",
"resolveAggTags",
"(",
"final",
"Set",
"<",
"byte",
"[",
"]",
">",
"tagks",
")",
"{",
"if",
"(",
"aggregated_tags",
"!=",
"null",
")",
"{",
"return",
"Deferred",
".",
"fromResult",
"(",
"null",
")",
";",
"}",
"aggregated_tags",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
"tagks",
".",
"size",
"(",
")",
")",
";",
"final",
"List",
"<",
"Deferred",
"<",
"String",
">",
">",
"names",
"=",
"new",
"ArrayList",
"<",
"Deferred",
"<",
"String",
">",
">",
"(",
"tagks",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"final",
"byte",
"[",
"]",
"tagk",
":",
"tagks",
")",
"{",
"names",
".",
"add",
"(",
"tsdb",
".",
"tag_names",
".",
"getNameAsync",
"(",
"tagk",
")",
")",
";",
"}",
"/** Adds the names to the aggregated_tags list */",
"final",
"class",
"ResolveCB",
"implements",
"Callback",
"<",
"List",
"<",
"String",
">",
",",
"ArrayList",
"<",
"String",
">",
">",
"{",
"@",
"Override",
"public",
"List",
"<",
"String",
">",
"call",
"(",
"final",
"ArrayList",
"<",
"String",
">",
"names",
")",
"throws",
"Exception",
"{",
"for",
"(",
"final",
"String",
"name",
":",
"names",
")",
"{",
"aggregated_tags",
".",
"add",
"(",
"name",
")",
";",
"}",
"return",
"aggregated_tags",
";",
"}",
"}",
"return",
"Deferred",
".",
"group",
"(",
"names",
")",
".",
"addCallback",
"(",
"new",
"ResolveCB",
"(",
")",
")",
";",
"}"
] |
Resolves the set of tag keys to their string names.
@param tagks The set of unique tag names
@return a deferred to wait on for all of the tag keys to be resolved. The
result should be null.
|
[
"Resolves",
"the",
"set",
"of",
"tag",
"keys",
"to",
"their",
"string",
"names",
"."
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/core/SpanGroup.java#L612-L636
|
13,385
|
OpenTSDB/opentsdb
|
src/query/expression/IntersectionIterator.java
|
IntersectionIterator.next
|
@Override
public void next() {
if (!hasNext()) {
throw new IllegalDataException("No more data");
}
for (final ITimeSyncedIterator sub : queries.values()) {
sub.next(timestamp);
}
timestamp = nextTimestamp();
}
|
java
|
@Override
public void next() {
if (!hasNext()) {
throw new IllegalDataException("No more data");
}
for (final ITimeSyncedIterator sub : queries.values()) {
sub.next(timestamp);
}
timestamp = nextTimestamp();
}
|
[
"@",
"Override",
"public",
"void",
"next",
"(",
")",
"{",
"if",
"(",
"!",
"hasNext",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalDataException",
"(",
"\"No more data\"",
")",
";",
"}",
"for",
"(",
"final",
"ITimeSyncedIterator",
"sub",
":",
"queries",
".",
"values",
"(",
")",
")",
"{",
"sub",
".",
"next",
"(",
"timestamp",
")",
";",
"}",
"timestamp",
"=",
"nextTimestamp",
"(",
")",
";",
"}"
] |
fetch the next set of time aligned results for all series
|
[
"fetch",
"the",
"next",
"set",
"of",
"time",
"aligned",
"results",
"for",
"all",
"series"
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/query/expression/IntersectionIterator.java#L214-L223
|
13,386
|
OpenTSDB/opentsdb
|
src/query/expression/IntersectionIterator.java
|
IntersectionIterator.flattenTags
|
static byte[] flattenTags(final boolean use_query_tags,
final boolean include_agg_tags, final ByteMap<byte[]> tags,
final ByteSet agg_tags, final ITimeSyncedIterator sub) {
if (tags.isEmpty()) {
return HBaseClient.EMPTY_ARRAY;
}
final ByteSet query_tagks;
// NOTE: We MAY need the agg tags but I'm not sure yet
final int tag_size;
if (use_query_tags) {
int i = 0;
if (sub.getQueryTagKs() != null && !sub.getQueryTagKs().isEmpty()) {
query_tagks = sub.getQueryTagKs();
for (final Map.Entry<byte[], byte[]> pair : tags.entrySet()) {
if (query_tagks.contains(pair.getKey())) {
i++;
}
}
} else {
query_tagks = new ByteSet();
}
tag_size = i;
} else {
query_tagks = new ByteSet();
tag_size = tags.size();
}
int len = (tag_size * (TSDB.tagk_width() + TSDB.tagv_width())) +
(include_agg_tags ? (agg_tags.size() * TSDB.tagk_width()) : 0);
final byte[] tagks = new byte[len];
int i = 0;
for (final Map.Entry<byte[], byte[]> pair : tags.entrySet()) {
if (use_query_tags && !query_tagks.contains(pair.getKey())) {
continue;
}
System.arraycopy(pair.getKey(), 0, tagks, i, TSDB.tagk_width());
i += TSDB.tagk_width();
System.arraycopy(pair.getValue(), 0, tagks, i, TSDB.tagv_width());
i += TSDB.tagv_width();
}
if (include_agg_tags) {
for (final byte[] tagk : agg_tags) {
System.arraycopy(tagk, 0, tagks, i, TSDB.tagk_width());
i += TSDB.tagk_width();
}
}
return tagks;
}
|
java
|
static byte[] flattenTags(final boolean use_query_tags,
final boolean include_agg_tags, final ByteMap<byte[]> tags,
final ByteSet agg_tags, final ITimeSyncedIterator sub) {
if (tags.isEmpty()) {
return HBaseClient.EMPTY_ARRAY;
}
final ByteSet query_tagks;
// NOTE: We MAY need the agg tags but I'm not sure yet
final int tag_size;
if (use_query_tags) {
int i = 0;
if (sub.getQueryTagKs() != null && !sub.getQueryTagKs().isEmpty()) {
query_tagks = sub.getQueryTagKs();
for (final Map.Entry<byte[], byte[]> pair : tags.entrySet()) {
if (query_tagks.contains(pair.getKey())) {
i++;
}
}
} else {
query_tagks = new ByteSet();
}
tag_size = i;
} else {
query_tagks = new ByteSet();
tag_size = tags.size();
}
int len = (tag_size * (TSDB.tagk_width() + TSDB.tagv_width())) +
(include_agg_tags ? (agg_tags.size() * TSDB.tagk_width()) : 0);
final byte[] tagks = new byte[len];
int i = 0;
for (final Map.Entry<byte[], byte[]> pair : tags.entrySet()) {
if (use_query_tags && !query_tagks.contains(pair.getKey())) {
continue;
}
System.arraycopy(pair.getKey(), 0, tagks, i, TSDB.tagk_width());
i += TSDB.tagk_width();
System.arraycopy(pair.getValue(), 0, tagks, i, TSDB.tagv_width());
i += TSDB.tagv_width();
}
if (include_agg_tags) {
for (final byte[] tagk : agg_tags) {
System.arraycopy(tagk, 0, tagks, i, TSDB.tagk_width());
i += TSDB.tagk_width();
}
}
return tagks;
}
|
[
"static",
"byte",
"[",
"]",
"flattenTags",
"(",
"final",
"boolean",
"use_query_tags",
",",
"final",
"boolean",
"include_agg_tags",
",",
"final",
"ByteMap",
"<",
"byte",
"[",
"]",
">",
"tags",
",",
"final",
"ByteSet",
"agg_tags",
",",
"final",
"ITimeSyncedIterator",
"sub",
")",
"{",
"if",
"(",
"tags",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"HBaseClient",
".",
"EMPTY_ARRAY",
";",
"}",
"final",
"ByteSet",
"query_tagks",
";",
"// NOTE: We MAY need the agg tags but I'm not sure yet",
"final",
"int",
"tag_size",
";",
"if",
"(",
"use_query_tags",
")",
"{",
"int",
"i",
"=",
"0",
";",
"if",
"(",
"sub",
".",
"getQueryTagKs",
"(",
")",
"!=",
"null",
"&&",
"!",
"sub",
".",
"getQueryTagKs",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"query_tagks",
"=",
"sub",
".",
"getQueryTagKs",
"(",
")",
";",
"for",
"(",
"final",
"Map",
".",
"Entry",
"<",
"byte",
"[",
"]",
",",
"byte",
"[",
"]",
">",
"pair",
":",
"tags",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"query_tagks",
".",
"contains",
"(",
"pair",
".",
"getKey",
"(",
")",
")",
")",
"{",
"i",
"++",
";",
"}",
"}",
"}",
"else",
"{",
"query_tagks",
"=",
"new",
"ByteSet",
"(",
")",
";",
"}",
"tag_size",
"=",
"i",
";",
"}",
"else",
"{",
"query_tagks",
"=",
"new",
"ByteSet",
"(",
")",
";",
"tag_size",
"=",
"tags",
".",
"size",
"(",
")",
";",
"}",
"int",
"len",
"=",
"(",
"tag_size",
"*",
"(",
"TSDB",
".",
"tagk_width",
"(",
")",
"+",
"TSDB",
".",
"tagv_width",
"(",
")",
")",
")",
"+",
"(",
"include_agg_tags",
"?",
"(",
"agg_tags",
".",
"size",
"(",
")",
"*",
"TSDB",
".",
"tagk_width",
"(",
")",
")",
":",
"0",
")",
";",
"final",
"byte",
"[",
"]",
"tagks",
"=",
"new",
"byte",
"[",
"len",
"]",
";",
"int",
"i",
"=",
"0",
";",
"for",
"(",
"final",
"Map",
".",
"Entry",
"<",
"byte",
"[",
"]",
",",
"byte",
"[",
"]",
">",
"pair",
":",
"tags",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"use_query_tags",
"&&",
"!",
"query_tagks",
".",
"contains",
"(",
"pair",
".",
"getKey",
"(",
")",
")",
")",
"{",
"continue",
";",
"}",
"System",
".",
"arraycopy",
"(",
"pair",
".",
"getKey",
"(",
")",
",",
"0",
",",
"tagks",
",",
"i",
",",
"TSDB",
".",
"tagk_width",
"(",
")",
")",
";",
"i",
"+=",
"TSDB",
".",
"tagk_width",
"(",
")",
";",
"System",
".",
"arraycopy",
"(",
"pair",
".",
"getValue",
"(",
")",
",",
"0",
",",
"tagks",
",",
"i",
",",
"TSDB",
".",
"tagv_width",
"(",
")",
")",
";",
"i",
"+=",
"TSDB",
".",
"tagv_width",
"(",
")",
";",
"}",
"if",
"(",
"include_agg_tags",
")",
"{",
"for",
"(",
"final",
"byte",
"[",
"]",
"tagk",
":",
"agg_tags",
")",
"{",
"System",
".",
"arraycopy",
"(",
"tagk",
",",
"0",
",",
"tagks",
",",
"i",
",",
"TSDB",
".",
"tagk_width",
"(",
")",
")",
";",
"i",
"+=",
"TSDB",
".",
"tagk_width",
"(",
")",
";",
"}",
"}",
"return",
"tagks",
";",
"}"
] |
Flattens the appropriate tags into a single byte array
@param use_query_tags Whether or not to include tags returned with the
results or just use those group by'd in the query
@param include_agg_tags Whether or not to include the aggregated tags in
the identifier
@param tags The map of tags from the result set
@param agg_tags The list of aggregated tags
@param sub The sub query iterator
@return A byte array with the flattened tag keys and values. Note that
if the tags set is empty, this may return an empty array (but not a null
array)
|
[
"Flattens",
"the",
"appropriate",
"tags",
"into",
"a",
"single",
"byte",
"array"
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/query/expression/IntersectionIterator.java#L397-L444
|
13,387
|
OpenTSDB/opentsdb
|
src/stats/QueryStats.java
|
QueryStats.markSerialized
|
public void markSerialized(final HttpResponseStatus response,
final Throwable exception) {
this.exception = exception;
this.response = response;
query_completed_ts = DateTime.currentTimeMillis();
overall_stats.put(QueryStat.PROCESSING_PRE_WRITE_TIME, DateTime.nanoTime() - query_start_ns);
synchronized (running_queries) {
if (!running_queries.containsKey(this.hashCode())) {
if (!ENABLE_DUPLICATES) {
LOG.warn("Query was already marked as complete: " + this);
}
}
running_queries.remove(hashCode());
if (LOG.isDebugEnabled()) {
LOG.debug("Removed completed query " + remote_address + " with hash " +
hashCode() + " on thread " + Thread.currentThread().getId());
}
}
aggQueryStats();
final int cache_hash = this.hashCode() ^ response.toString().hashCode();
synchronized (completed_queries) {
final QueryStats old_query = completed_queries.getIfPresent(cache_hash);
if (old_query == null) {
completed_queries.put(cache_hash, this);
} else {
old_query.executed++;
}
}
}
|
java
|
public void markSerialized(final HttpResponseStatus response,
final Throwable exception) {
this.exception = exception;
this.response = response;
query_completed_ts = DateTime.currentTimeMillis();
overall_stats.put(QueryStat.PROCESSING_PRE_WRITE_TIME, DateTime.nanoTime() - query_start_ns);
synchronized (running_queries) {
if (!running_queries.containsKey(this.hashCode())) {
if (!ENABLE_DUPLICATES) {
LOG.warn("Query was already marked as complete: " + this);
}
}
running_queries.remove(hashCode());
if (LOG.isDebugEnabled()) {
LOG.debug("Removed completed query " + remote_address + " with hash " +
hashCode() + " on thread " + Thread.currentThread().getId());
}
}
aggQueryStats();
final int cache_hash = this.hashCode() ^ response.toString().hashCode();
synchronized (completed_queries) {
final QueryStats old_query = completed_queries.getIfPresent(cache_hash);
if (old_query == null) {
completed_queries.put(cache_hash, this);
} else {
old_query.executed++;
}
}
}
|
[
"public",
"void",
"markSerialized",
"(",
"final",
"HttpResponseStatus",
"response",
",",
"final",
"Throwable",
"exception",
")",
"{",
"this",
".",
"exception",
"=",
"exception",
";",
"this",
".",
"response",
"=",
"response",
";",
"query_completed_ts",
"=",
"DateTime",
".",
"currentTimeMillis",
"(",
")",
";",
"overall_stats",
".",
"put",
"(",
"QueryStat",
".",
"PROCESSING_PRE_WRITE_TIME",
",",
"DateTime",
".",
"nanoTime",
"(",
")",
"-",
"query_start_ns",
")",
";",
"synchronized",
"(",
"running_queries",
")",
"{",
"if",
"(",
"!",
"running_queries",
".",
"containsKey",
"(",
"this",
".",
"hashCode",
"(",
")",
")",
")",
"{",
"if",
"(",
"!",
"ENABLE_DUPLICATES",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"Query was already marked as complete: \"",
"+",
"this",
")",
";",
"}",
"}",
"running_queries",
".",
"remove",
"(",
"hashCode",
"(",
")",
")",
";",
"if",
"(",
"LOG",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Removed completed query \"",
"+",
"remote_address",
"+",
"\" with hash \"",
"+",
"hashCode",
"(",
")",
"+",
"\" on thread \"",
"+",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getId",
"(",
")",
")",
";",
"}",
"}",
"aggQueryStats",
"(",
")",
";",
"final",
"int",
"cache_hash",
"=",
"this",
".",
"hashCode",
"(",
")",
"^",
"response",
".",
"toString",
"(",
")",
".",
"hashCode",
"(",
")",
";",
"synchronized",
"(",
"completed_queries",
")",
"{",
"final",
"QueryStats",
"old_query",
"=",
"completed_queries",
".",
"getIfPresent",
"(",
"cache_hash",
")",
";",
"if",
"(",
"old_query",
"==",
"null",
")",
"{",
"completed_queries",
".",
"put",
"(",
"cache_hash",
",",
"this",
")",
";",
"}",
"else",
"{",
"old_query",
".",
"executed",
"++",
";",
"}",
"}",
"}"
] |
Marks a query as completed with the given HTTP code with exception and
moves it from the running map to the cache, updating the cache if it
already existed.
@param response The HTTP response to log
@param exception The exception thrown
|
[
"Marks",
"a",
"query",
"as",
"completed",
"with",
"the",
"given",
"HTTP",
"code",
"with",
"exception",
"and",
"moves",
"it",
"from",
"the",
"running",
"map",
"to",
"the",
"cache",
"updating",
"the",
"cache",
"if",
"it",
"already",
"existed",
"."
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/stats/QueryStats.java#L341-L372
|
13,388
|
OpenTSDB/opentsdb
|
src/stats/QueryStats.java
|
QueryStats.markSent
|
public void markSent() {
sent_to_client = true;
overall_stats.put(QueryStat.TOTAL_TIME, DateTime.nanoTime() - query_start_ns);
LOG.info("Completing query=" + JSON.serializeToString(this));
QUERY_LOG.info(this.toString());
}
|
java
|
public void markSent() {
sent_to_client = true;
overall_stats.put(QueryStat.TOTAL_TIME, DateTime.nanoTime() - query_start_ns);
LOG.info("Completing query=" + JSON.serializeToString(this));
QUERY_LOG.info(this.toString());
}
|
[
"public",
"void",
"markSent",
"(",
")",
"{",
"sent_to_client",
"=",
"true",
";",
"overall_stats",
".",
"put",
"(",
"QueryStat",
".",
"TOTAL_TIME",
",",
"DateTime",
".",
"nanoTime",
"(",
")",
"-",
"query_start_ns",
")",
";",
"LOG",
".",
"info",
"(",
"\"Completing query=\"",
"+",
"JSON",
".",
"serializeToString",
"(",
"this",
")",
")",
";",
"QUERY_LOG",
".",
"info",
"(",
"this",
".",
"toString",
"(",
")",
")",
";",
"}"
] |
Marks the query as complete and logs it to the proper logs. This is called
after the data has been sent to the client.
|
[
"Marks",
"the",
"query",
"as",
"complete",
"and",
"logs",
"it",
"to",
"the",
"proper",
"logs",
".",
"This",
"is",
"called",
"after",
"the",
"data",
"has",
"been",
"sent",
"to",
"the",
"client",
"."
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/stats/QueryStats.java#L378-L383
|
13,389
|
OpenTSDB/opentsdb
|
src/stats/QueryStats.java
|
QueryStats.markSendFailed
|
public void markSendFailed() {
overall_stats.put(QueryStat.TOTAL_TIME, DateTime.nanoTime() - query_start_ns);
LOG.info("Completing query=" + JSON.serializeToString(this));
QUERY_LOG.info(this.toString());
}
|
java
|
public void markSendFailed() {
overall_stats.put(QueryStat.TOTAL_TIME, DateTime.nanoTime() - query_start_ns);
LOG.info("Completing query=" + JSON.serializeToString(this));
QUERY_LOG.info(this.toString());
}
|
[
"public",
"void",
"markSendFailed",
"(",
")",
"{",
"overall_stats",
".",
"put",
"(",
"QueryStat",
".",
"TOTAL_TIME",
",",
"DateTime",
".",
"nanoTime",
"(",
")",
"-",
"query_start_ns",
")",
";",
"LOG",
".",
"info",
"(",
"\"Completing query=\"",
"+",
"JSON",
".",
"serializeToString",
"(",
"this",
")",
")",
";",
"QUERY_LOG",
".",
"info",
"(",
"this",
".",
"toString",
"(",
")",
")",
";",
"}"
] |
Leaves the sent_to_client field as false when we were unable to write to
the client end point.
|
[
"Leaves",
"the",
"sent_to_client",
"field",
"as",
"false",
"when",
"we",
"were",
"unable",
"to",
"write",
"to",
"the",
"client",
"end",
"point",
"."
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/stats/QueryStats.java#L387-L391
|
13,390
|
OpenTSDB/opentsdb
|
src/stats/QueryStats.java
|
QueryStats.getRunningAndCompleteStats
|
public static Map<String, Object> getRunningAndCompleteStats() {
Map<String, Object> root = new TreeMap<String, Object>();
if (running_queries.isEmpty()) {
root.put("running", Collections.emptyList());
} else {
final List<Object> running = new ArrayList<Object>(running_queries.size());
root.put("running", running);
// don't need to lock the map beyond what the iterator will do implicitly
for (final QueryStats stats : running_queries.values()) {
final Map<String, Object> obj = new HashMap<String, Object>(10);
obj.put("query", stats.query);
obj.put("remote", stats.remote_address);
obj.put("user", stats.user);
obj.put("headers", stats.headers);;
obj.put("queryStart", stats.query_start_ms);
obj.put("elapsed", DateTime.msFromNanoDiff(DateTime.nanoTime(),
stats.query_start_ns));
running.add(obj);
}
}
final Map<Integer, QueryStats> completed = completed_queries.asMap();
if (completed.isEmpty()) {
root.put("completed", Collections.emptyList());
} else {
root.put("completed", completed.values());
}
return root;
}
|
java
|
public static Map<String, Object> getRunningAndCompleteStats() {
Map<String, Object> root = new TreeMap<String, Object>();
if (running_queries.isEmpty()) {
root.put("running", Collections.emptyList());
} else {
final List<Object> running = new ArrayList<Object>(running_queries.size());
root.put("running", running);
// don't need to lock the map beyond what the iterator will do implicitly
for (final QueryStats stats : running_queries.values()) {
final Map<String, Object> obj = new HashMap<String, Object>(10);
obj.put("query", stats.query);
obj.put("remote", stats.remote_address);
obj.put("user", stats.user);
obj.put("headers", stats.headers);;
obj.put("queryStart", stats.query_start_ms);
obj.put("elapsed", DateTime.msFromNanoDiff(DateTime.nanoTime(),
stats.query_start_ns));
running.add(obj);
}
}
final Map<Integer, QueryStats> completed = completed_queries.asMap();
if (completed.isEmpty()) {
root.put("completed", Collections.emptyList());
} else {
root.put("completed", completed.values());
}
return root;
}
|
[
"public",
"static",
"Map",
"<",
"String",
",",
"Object",
">",
"getRunningAndCompleteStats",
"(",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"root",
"=",
"new",
"TreeMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"if",
"(",
"running_queries",
".",
"isEmpty",
"(",
")",
")",
"{",
"root",
".",
"put",
"(",
"\"running\"",
",",
"Collections",
".",
"emptyList",
"(",
")",
")",
";",
"}",
"else",
"{",
"final",
"List",
"<",
"Object",
">",
"running",
"=",
"new",
"ArrayList",
"<",
"Object",
">",
"(",
"running_queries",
".",
"size",
"(",
")",
")",
";",
"root",
".",
"put",
"(",
"\"running\"",
",",
"running",
")",
";",
"// don't need to lock the map beyond what the iterator will do implicitly",
"for",
"(",
"final",
"QueryStats",
"stats",
":",
"running_queries",
".",
"values",
"(",
")",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"obj",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
"10",
")",
";",
"obj",
".",
"put",
"(",
"\"query\"",
",",
"stats",
".",
"query",
")",
";",
"obj",
".",
"put",
"(",
"\"remote\"",
",",
"stats",
".",
"remote_address",
")",
";",
"obj",
".",
"put",
"(",
"\"user\"",
",",
"stats",
".",
"user",
")",
";",
"obj",
".",
"put",
"(",
"\"headers\"",
",",
"stats",
".",
"headers",
")",
";",
";",
"obj",
".",
"put",
"(",
"\"queryStart\"",
",",
"stats",
".",
"query_start_ms",
")",
";",
"obj",
".",
"put",
"(",
"\"elapsed\"",
",",
"DateTime",
".",
"msFromNanoDiff",
"(",
"DateTime",
".",
"nanoTime",
"(",
")",
",",
"stats",
".",
"query_start_ns",
")",
")",
";",
"running",
".",
"add",
"(",
"obj",
")",
";",
"}",
"}",
"final",
"Map",
"<",
"Integer",
",",
"QueryStats",
">",
"completed",
"=",
"completed_queries",
".",
"asMap",
"(",
")",
";",
"if",
"(",
"completed",
".",
"isEmpty",
"(",
")",
")",
"{",
"root",
".",
"put",
"(",
"\"completed\"",
",",
"Collections",
".",
"emptyList",
"(",
")",
")",
";",
"}",
"else",
"{",
"root",
".",
"put",
"(",
"\"completed\"",
",",
"completed",
".",
"values",
"(",
")",
")",
";",
"}",
"return",
"root",
";",
"}"
] |
Builds a serializable map from the running and cached query maps to be
returned to a caller.
@return A map for serialization
|
[
"Builds",
"a",
"serializable",
"map",
"from",
"the",
"running",
"and",
"cached",
"query",
"maps",
"to",
"be",
"returned",
"to",
"a",
"caller",
"."
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/stats/QueryStats.java#L398-L429
|
13,391
|
OpenTSDB/opentsdb
|
src/stats/QueryStats.java
|
QueryStats.addStat
|
public void addStat(final int query_index, final QueryStat name,
final long value) {
Map<QueryStat, Long> qs = query_stats.get(query_index);
if (qs == null) {
qs = new HashMap<QueryStat, Long>();
query_stats.put(query_index, qs);
}
qs.put(name, value);
}
|
java
|
public void addStat(final int query_index, final QueryStat name,
final long value) {
Map<QueryStat, Long> qs = query_stats.get(query_index);
if (qs == null) {
qs = new HashMap<QueryStat, Long>();
query_stats.put(query_index, qs);
}
qs.put(name, value);
}
|
[
"public",
"void",
"addStat",
"(",
"final",
"int",
"query_index",
",",
"final",
"QueryStat",
"name",
",",
"final",
"long",
"value",
")",
"{",
"Map",
"<",
"QueryStat",
",",
"Long",
">",
"qs",
"=",
"query_stats",
".",
"get",
"(",
"query_index",
")",
";",
"if",
"(",
"qs",
"==",
"null",
")",
"{",
"qs",
"=",
"new",
"HashMap",
"<",
"QueryStat",
",",
"Long",
">",
"(",
")",
";",
"query_stats",
".",
"put",
"(",
"query_index",
",",
"qs",
")",
";",
"}",
"qs",
".",
"put",
"(",
"name",
",",
"value",
")",
";",
"}"
] |
Adds a stat for a sub query, replacing it if it exists. Times must be
in nanoseconds.
@param query_index The index of the sub query to update
@param name The name of the stat to update
@param value The value to set
|
[
"Adds",
"a",
"stat",
"for",
"a",
"sub",
"query",
"replacing",
"it",
"if",
"it",
"exists",
".",
"Times",
"must",
"be",
"in",
"nanoseconds",
"."
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/stats/QueryStats.java#L456-L464
|
13,392
|
OpenTSDB/opentsdb
|
src/stats/QueryStats.java
|
QueryStats.updateStat
|
public void updateStat(final int query_index, final QueryStat name,
final long value) {
Map<QueryStat, Long> qs = query_stats.get(query_index);
long cum_time = value;
if (qs == null) {
qs = new HashMap<QueryStat, Long>();
query_stats.put(query_index, qs);
}
if (qs.containsKey(name)) {
cum_time += qs.get(name);
}
qs.put(name, cum_time);
}
|
java
|
public void updateStat(final int query_index, final QueryStat name,
final long value) {
Map<QueryStat, Long> qs = query_stats.get(query_index);
long cum_time = value;
if (qs == null) {
qs = new HashMap<QueryStat, Long>();
query_stats.put(query_index, qs);
}
if (qs.containsKey(name)) {
cum_time += qs.get(name);
}
qs.put(name, cum_time);
}
|
[
"public",
"void",
"updateStat",
"(",
"final",
"int",
"query_index",
",",
"final",
"QueryStat",
"name",
",",
"final",
"long",
"value",
")",
"{",
"Map",
"<",
"QueryStat",
",",
"Long",
">",
"qs",
"=",
"query_stats",
".",
"get",
"(",
"query_index",
")",
";",
"long",
"cum_time",
"=",
"value",
";",
"if",
"(",
"qs",
"==",
"null",
")",
"{",
"qs",
"=",
"new",
"HashMap",
"<",
"QueryStat",
",",
"Long",
">",
"(",
")",
";",
"query_stats",
".",
"put",
"(",
"query_index",
",",
"qs",
")",
";",
"}",
"if",
"(",
"qs",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"cum_time",
"+=",
"qs",
".",
"get",
"(",
"name",
")",
";",
"}",
"qs",
".",
"put",
"(",
"name",
",",
"cum_time",
")",
";",
"}"
] |
Increments the cumulative value for a cumulative stat. If it's a time then
it must be in nanoseconds
@param query_index The index of the sub query
@param name The name of the stat
@param value The value to add to the existing value
|
[
"Increments",
"the",
"cumulative",
"value",
"for",
"a",
"cumulative",
"stat",
".",
"If",
"it",
"s",
"a",
"time",
"then",
"it",
"must",
"be",
"in",
"nanoseconds"
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/stats/QueryStats.java#L589-L602
|
13,393
|
OpenTSDB/opentsdb
|
src/stats/QueryStats.java
|
QueryStats.addScannerStat
|
public void addScannerStat(final int query_index, final int id,
final QueryStat name, final long value) {
Map<Integer, Map<QueryStat, Long>> qs = scanner_stats.get(query_index);
if (qs == null) {
qs = new ConcurrentHashMap<Integer, Map<QueryStat, Long>>(
Const.SALT_WIDTH() > 0 ? Const.SALT_BUCKETS() : 1);
scanner_stats.put(query_index, qs);
}
Map<QueryStat, Long> scanner_stat_map = qs.get(id);
if (scanner_stat_map == null) {
scanner_stat_map = new HashMap<QueryStat, Long>();
qs.put(id, scanner_stat_map);
}
scanner_stat_map.put(name, value);
}
|
java
|
public void addScannerStat(final int query_index, final int id,
final QueryStat name, final long value) {
Map<Integer, Map<QueryStat, Long>> qs = scanner_stats.get(query_index);
if (qs == null) {
qs = new ConcurrentHashMap<Integer, Map<QueryStat, Long>>(
Const.SALT_WIDTH() > 0 ? Const.SALT_BUCKETS() : 1);
scanner_stats.put(query_index, qs);
}
Map<QueryStat, Long> scanner_stat_map = qs.get(id);
if (scanner_stat_map == null) {
scanner_stat_map = new HashMap<QueryStat, Long>();
qs.put(id, scanner_stat_map);
}
scanner_stat_map.put(name, value);
}
|
[
"public",
"void",
"addScannerStat",
"(",
"final",
"int",
"query_index",
",",
"final",
"int",
"id",
",",
"final",
"QueryStat",
"name",
",",
"final",
"long",
"value",
")",
"{",
"Map",
"<",
"Integer",
",",
"Map",
"<",
"QueryStat",
",",
"Long",
">",
">",
"qs",
"=",
"scanner_stats",
".",
"get",
"(",
"query_index",
")",
";",
"if",
"(",
"qs",
"==",
"null",
")",
"{",
"qs",
"=",
"new",
"ConcurrentHashMap",
"<",
"Integer",
",",
"Map",
"<",
"QueryStat",
",",
"Long",
">",
">",
"(",
"Const",
".",
"SALT_WIDTH",
"(",
")",
">",
"0",
"?",
"Const",
".",
"SALT_BUCKETS",
"(",
")",
":",
"1",
")",
";",
"scanner_stats",
".",
"put",
"(",
"query_index",
",",
"qs",
")",
";",
"}",
"Map",
"<",
"QueryStat",
",",
"Long",
">",
"scanner_stat_map",
"=",
"qs",
".",
"get",
"(",
"id",
")",
";",
"if",
"(",
"scanner_stat_map",
"==",
"null",
")",
"{",
"scanner_stat_map",
"=",
"new",
"HashMap",
"<",
"QueryStat",
",",
"Long",
">",
"(",
")",
";",
"qs",
".",
"put",
"(",
"id",
",",
"scanner_stat_map",
")",
";",
"}",
"scanner_stat_map",
".",
"put",
"(",
"name",
",",
"value",
")",
";",
"}"
] |
Adds a value for a specific scanner for a specific sub query. If it's a time
then it must be in nanoseconds.
@param query_index The index of the sub query
@param id The numeric ID of the scanner
@param name The name of the stat
@param value The value to add to the map
|
[
"Adds",
"a",
"value",
"for",
"a",
"specific",
"scanner",
"for",
"a",
"specific",
"sub",
"query",
".",
"If",
"it",
"s",
"a",
"time",
"then",
"it",
"must",
"be",
"in",
"nanoseconds",
"."
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/stats/QueryStats.java#L612-L626
|
13,394
|
OpenTSDB/opentsdb
|
src/stats/QueryStats.java
|
QueryStats.addScannerServers
|
public void addScannerServers(final int query_index, final int id,
final Set<String> servers) {
Map<Integer, Set<String>> query_servers = scanner_servers.get(query_index);
if (query_servers == null) {
query_servers = new ConcurrentHashMap<Integer, Set<String>>(
Const.SALT_WIDTH() > 0 ? Const.SALT_BUCKETS() : 1);
scanner_servers.put(query_index, query_servers);
}
query_servers.put(id, servers);
}
|
java
|
public void addScannerServers(final int query_index, final int id,
final Set<String> servers) {
Map<Integer, Set<String>> query_servers = scanner_servers.get(query_index);
if (query_servers == null) {
query_servers = new ConcurrentHashMap<Integer, Set<String>>(
Const.SALT_WIDTH() > 0 ? Const.SALT_BUCKETS() : 1);
scanner_servers.put(query_index, query_servers);
}
query_servers.put(id, servers);
}
|
[
"public",
"void",
"addScannerServers",
"(",
"final",
"int",
"query_index",
",",
"final",
"int",
"id",
",",
"final",
"Set",
"<",
"String",
">",
"servers",
")",
"{",
"Map",
"<",
"Integer",
",",
"Set",
"<",
"String",
">",
">",
"query_servers",
"=",
"scanner_servers",
".",
"get",
"(",
"query_index",
")",
";",
"if",
"(",
"query_servers",
"==",
"null",
")",
"{",
"query_servers",
"=",
"new",
"ConcurrentHashMap",
"<",
"Integer",
",",
"Set",
"<",
"String",
">",
">",
"(",
"Const",
".",
"SALT_WIDTH",
"(",
")",
">",
"0",
"?",
"Const",
".",
"SALT_BUCKETS",
"(",
")",
":",
"1",
")",
";",
"scanner_servers",
".",
"put",
"(",
"query_index",
",",
"query_servers",
")",
";",
"}",
"query_servers",
".",
"put",
"(",
"id",
",",
"servers",
")",
";",
"}"
] |
Adds or overwrites the list of servers scanned by a scanner
@param query_index The index of the sub query
@param id The numeric ID of the scanner
@param servers The list of servers encountered
|
[
"Adds",
"or",
"overwrites",
"the",
"list",
"of",
"servers",
"scanned",
"by",
"a",
"scanner"
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/stats/QueryStats.java#L634-L643
|
13,395
|
OpenTSDB/opentsdb
|
src/stats/QueryStats.java
|
QueryStats.updateScannerStat
|
public void updateScannerStat(final int query_index, final int id,
final QueryStat name, final long value) {
Map<Integer, Map<QueryStat, Long>> qs = scanner_stats.get(query_index);
long cum_time = value;
if (qs == null) {
qs = new ConcurrentHashMap<Integer, Map<QueryStat, Long>>();
scanner_stats.put(query_index, qs);
}
Map<QueryStat, Long> scanner_stat_map = qs.get(id);
if (scanner_stat_map == null) {
scanner_stat_map = new HashMap<QueryStat, Long>();
qs.put(id, scanner_stat_map);
}
if (scanner_stat_map.containsKey(name)) {
cum_time += scanner_stat_map.get(name);
}
scanner_stat_map.put(name, cum_time);
}
|
java
|
public void updateScannerStat(final int query_index, final int id,
final QueryStat name, final long value) {
Map<Integer, Map<QueryStat, Long>> qs = scanner_stats.get(query_index);
long cum_time = value;
if (qs == null) {
qs = new ConcurrentHashMap<Integer, Map<QueryStat, Long>>();
scanner_stats.put(query_index, qs);
}
Map<QueryStat, Long> scanner_stat_map = qs.get(id);
if (scanner_stat_map == null) {
scanner_stat_map = new HashMap<QueryStat, Long>();
qs.put(id, scanner_stat_map);
}
if (scanner_stat_map.containsKey(name)) {
cum_time += scanner_stat_map.get(name);
}
scanner_stat_map.put(name, cum_time);
}
|
[
"public",
"void",
"updateScannerStat",
"(",
"final",
"int",
"query_index",
",",
"final",
"int",
"id",
",",
"final",
"QueryStat",
"name",
",",
"final",
"long",
"value",
")",
"{",
"Map",
"<",
"Integer",
",",
"Map",
"<",
"QueryStat",
",",
"Long",
">",
">",
"qs",
"=",
"scanner_stats",
".",
"get",
"(",
"query_index",
")",
";",
"long",
"cum_time",
"=",
"value",
";",
"if",
"(",
"qs",
"==",
"null",
")",
"{",
"qs",
"=",
"new",
"ConcurrentHashMap",
"<",
"Integer",
",",
"Map",
"<",
"QueryStat",
",",
"Long",
">",
">",
"(",
")",
";",
"scanner_stats",
".",
"put",
"(",
"query_index",
",",
"qs",
")",
";",
"}",
"Map",
"<",
"QueryStat",
",",
"Long",
">",
"scanner_stat_map",
"=",
"qs",
".",
"get",
"(",
"id",
")",
";",
"if",
"(",
"scanner_stat_map",
"==",
"null",
")",
"{",
"scanner_stat_map",
"=",
"new",
"HashMap",
"<",
"QueryStat",
",",
"Long",
">",
"(",
")",
";",
"qs",
".",
"put",
"(",
"id",
",",
"scanner_stat_map",
")",
";",
"}",
"if",
"(",
"scanner_stat_map",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"cum_time",
"+=",
"scanner_stat_map",
".",
"get",
"(",
"name",
")",
";",
"}",
"scanner_stat_map",
".",
"put",
"(",
"name",
",",
"cum_time",
")",
";",
"}"
] |
Updates or adds a stat for a specific scanner. IF it's a time it must
be in nanoseconds
@param query_index The index of the sub query
@param id The numeric ID of the scanner
@param name The name of the stat
@param value The value to update to the map
|
[
"Updates",
"or",
"adds",
"a",
"stat",
"for",
"a",
"specific",
"scanner",
".",
"IF",
"it",
"s",
"a",
"time",
"it",
"must",
"be",
"in",
"nanoseconds"
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/stats/QueryStats.java#L653-L672
|
13,396
|
OpenTSDB/opentsdb
|
src/stats/QueryStats.java
|
QueryStats.addScannerId
|
public void addScannerId(final int query_index, final int id,
final String string_id) {
Map<Integer, String> scanners = scanner_ids.get(query_index);
if (scanners == null) {
scanners = new ConcurrentHashMap<Integer, String>();
scanner_ids.put(query_index, scanners);
}
scanners.put(id, string_id);
}
|
java
|
public void addScannerId(final int query_index, final int id,
final String string_id) {
Map<Integer, String> scanners = scanner_ids.get(query_index);
if (scanners == null) {
scanners = new ConcurrentHashMap<Integer, String>();
scanner_ids.put(query_index, scanners);
}
scanners.put(id, string_id);
}
|
[
"public",
"void",
"addScannerId",
"(",
"final",
"int",
"query_index",
",",
"final",
"int",
"id",
",",
"final",
"String",
"string_id",
")",
"{",
"Map",
"<",
"Integer",
",",
"String",
">",
"scanners",
"=",
"scanner_ids",
".",
"get",
"(",
"query_index",
")",
";",
"if",
"(",
"scanners",
"==",
"null",
")",
"{",
"scanners",
"=",
"new",
"ConcurrentHashMap",
"<",
"Integer",
",",
"String",
">",
"(",
")",
";",
"scanner_ids",
".",
"put",
"(",
"query_index",
",",
"scanners",
")",
";",
"}",
"scanners",
".",
"put",
"(",
"id",
",",
"string_id",
")",
";",
"}"
] |
Adds a scanner for a sub query to the stats along with the description of
the scanner.
@param query_index The index of the sub query
@param id The numeric ID of the scanner
@param string_id The description of the scanner
|
[
"Adds",
"a",
"scanner",
"for",
"a",
"sub",
"query",
"to",
"the",
"stats",
"along",
"with",
"the",
"description",
"of",
"the",
"scanner",
"."
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/stats/QueryStats.java#L681-L689
|
13,397
|
OpenTSDB/opentsdb
|
src/stats/QueryStats.java
|
QueryStats.getStats
|
public Map<String, Object> getStats(final boolean with_sub_queries,
final boolean with_scanners) {
final Map<String, Object> map = new TreeMap<String, Object>();
for (final Entry<QueryStat, Long> entry : overall_stats.entrySet()) {
if (entry.getKey().is_time) {
map.put(entry.getKey().toString(), DateTime.msFromNano(entry.getValue()));
} else {
map.put(entry.getKey().toString(), entry.getValue());
}
}
if (with_sub_queries) {
final Iterator<Entry<Integer, Map<QueryStat, Long>>> it =
query_stats.entrySet().iterator();
while (it.hasNext()) {
final Entry<Integer, Map<QueryStat, Long>> entry = it.next();
final Map<String, Object> qs = new HashMap<String, Object>(1);
qs.put(String.format("queryIdx_%02d", entry.getKey()),
getQueryStats(entry.getKey(), with_scanners));
map.putAll(qs);
}
}
return map;
}
|
java
|
public Map<String, Object> getStats(final boolean with_sub_queries,
final boolean with_scanners) {
final Map<String, Object> map = new TreeMap<String, Object>();
for (final Entry<QueryStat, Long> entry : overall_stats.entrySet()) {
if (entry.getKey().is_time) {
map.put(entry.getKey().toString(), DateTime.msFromNano(entry.getValue()));
} else {
map.put(entry.getKey().toString(), entry.getValue());
}
}
if (with_sub_queries) {
final Iterator<Entry<Integer, Map<QueryStat, Long>>> it =
query_stats.entrySet().iterator();
while (it.hasNext()) {
final Entry<Integer, Map<QueryStat, Long>> entry = it.next();
final Map<String, Object> qs = new HashMap<String, Object>(1);
qs.put(String.format("queryIdx_%02d", entry.getKey()),
getQueryStats(entry.getKey(), with_scanners));
map.putAll(qs);
}
}
return map;
}
|
[
"public",
"Map",
"<",
"String",
",",
"Object",
">",
"getStats",
"(",
"final",
"boolean",
"with_sub_queries",
",",
"final",
"boolean",
"with_scanners",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
"=",
"new",
"TreeMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"for",
"(",
"final",
"Entry",
"<",
"QueryStat",
",",
"Long",
">",
"entry",
":",
"overall_stats",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"entry",
".",
"getKey",
"(",
")",
".",
"is_time",
")",
"{",
"map",
".",
"put",
"(",
"entry",
".",
"getKey",
"(",
")",
".",
"toString",
"(",
")",
",",
"DateTime",
".",
"msFromNano",
"(",
"entry",
".",
"getValue",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"map",
".",
"put",
"(",
"entry",
".",
"getKey",
"(",
")",
".",
"toString",
"(",
")",
",",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}",
"if",
"(",
"with_sub_queries",
")",
"{",
"final",
"Iterator",
"<",
"Entry",
"<",
"Integer",
",",
"Map",
"<",
"QueryStat",
",",
"Long",
">",
">",
">",
"it",
"=",
"query_stats",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"it",
".",
"hasNext",
"(",
")",
")",
"{",
"final",
"Entry",
"<",
"Integer",
",",
"Map",
"<",
"QueryStat",
",",
"Long",
">",
">",
"entry",
"=",
"it",
".",
"next",
"(",
")",
";",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"qs",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
"1",
")",
";",
"qs",
".",
"put",
"(",
"String",
".",
"format",
"(",
"\"queryIdx_%02d\"",
",",
"entry",
".",
"getKey",
"(",
")",
")",
",",
"getQueryStats",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"with_scanners",
")",
")",
";",
"map",
".",
"putAll",
"(",
"qs",
")",
";",
"}",
"}",
"return",
"map",
";",
"}"
] |
Returns measurements of the given query
@param with_scanners Whether or not to dump individual scanner stats
@return A map with stats for the query
|
[
"Returns",
"measurements",
"of",
"the",
"given",
"query"
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/stats/QueryStats.java#L769-L793
|
13,398
|
OpenTSDB/opentsdb
|
src/search/TimeSeriesLookup.java
|
TimeSeriesLookup.getScanner
|
private Scanner getScanner(final int salt) {
final Scanner scanner = tsdb.getClient().newScanner(
query.useMeta() ? tsdb.metaTable() : tsdb.dataTable());
scanner.setFamily(query.useMeta() ? TSMeta.FAMILY : TSDB.FAMILY());
if (metric_uid != null) {
byte[] key;
if (query.useMeta() || Const.SALT_WIDTH() < 1) {
key = metric_uid;
} else {
key = new byte[Const.SALT_WIDTH() + TSDB.metrics_width()];
System.arraycopy(RowKey.getSaltBytes(salt), 0, key, 0, Const.SALT_WIDTH());
System.arraycopy(metric_uid, 0, key, Const.SALT_WIDTH(), metric_uid.length);
}
scanner.setStartKey(key);
long uid = UniqueId.uidToLong(metric_uid, TSDB.metrics_width());
uid++;
if (uid < Internal.getMaxUnsignedValueOnBytes(TSDB.metrics_width())) {
// if random metrics are enabled we could see a metric with the max UID
// value. If so, we need to leave the stop key as null
if (query.useMeta() || Const.SALT_WIDTH() < 1) {
key = UniqueId.longToUID(uid, TSDB.metrics_width());
} else {
key = new byte[Const.SALT_WIDTH() + TSDB.metrics_width()];
System.arraycopy(RowKey.getSaltBytes(salt), 0, key, 0, Const.SALT_WIDTH());
System.arraycopy(UniqueId.longToUID(uid, TSDB.metrics_width()), 0,
key, Const.SALT_WIDTH(), metric_uid.length);
}
scanner.setStopKey(key);
}
}
if (rowkey_regex != null) {
scanner.setKeyRegexp(rowkey_regex, CHARSET);
if (LOG.isDebugEnabled()) {
LOG.debug("Scanner regex: " + QueryUtil.byteRegexToString(rowkey_regex));
}
}
return scanner;
}
|
java
|
private Scanner getScanner(final int salt) {
final Scanner scanner = tsdb.getClient().newScanner(
query.useMeta() ? tsdb.metaTable() : tsdb.dataTable());
scanner.setFamily(query.useMeta() ? TSMeta.FAMILY : TSDB.FAMILY());
if (metric_uid != null) {
byte[] key;
if (query.useMeta() || Const.SALT_WIDTH() < 1) {
key = metric_uid;
} else {
key = new byte[Const.SALT_WIDTH() + TSDB.metrics_width()];
System.arraycopy(RowKey.getSaltBytes(salt), 0, key, 0, Const.SALT_WIDTH());
System.arraycopy(metric_uid, 0, key, Const.SALT_WIDTH(), metric_uid.length);
}
scanner.setStartKey(key);
long uid = UniqueId.uidToLong(metric_uid, TSDB.metrics_width());
uid++;
if (uid < Internal.getMaxUnsignedValueOnBytes(TSDB.metrics_width())) {
// if random metrics are enabled we could see a metric with the max UID
// value. If so, we need to leave the stop key as null
if (query.useMeta() || Const.SALT_WIDTH() < 1) {
key = UniqueId.longToUID(uid, TSDB.metrics_width());
} else {
key = new byte[Const.SALT_WIDTH() + TSDB.metrics_width()];
System.arraycopy(RowKey.getSaltBytes(salt), 0, key, 0, Const.SALT_WIDTH());
System.arraycopy(UniqueId.longToUID(uid, TSDB.metrics_width()), 0,
key, Const.SALT_WIDTH(), metric_uid.length);
}
scanner.setStopKey(key);
}
}
if (rowkey_regex != null) {
scanner.setKeyRegexp(rowkey_regex, CHARSET);
if (LOG.isDebugEnabled()) {
LOG.debug("Scanner regex: " + QueryUtil.byteRegexToString(rowkey_regex));
}
}
return scanner;
}
|
[
"private",
"Scanner",
"getScanner",
"(",
"final",
"int",
"salt",
")",
"{",
"final",
"Scanner",
"scanner",
"=",
"tsdb",
".",
"getClient",
"(",
")",
".",
"newScanner",
"(",
"query",
".",
"useMeta",
"(",
")",
"?",
"tsdb",
".",
"metaTable",
"(",
")",
":",
"tsdb",
".",
"dataTable",
"(",
")",
")",
";",
"scanner",
".",
"setFamily",
"(",
"query",
".",
"useMeta",
"(",
")",
"?",
"TSMeta",
".",
"FAMILY",
":",
"TSDB",
".",
"FAMILY",
"(",
")",
")",
";",
"if",
"(",
"metric_uid",
"!=",
"null",
")",
"{",
"byte",
"[",
"]",
"key",
";",
"if",
"(",
"query",
".",
"useMeta",
"(",
")",
"||",
"Const",
".",
"SALT_WIDTH",
"(",
")",
"<",
"1",
")",
"{",
"key",
"=",
"metric_uid",
";",
"}",
"else",
"{",
"key",
"=",
"new",
"byte",
"[",
"Const",
".",
"SALT_WIDTH",
"(",
")",
"+",
"TSDB",
".",
"metrics_width",
"(",
")",
"]",
";",
"System",
".",
"arraycopy",
"(",
"RowKey",
".",
"getSaltBytes",
"(",
"salt",
")",
",",
"0",
",",
"key",
",",
"0",
",",
"Const",
".",
"SALT_WIDTH",
"(",
")",
")",
";",
"System",
".",
"arraycopy",
"(",
"metric_uid",
",",
"0",
",",
"key",
",",
"Const",
".",
"SALT_WIDTH",
"(",
")",
",",
"metric_uid",
".",
"length",
")",
";",
"}",
"scanner",
".",
"setStartKey",
"(",
"key",
")",
";",
"long",
"uid",
"=",
"UniqueId",
".",
"uidToLong",
"(",
"metric_uid",
",",
"TSDB",
".",
"metrics_width",
"(",
")",
")",
";",
"uid",
"++",
";",
"if",
"(",
"uid",
"<",
"Internal",
".",
"getMaxUnsignedValueOnBytes",
"(",
"TSDB",
".",
"metrics_width",
"(",
")",
")",
")",
"{",
"// if random metrics are enabled we could see a metric with the max UID",
"// value. If so, we need to leave the stop key as null",
"if",
"(",
"query",
".",
"useMeta",
"(",
")",
"||",
"Const",
".",
"SALT_WIDTH",
"(",
")",
"<",
"1",
")",
"{",
"key",
"=",
"UniqueId",
".",
"longToUID",
"(",
"uid",
",",
"TSDB",
".",
"metrics_width",
"(",
")",
")",
";",
"}",
"else",
"{",
"key",
"=",
"new",
"byte",
"[",
"Const",
".",
"SALT_WIDTH",
"(",
")",
"+",
"TSDB",
".",
"metrics_width",
"(",
")",
"]",
";",
"System",
".",
"arraycopy",
"(",
"RowKey",
".",
"getSaltBytes",
"(",
"salt",
")",
",",
"0",
",",
"key",
",",
"0",
",",
"Const",
".",
"SALT_WIDTH",
"(",
")",
")",
";",
"System",
".",
"arraycopy",
"(",
"UniqueId",
".",
"longToUID",
"(",
"uid",
",",
"TSDB",
".",
"metrics_width",
"(",
")",
")",
",",
"0",
",",
"key",
",",
"Const",
".",
"SALT_WIDTH",
"(",
")",
",",
"metric_uid",
".",
"length",
")",
";",
"}",
"scanner",
".",
"setStopKey",
"(",
"key",
")",
";",
"}",
"}",
"if",
"(",
"rowkey_regex",
"!=",
"null",
")",
"{",
"scanner",
".",
"setKeyRegexp",
"(",
"rowkey_regex",
",",
"CHARSET",
")",
";",
"if",
"(",
"LOG",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Scanner regex: \"",
"+",
"QueryUtil",
".",
"byteRegexToString",
"(",
"rowkey_regex",
")",
")",
";",
"}",
"}",
"return",
"scanner",
";",
"}"
] |
Compiles a scanner with the given salt ID if salting is enabled AND we're
not scanning the meta table.
@param salt An ID for the salt bucket
@return A scanner to send to HBase.
|
[
"Compiles",
"a",
"scanner",
"with",
"the",
"given",
"salt",
"ID",
"if",
"salting",
"is",
"enabled",
"AND",
"we",
"re",
"not",
"scanning",
"the",
"meta",
"table",
"."
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/search/TimeSeriesLookup.java#L394-L434
|
13,399
|
OpenTSDB/opentsdb
|
src/query/pojo/Metric.java
|
Metric.validate
|
public void validate() {
if (metric == null || metric.isEmpty()) {
throw new IllegalArgumentException("missing or empty metric");
}
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("missing or empty id");
}
Query.validateId(id);
if (time_offset != null) {
DateTime.parseDateTimeString(time_offset, null);
}
if (aggregator != null && !aggregator.isEmpty()) {
try {
Aggregators.get(aggregator.toLowerCase());
} catch (final NoSuchElementException e) {
throw new IllegalArgumentException("Invalid aggregator");
}
}
if (fill_policy != null) {
fill_policy.validate();
}
}
|
java
|
public void validate() {
if (metric == null || metric.isEmpty()) {
throw new IllegalArgumentException("missing or empty metric");
}
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("missing or empty id");
}
Query.validateId(id);
if (time_offset != null) {
DateTime.parseDateTimeString(time_offset, null);
}
if (aggregator != null && !aggregator.isEmpty()) {
try {
Aggregators.get(aggregator.toLowerCase());
} catch (final NoSuchElementException e) {
throw new IllegalArgumentException("Invalid aggregator");
}
}
if (fill_policy != null) {
fill_policy.validate();
}
}
|
[
"public",
"void",
"validate",
"(",
")",
"{",
"if",
"(",
"metric",
"==",
"null",
"||",
"metric",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"missing or empty metric\"",
")",
";",
"}",
"if",
"(",
"id",
"==",
"null",
"||",
"id",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"missing or empty id\"",
")",
";",
"}",
"Query",
".",
"validateId",
"(",
"id",
")",
";",
"if",
"(",
"time_offset",
"!=",
"null",
")",
"{",
"DateTime",
".",
"parseDateTimeString",
"(",
"time_offset",
",",
"null",
")",
";",
"}",
"if",
"(",
"aggregator",
"!=",
"null",
"&&",
"!",
"aggregator",
".",
"isEmpty",
"(",
")",
")",
"{",
"try",
"{",
"Aggregators",
".",
"get",
"(",
"aggregator",
".",
"toLowerCase",
"(",
")",
")",
";",
"}",
"catch",
"(",
"final",
"NoSuchElementException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid aggregator\"",
")",
";",
"}",
"}",
"if",
"(",
"fill_policy",
"!=",
"null",
")",
"{",
"fill_policy",
".",
"validate",
"(",
")",
";",
"}",
"}"
] |
Validates the metric
@throws IllegalArgumentException if one or more parameters were invalid
|
[
"Validates",
"the",
"metric"
] |
3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/query/pojo/Metric.java#L102-L127
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.