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
156,600
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java
StringGroovyMethods.unexpand
public static String unexpand(CharSequence self, int tabStop) { String s = self.toString(); if (s.length() == 0) return s; try { StringBuilder builder = new StringBuilder(); for (String line : readLines((CharSequence) s)) { builder.append(unexpandLine(line, tabStop)); builder.append("\n"); } // remove the normalized ending line ending if it was not present if (!s.endsWith("\n")) { builder.deleteCharAt(builder.length() - 1); } return builder.toString(); } catch (IOException e) { /* ignore */ } return s; }
java
public static String unexpand(CharSequence self, int tabStop) { String s = self.toString(); if (s.length() == 0) return s; try { StringBuilder builder = new StringBuilder(); for (String line : readLines((CharSequence) s)) { builder.append(unexpandLine(line, tabStop)); builder.append("\n"); } // remove the normalized ending line ending if it was not present if (!s.endsWith("\n")) { builder.deleteCharAt(builder.length() - 1); } return builder.toString(); } catch (IOException e) { /* ignore */ } return s; }
[ "public", "static", "String", "unexpand", "(", "CharSequence", "self", ",", "int", "tabStop", ")", "{", "String", "s", "=", "self", ".", "toString", "(", ")", ";", "if", "(", "s", ".", "length", "(", ")", "==", "0", ")", "return", "s", ";", "try", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "String", "line", ":", "readLines", "(", "(", "CharSequence", ")", "s", ")", ")", "{", "builder", ".", "append", "(", "unexpandLine", "(", "line", ",", "tabStop", ")", ")", ";", "builder", ".", "append", "(", "\"\\n\"", ")", ";", "}", "// remove the normalized ending line ending if it was not present", "if", "(", "!", "s", ".", "endsWith", "(", "\"\\n\"", ")", ")", "{", "builder", ".", "deleteCharAt", "(", "builder", ".", "length", "(", ")", "-", "1", ")", ";", "}", "return", "builder", ".", "toString", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "/* ignore */", "}", "return", "s", ";", "}" ]
Replaces sequences of whitespaces with tabs. @param self A CharSequence to unexpand @param tabStop The number of spaces a tab represents @return an unexpanded String @since 1.8.2
[ "Replaces", "sequences", "of", "whitespaces", "with", "tabs", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java#L3580-L3598
156,601
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java
StringGroovyMethods.unexpandLine
public static String unexpandLine(CharSequence self, int tabStop) { StringBuilder builder = new StringBuilder(self.toString()); int index = 0; while (index + tabStop < builder.length()) { // cut original string in tabstop-length pieces String piece = builder.substring(index, index + tabStop); // count trailing whitespace characters int count = 0; while ((count < tabStop) && (Character.isWhitespace(piece.charAt(tabStop - (count + 1))))) count++; // replace if whitespace was found if (count > 0) { piece = piece.substring(0, tabStop - count) + '\t'; builder.replace(index, index + tabStop, piece); index = index + tabStop - (count - 1); } else index = index + tabStop; } return builder.toString(); }
java
public static String unexpandLine(CharSequence self, int tabStop) { StringBuilder builder = new StringBuilder(self.toString()); int index = 0; while (index + tabStop < builder.length()) { // cut original string in tabstop-length pieces String piece = builder.substring(index, index + tabStop); // count trailing whitespace characters int count = 0; while ((count < tabStop) && (Character.isWhitespace(piece.charAt(tabStop - (count + 1))))) count++; // replace if whitespace was found if (count > 0) { piece = piece.substring(0, tabStop - count) + '\t'; builder.replace(index, index + tabStop, piece); index = index + tabStop - (count - 1); } else index = index + tabStop; } return builder.toString(); }
[ "public", "static", "String", "unexpandLine", "(", "CharSequence", "self", ",", "int", "tabStop", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", "self", ".", "toString", "(", ")", ")", ";", "int", "index", "=", "0", ";", "while", "(", "index", "+", "tabStop", "<", "builder", ".", "length", "(", ")", ")", "{", "// cut original string in tabstop-length pieces", "String", "piece", "=", "builder", ".", "substring", "(", "index", ",", "index", "+", "tabStop", ")", ";", "// count trailing whitespace characters", "int", "count", "=", "0", ";", "while", "(", "(", "count", "<", "tabStop", ")", "&&", "(", "Character", ".", "isWhitespace", "(", "piece", ".", "charAt", "(", "tabStop", "-", "(", "count", "+", "1", ")", ")", ")", ")", ")", "count", "++", ";", "// replace if whitespace was found", "if", "(", "count", ">", "0", ")", "{", "piece", "=", "piece", ".", "substring", "(", "0", ",", "tabStop", "-", "count", ")", "+", "'", "'", ";", "builder", ".", "replace", "(", "index", ",", "index", "+", "tabStop", ",", "piece", ")", ";", "index", "=", "index", "+", "tabStop", "-", "(", "count", "-", "1", ")", ";", "}", "else", "index", "=", "index", "+", "tabStop", ";", "}", "return", "builder", ".", "toString", "(", ")", ";", "}" ]
Replaces sequences of whitespaces with tabs within a line. @param self A line to unexpand @param tabStop The number of spaces a tab represents @return an unexpanded String @since 1.8.2
[ "Replaces", "sequences", "of", "whitespaces", "with", "tabs", "within", "a", "line", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java#L3626-L3645
156,602
groovy/groovy-core
src/main/org/codehaus/groovy/ast/ClassNode.java
ClassNode.hasPossibleMethod
public boolean hasPossibleMethod(String name, Expression arguments) { int count = 0; if (arguments instanceof TupleExpression) { TupleExpression tuple = (TupleExpression) arguments; // TODO this won't strictly be true when using list expansion in argument calls count = tuple.getExpressions().size(); } ClassNode node = this; do { for (MethodNode method : getMethods(name)) { if (method.getParameters().length == count && !method.isStatic()) { return true; } } node = node.getSuperClass(); } while (node != null); return false; }
java
public boolean hasPossibleMethod(String name, Expression arguments) { int count = 0; if (arguments instanceof TupleExpression) { TupleExpression tuple = (TupleExpression) arguments; // TODO this won't strictly be true when using list expansion in argument calls count = tuple.getExpressions().size(); } ClassNode node = this; do { for (MethodNode method : getMethods(name)) { if (method.getParameters().length == count && !method.isStatic()) { return true; } } node = node.getSuperClass(); } while (node != null); return false; }
[ "public", "boolean", "hasPossibleMethod", "(", "String", "name", ",", "Expression", "arguments", ")", "{", "int", "count", "=", "0", ";", "if", "(", "arguments", "instanceof", "TupleExpression", ")", "{", "TupleExpression", "tuple", "=", "(", "TupleExpression", ")", "arguments", ";", "// TODO this won't strictly be true when using list expansion in argument calls", "count", "=", "tuple", ".", "getExpressions", "(", ")", ".", "size", "(", ")", ";", "}", "ClassNode", "node", "=", "this", ";", "do", "{", "for", "(", "MethodNode", "method", ":", "getMethods", "(", "name", ")", ")", "{", "if", "(", "method", ".", "getParameters", "(", ")", ".", "length", "==", "count", "&&", "!", "method", ".", "isStatic", "(", ")", ")", "{", "return", "true", ";", "}", "}", "node", "=", "node", ".", "getSuperClass", "(", ")", ";", "}", "while", "(", "node", "!=", "null", ")", ";", "return", "false", ";", "}" ]
Returns true if the given method has a possibly matching instance method with the given name and arguments. @param name the name of the method of interest @param arguments the arguments to match against @return true if a matching method was found
[ "Returns", "true", "if", "the", "given", "method", "has", "a", "possibly", "matching", "instance", "method", "with", "the", "given", "name", "and", "arguments", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/ast/ClassNode.java#L1221-L1240
156,603
groovy/groovy-core
src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
StaticTypeCheckingVisitor.checkOrMarkPrivateAccess
private void checkOrMarkPrivateAccess(Expression source, FieldNode fn) { if (fn!=null && Modifier.isPrivate(fn.getModifiers()) && (fn.getDeclaringClass() != typeCheckingContext.getEnclosingClassNode() || typeCheckingContext.getEnclosingClosure()!=null) && fn.getDeclaringClass().getModule() == typeCheckingContext.getEnclosingClassNode().getModule()) { addPrivateFieldOrMethodAccess(source, fn.getDeclaringClass(), StaticTypesMarker.PV_FIELDS_ACCESS, fn); } }
java
private void checkOrMarkPrivateAccess(Expression source, FieldNode fn) { if (fn!=null && Modifier.isPrivate(fn.getModifiers()) && (fn.getDeclaringClass() != typeCheckingContext.getEnclosingClassNode() || typeCheckingContext.getEnclosingClosure()!=null) && fn.getDeclaringClass().getModule() == typeCheckingContext.getEnclosingClassNode().getModule()) { addPrivateFieldOrMethodAccess(source, fn.getDeclaringClass(), StaticTypesMarker.PV_FIELDS_ACCESS, fn); } }
[ "private", "void", "checkOrMarkPrivateAccess", "(", "Expression", "source", ",", "FieldNode", "fn", ")", "{", "if", "(", "fn", "!=", "null", "&&", "Modifier", ".", "isPrivate", "(", "fn", ".", "getModifiers", "(", ")", ")", "&&", "(", "fn", ".", "getDeclaringClass", "(", ")", "!=", "typeCheckingContext", ".", "getEnclosingClassNode", "(", ")", "||", "typeCheckingContext", ".", "getEnclosingClosure", "(", ")", "!=", "null", ")", "&&", "fn", ".", "getDeclaringClass", "(", ")", ".", "getModule", "(", ")", "==", "typeCheckingContext", ".", "getEnclosingClassNode", "(", ")", ".", "getModule", "(", ")", ")", "{", "addPrivateFieldOrMethodAccess", "(", "source", ",", "fn", ".", "getDeclaringClass", "(", ")", ",", "StaticTypesMarker", ".", "PV_FIELDS_ACCESS", ",", "fn", ")", ";", "}", "}" ]
Given a field node, checks if we are calling a private field from an inner class.
[ "Given", "a", "field", "node", "checks", "if", "we", "are", "calling", "a", "private", "field", "from", "an", "inner", "class", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L347-L353
156,604
groovy/groovy-core
src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
StaticTypeCheckingVisitor.checkOrMarkPrivateAccess
private void checkOrMarkPrivateAccess(Expression source, MethodNode mn) { if (mn==null) { return; } ClassNode declaringClass = mn.getDeclaringClass(); ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode(); if (declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) { int mods = mn.getModifiers(); boolean sameModule = declaringClass.getModule() == enclosingClassNode.getModule(); String packageName = declaringClass.getPackageName(); if (packageName==null) { packageName = ""; } if ((Modifier.isPrivate(mods) && sameModule) || (Modifier.isProtected(mods) && !packageName.equals(enclosingClassNode.getPackageName()))) { addPrivateFieldOrMethodAccess(source, sameModule? declaringClass : enclosingClassNode, StaticTypesMarker.PV_METHODS_ACCESS, mn); } } }
java
private void checkOrMarkPrivateAccess(Expression source, MethodNode mn) { if (mn==null) { return; } ClassNode declaringClass = mn.getDeclaringClass(); ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode(); if (declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) { int mods = mn.getModifiers(); boolean sameModule = declaringClass.getModule() == enclosingClassNode.getModule(); String packageName = declaringClass.getPackageName(); if (packageName==null) { packageName = ""; } if ((Modifier.isPrivate(mods) && sameModule) || (Modifier.isProtected(mods) && !packageName.equals(enclosingClassNode.getPackageName()))) { addPrivateFieldOrMethodAccess(source, sameModule? declaringClass : enclosingClassNode, StaticTypesMarker.PV_METHODS_ACCESS, mn); } } }
[ "private", "void", "checkOrMarkPrivateAccess", "(", "Expression", "source", ",", "MethodNode", "mn", ")", "{", "if", "(", "mn", "==", "null", ")", "{", "return", ";", "}", "ClassNode", "declaringClass", "=", "mn", ".", "getDeclaringClass", "(", ")", ";", "ClassNode", "enclosingClassNode", "=", "typeCheckingContext", ".", "getEnclosingClassNode", "(", ")", ";", "if", "(", "declaringClass", "!=", "enclosingClassNode", "||", "typeCheckingContext", ".", "getEnclosingClosure", "(", ")", "!=", "null", ")", "{", "int", "mods", "=", "mn", ".", "getModifiers", "(", ")", ";", "boolean", "sameModule", "=", "declaringClass", ".", "getModule", "(", ")", "==", "enclosingClassNode", ".", "getModule", "(", ")", ";", "String", "packageName", "=", "declaringClass", ".", "getPackageName", "(", ")", ";", "if", "(", "packageName", "==", "null", ")", "{", "packageName", "=", "\"\"", ";", "}", "if", "(", "(", "Modifier", ".", "isPrivate", "(", "mods", ")", "&&", "sameModule", ")", "||", "(", "Modifier", ".", "isProtected", "(", "mods", ")", "&&", "!", "packageName", ".", "equals", "(", "enclosingClassNode", ".", "getPackageName", "(", ")", ")", ")", ")", "{", "addPrivateFieldOrMethodAccess", "(", "source", ",", "sameModule", "?", "declaringClass", ":", "enclosingClassNode", ",", "StaticTypesMarker", ".", "PV_METHODS_ACCESS", ",", "mn", ")", ";", "}", "}", "}" ]
Given a method node, checks if we are calling a private method from an inner class.
[ "Given", "a", "method", "node", "checks", "if", "we", "are", "calling", "a", "private", "method", "from", "an", "inner", "class", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L358-L376
156,605
groovy/groovy-core
src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
StaticTypeCheckingVisitor.ensureValidSetter
private boolean ensureValidSetter(final Expression expression, final Expression leftExpression, final Expression rightExpression, final SetterInfo setterInfo) { // for expressions like foo = { ... } // we know that the RHS type is a closure // but we must check if the binary expression is an assignment // because we need to check if a setter uses @DelegatesTo VariableExpression ve = new VariableExpression("%", setterInfo.receiverType); MethodCallExpression call = new MethodCallExpression( ve, setterInfo.name, rightExpression ); call.setImplicitThis(false); visitMethodCallExpression(call); MethodNode directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET); if (directSetterCandidate==null) { // this may happen if there's a setter of type boolean/String/Class, and that we are using the property // notation AND that the RHS is not a boolean/String/Class for (MethodNode setter : setterInfo.setters) { ClassNode type = getWrapper(setter.getParameters()[0].getOriginType()); if (Boolean_TYPE.equals(type) || STRING_TYPE.equals(type) || CLASS_Type.equals(type)) { call = new MethodCallExpression( ve, setterInfo.name, new CastExpression(type,rightExpression) ); call.setImplicitThis(false); visitMethodCallExpression(call); directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET); if (directSetterCandidate!=null) { break; } } } } if (directSetterCandidate != null) { for (MethodNode setter : setterInfo.setters) { if (setter == directSetterCandidate) { leftExpression.putNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, directSetterCandidate); storeType(leftExpression, getType(rightExpression)); break; } } } else { ClassNode firstSetterType = setterInfo.setters.iterator().next().getParameters()[0].getOriginType(); addAssignmentError(firstSetterType, getType(rightExpression), expression); return true; } return false; }
java
private boolean ensureValidSetter(final Expression expression, final Expression leftExpression, final Expression rightExpression, final SetterInfo setterInfo) { // for expressions like foo = { ... } // we know that the RHS type is a closure // but we must check if the binary expression is an assignment // because we need to check if a setter uses @DelegatesTo VariableExpression ve = new VariableExpression("%", setterInfo.receiverType); MethodCallExpression call = new MethodCallExpression( ve, setterInfo.name, rightExpression ); call.setImplicitThis(false); visitMethodCallExpression(call); MethodNode directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET); if (directSetterCandidate==null) { // this may happen if there's a setter of type boolean/String/Class, and that we are using the property // notation AND that the RHS is not a boolean/String/Class for (MethodNode setter : setterInfo.setters) { ClassNode type = getWrapper(setter.getParameters()[0].getOriginType()); if (Boolean_TYPE.equals(type) || STRING_TYPE.equals(type) || CLASS_Type.equals(type)) { call = new MethodCallExpression( ve, setterInfo.name, new CastExpression(type,rightExpression) ); call.setImplicitThis(false); visitMethodCallExpression(call); directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET); if (directSetterCandidate!=null) { break; } } } } if (directSetterCandidate != null) { for (MethodNode setter : setterInfo.setters) { if (setter == directSetterCandidate) { leftExpression.putNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, directSetterCandidate); storeType(leftExpression, getType(rightExpression)); break; } } } else { ClassNode firstSetterType = setterInfo.setters.iterator().next().getParameters()[0].getOriginType(); addAssignmentError(firstSetterType, getType(rightExpression), expression); return true; } return false; }
[ "private", "boolean", "ensureValidSetter", "(", "final", "Expression", "expression", ",", "final", "Expression", "leftExpression", ",", "final", "Expression", "rightExpression", ",", "final", "SetterInfo", "setterInfo", ")", "{", "// for expressions like foo = { ... }", "// we know that the RHS type is a closure", "// but we must check if the binary expression is an assignment", "// because we need to check if a setter uses @DelegatesTo", "VariableExpression", "ve", "=", "new", "VariableExpression", "(", "\"%\"", ",", "setterInfo", ".", "receiverType", ")", ";", "MethodCallExpression", "call", "=", "new", "MethodCallExpression", "(", "ve", ",", "setterInfo", ".", "name", ",", "rightExpression", ")", ";", "call", ".", "setImplicitThis", "(", "false", ")", ";", "visitMethodCallExpression", "(", "call", ")", ";", "MethodNode", "directSetterCandidate", "=", "call", ".", "getNodeMetaData", "(", "StaticTypesMarker", ".", "DIRECT_METHOD_CALL_TARGET", ")", ";", "if", "(", "directSetterCandidate", "==", "null", ")", "{", "// this may happen if there's a setter of type boolean/String/Class, and that we are using the property", "// notation AND that the RHS is not a boolean/String/Class", "for", "(", "MethodNode", "setter", ":", "setterInfo", ".", "setters", ")", "{", "ClassNode", "type", "=", "getWrapper", "(", "setter", ".", "getParameters", "(", ")", "[", "0", "]", ".", "getOriginType", "(", ")", ")", ";", "if", "(", "Boolean_TYPE", ".", "equals", "(", "type", ")", "||", "STRING_TYPE", ".", "equals", "(", "type", ")", "||", "CLASS_Type", ".", "equals", "(", "type", ")", ")", "{", "call", "=", "new", "MethodCallExpression", "(", "ve", ",", "setterInfo", ".", "name", ",", "new", "CastExpression", "(", "type", ",", "rightExpression", ")", ")", ";", "call", ".", "setImplicitThis", "(", "false", ")", ";", "visitMethodCallExpression", "(", "call", ")", ";", "directSetterCandidate", "=", "call", ".", "getNodeMetaData", "(", "StaticTypesMarker", ".", "DIRECT_METHOD_CALL_TARGET", ")", ";", "if", "(", "directSetterCandidate", "!=", "null", ")", "{", "break", ";", "}", "}", "}", "}", "if", "(", "directSetterCandidate", "!=", "null", ")", "{", "for", "(", "MethodNode", "setter", ":", "setterInfo", ".", "setters", ")", "{", "if", "(", "setter", "==", "directSetterCandidate", ")", "{", "leftExpression", ".", "putNodeMetaData", "(", "StaticTypesMarker", ".", "DIRECT_METHOD_CALL_TARGET", ",", "directSetterCandidate", ")", ";", "storeType", "(", "leftExpression", ",", "getType", "(", "rightExpression", ")", ")", ";", "break", ";", "}", "}", "}", "else", "{", "ClassNode", "firstSetterType", "=", "setterInfo", ".", "setters", ".", "iterator", "(", ")", ".", "next", "(", ")", ".", "getParameters", "(", ")", "[", "0", "]", ".", "getOriginType", "(", ")", ";", "addAssignmentError", "(", "firstSetterType", ",", "getType", "(", "rightExpression", ")", ",", "expression", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Given a binary expression corresponding to an assignment, will check that the type of the RHS matches one of the possible setters and if not, throw a type checking error. @param expression the assignment expression @param leftExpression left expression of the assignment @param rightExpression right expression of the assignment @param setterInfo possible setters @return true if type checking passed
[ "Given", "a", "binary", "expression", "corresponding", "to", "an", "assignment", "will", "check", "that", "the", "type", "of", "the", "RHS", "matches", "one", "of", "the", "possible", "setters", "and", "if", "not", "throw", "a", "type", "checking", "error", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L704-L752
156,606
groovy/groovy-core
src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
StaticTypeCheckingVisitor.addArrayMethods
private void addArrayMethods(List<MethodNode> methods, ClassNode receiver, String name, ClassNode[] args) { if (args.length!=1) return; if (!receiver.isArray()) return; if (!isIntCategory(getUnwrapper(args[0]))) return; if ("getAt".equals(name)) { MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, receiver.getComponentType(), new Parameter[]{new Parameter(args[0],"arg")}, null, null); node.setDeclaringClass(receiver.redirect()); methods.add(node); } else if ("setAt".equals(name)) { MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, VOID_TYPE, new Parameter[]{new Parameter(args[0],"arg")}, null, null); node.setDeclaringClass(receiver.redirect()); methods.add(node); } }
java
private void addArrayMethods(List<MethodNode> methods, ClassNode receiver, String name, ClassNode[] args) { if (args.length!=1) return; if (!receiver.isArray()) return; if (!isIntCategory(getUnwrapper(args[0]))) return; if ("getAt".equals(name)) { MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, receiver.getComponentType(), new Parameter[]{new Parameter(args[0],"arg")}, null, null); node.setDeclaringClass(receiver.redirect()); methods.add(node); } else if ("setAt".equals(name)) { MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC, VOID_TYPE, new Parameter[]{new Parameter(args[0],"arg")}, null, null); node.setDeclaringClass(receiver.redirect()); methods.add(node); } }
[ "private", "void", "addArrayMethods", "(", "List", "<", "MethodNode", ">", "methods", ",", "ClassNode", "receiver", ",", "String", "name", ",", "ClassNode", "[", "]", "args", ")", "{", "if", "(", "args", ".", "length", "!=", "1", ")", "return", ";", "if", "(", "!", "receiver", ".", "isArray", "(", ")", ")", "return", ";", "if", "(", "!", "isIntCategory", "(", "getUnwrapper", "(", "args", "[", "0", "]", ")", ")", ")", "return", ";", "if", "(", "\"getAt\"", ".", "equals", "(", "name", ")", ")", "{", "MethodNode", "node", "=", "new", "MethodNode", "(", "name", ",", "Opcodes", ".", "ACC_PUBLIC", ",", "receiver", ".", "getComponentType", "(", ")", ",", "new", "Parameter", "[", "]", "{", "new", "Parameter", "(", "args", "[", "0", "]", ",", "\"arg\"", ")", "}", ",", "null", ",", "null", ")", ";", "node", ".", "setDeclaringClass", "(", "receiver", ".", "redirect", "(", ")", ")", ";", "methods", ".", "add", "(", "node", ")", ";", "}", "else", "if", "(", "\"setAt\"", ".", "equals", "(", "name", ")", ")", "{", "MethodNode", "node", "=", "new", "MethodNode", "(", "name", ",", "Opcodes", ".", "ACC_PUBLIC", ",", "VOID_TYPE", ",", "new", "Parameter", "[", "]", "{", "new", "Parameter", "(", "args", "[", "0", "]", ",", "\"arg\"", ")", "}", ",", "null", ",", "null", ")", ";", "node", ".", "setDeclaringClass", "(", "receiver", ".", "redirect", "(", ")", ")", ";", "methods", ".", "add", "(", "node", ")", ";", "}", "}" ]
add various getAt and setAt methods for primitive arrays @param receiver the receiver class @param name the name of the method @param args the argument classes
[ "add", "various", "getAt", "and", "setAt", "methods", "for", "primitive", "arrays" ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L3011-L3024
156,607
groovy/groovy-core
src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
StaticTypeCheckingVisitor.getGenericsResolvedTypeOfFieldOrProperty
private ClassNode getGenericsResolvedTypeOfFieldOrProperty(AnnotatedNode an, ClassNode type) { if (!type.isUsingGenerics()) return type; Map<String, GenericsType> connections = new HashMap(); //TODO: inner classes mean a different this-type. This is ignored here! extractGenericsConnections(connections, typeCheckingContext.getEnclosingClassNode(), an.getDeclaringClass()); type= applyGenericsContext(connections, type); return type; }
java
private ClassNode getGenericsResolvedTypeOfFieldOrProperty(AnnotatedNode an, ClassNode type) { if (!type.isUsingGenerics()) return type; Map<String, GenericsType> connections = new HashMap(); //TODO: inner classes mean a different this-type. This is ignored here! extractGenericsConnections(connections, typeCheckingContext.getEnclosingClassNode(), an.getDeclaringClass()); type= applyGenericsContext(connections, type); return type; }
[ "private", "ClassNode", "getGenericsResolvedTypeOfFieldOrProperty", "(", "AnnotatedNode", "an", ",", "ClassNode", "type", ")", "{", "if", "(", "!", "type", ".", "isUsingGenerics", "(", ")", ")", "return", "type", ";", "Map", "<", "String", ",", "GenericsType", ">", "connections", "=", "new", "HashMap", "(", ")", ";", "//TODO: inner classes mean a different this-type. This is ignored here!", "extractGenericsConnections", "(", "connections", ",", "typeCheckingContext", ".", "getEnclosingClassNode", "(", ")", ",", "an", ".", "getDeclaringClass", "(", ")", ")", ";", "type", "=", "applyGenericsContext", "(", "connections", ",", "type", ")", ";", "return", "type", ";", "}" ]
resolves a Field or Property node generics by using the current class and the declaring class to extract the right meaning of the generics symbols @param an a FieldNode or PropertyNode @param type the origin type @return the new ClassNode with corrected generics
[ "resolves", "a", "Field", "or", "Property", "node", "generics", "by", "using", "the", "current", "class", "and", "the", "declaring", "class", "to", "extract", "the", "right", "meaning", "of", "the", "generics", "symbols" ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L4000-L4007
156,608
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/EncodingGroovyMethods.java
EncodingGroovyMethods.decodeBase64
public static byte[] decodeBase64(String value) { int byteShift = 4; int tmp = 0; boolean done = false; final StringBuilder buffer = new StringBuilder(); for (int i = 0; i != value.length(); i++) { final char c = value.charAt(i); final int sixBit = (c < 123) ? EncodingGroovyMethodsSupport.TRANSLATE_TABLE[c] : 66; if (sixBit < 64) { if (done) throw new RuntimeException("= character not at end of base64 value"); // TODO: change this exception type tmp = (tmp << 6) | sixBit; if (byteShift-- != 4) { buffer.append((char) ((tmp >> (byteShift * 2)) & 0XFF)); } } else if (sixBit == 64) { byteShift--; done = true; } else if (sixBit == 66) { // RFC 2045 says that I'm allowed to take the presence of // these characters as evidence of data corruption // So I will throw new RuntimeException("bad character in base64 value"); // TODO: change this exception type } if (byteShift == 0) byteShift = 4; } try { return buffer.toString().getBytes("ISO-8859-1"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Base 64 decode produced byte values > 255"); // TODO: change this exception type } }
java
public static byte[] decodeBase64(String value) { int byteShift = 4; int tmp = 0; boolean done = false; final StringBuilder buffer = new StringBuilder(); for (int i = 0; i != value.length(); i++) { final char c = value.charAt(i); final int sixBit = (c < 123) ? EncodingGroovyMethodsSupport.TRANSLATE_TABLE[c] : 66; if (sixBit < 64) { if (done) throw new RuntimeException("= character not at end of base64 value"); // TODO: change this exception type tmp = (tmp << 6) | sixBit; if (byteShift-- != 4) { buffer.append((char) ((tmp >> (byteShift * 2)) & 0XFF)); } } else if (sixBit == 64) { byteShift--; done = true; } else if (sixBit == 66) { // RFC 2045 says that I'm allowed to take the presence of // these characters as evidence of data corruption // So I will throw new RuntimeException("bad character in base64 value"); // TODO: change this exception type } if (byteShift == 0) byteShift = 4; } try { return buffer.toString().getBytes("ISO-8859-1"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Base 64 decode produced byte values > 255"); // TODO: change this exception type } }
[ "public", "static", "byte", "[", "]", "decodeBase64", "(", "String", "value", ")", "{", "int", "byteShift", "=", "4", ";", "int", "tmp", "=", "0", ";", "boolean", "done", "=", "false", ";", "final", "StringBuilder", "buffer", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "!=", "value", ".", "length", "(", ")", ";", "i", "++", ")", "{", "final", "char", "c", "=", "value", ".", "charAt", "(", "i", ")", ";", "final", "int", "sixBit", "=", "(", "c", "<", "123", ")", "?", "EncodingGroovyMethodsSupport", ".", "TRANSLATE_TABLE", "[", "c", "]", ":", "66", ";", "if", "(", "sixBit", "<", "64", ")", "{", "if", "(", "done", ")", "throw", "new", "RuntimeException", "(", "\"= character not at end of base64 value\"", ")", ";", "// TODO: change this exception type", "tmp", "=", "(", "tmp", "<<", "6", ")", "|", "sixBit", ";", "if", "(", "byteShift", "--", "!=", "4", ")", "{", "buffer", ".", "append", "(", "(", "char", ")", "(", "(", "tmp", ">>", "(", "byteShift", "*", "2", ")", ")", "&", "0XFF", ")", ")", ";", "}", "}", "else", "if", "(", "sixBit", "==", "64", ")", "{", "byteShift", "--", ";", "done", "=", "true", ";", "}", "else", "if", "(", "sixBit", "==", "66", ")", "{", "// RFC 2045 says that I'm allowed to take the presence of", "// these characters as evidence of data corruption", "// So I will", "throw", "new", "RuntimeException", "(", "\"bad character in base64 value\"", ")", ";", "// TODO: change this exception type", "}", "if", "(", "byteShift", "==", "0", ")", "byteShift", "=", "4", ";", "}", "try", "{", "return", "buffer", ".", "toString", "(", ")", ".", "getBytes", "(", "\"ISO-8859-1\"", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Base 64 decode produced byte values > 255\"", ")", ";", "// TODO: change this exception type", "}", "}" ]
Decode the String from Base64 into a byte array. @param value the string to be decoded @return the decoded bytes as an array @since 1.0
[ "Decode", "the", "String", "from", "Base64", "into", "a", "byte", "array", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/EncodingGroovyMethods.java#L151-L191
156,609
groovy/groovy-core
subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovy.java
Groovy.runStatements
protected void runStatements(Reader reader, PrintStream out) throws IOException { log.debug("runStatements()"); StringBuilder txt = new StringBuilder(); String line = ""; BufferedReader in = new BufferedReader(reader); while ((line = in.readLine()) != null) { line = getProject().replaceProperties(line); if (line.indexOf("--") >= 0) { txt.append("\n"); } } // Catch any statements not followed by ; if (!txt.toString().equals("")) { execGroovy(txt.toString(), out); } }
java
protected void runStatements(Reader reader, PrintStream out) throws IOException { log.debug("runStatements()"); StringBuilder txt = new StringBuilder(); String line = ""; BufferedReader in = new BufferedReader(reader); while ((line = in.readLine()) != null) { line = getProject().replaceProperties(line); if (line.indexOf("--") >= 0) { txt.append("\n"); } } // Catch any statements not followed by ; if (!txt.toString().equals("")) { execGroovy(txt.toString(), out); } }
[ "protected", "void", "runStatements", "(", "Reader", "reader", ",", "PrintStream", "out", ")", "throws", "IOException", "{", "log", ".", "debug", "(", "\"runStatements()\"", ")", ";", "StringBuilder", "txt", "=", "new", "StringBuilder", "(", ")", ";", "String", "line", "=", "\"\"", ";", "BufferedReader", "in", "=", "new", "BufferedReader", "(", "reader", ")", ";", "while", "(", "(", "line", "=", "in", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "line", "=", "getProject", "(", ")", ".", "replaceProperties", "(", "line", ")", ";", "if", "(", "line", ".", "indexOf", "(", "\"--\"", ")", ">=", "0", ")", "{", "txt", ".", "append", "(", "\"\\n\"", ")", ";", "}", "}", "// Catch any statements not followed by ;", "if", "(", "!", "txt", ".", "toString", "(", ")", ".", "equals", "(", "\"\"", ")", ")", "{", "execGroovy", "(", "txt", ".", "toString", "(", ")", ",", "out", ")", ";", "}", "}" ]
Read in lines and execute them. @param reader the reader from which to get the groovy source to exec @param out the outputstream to use @throws java.io.IOException if something goes wrong
[ "Read", "in", "lines", "and", "execute", "them", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovy.java#L354-L371
156,610
groovy/groovy-core
subprojects/groovy-json/src/main/java/groovy/json/JsonOutput.java
JsonOutput.toJson
public static String toJson(Date date) { if (date == null) { return NULL_VALUE; } CharBuf buffer = CharBuf.create(26); writeDate(date, buffer); return buffer.toString(); }
java
public static String toJson(Date date) { if (date == null) { return NULL_VALUE; } CharBuf buffer = CharBuf.create(26); writeDate(date, buffer); return buffer.toString(); }
[ "public", "static", "String", "toJson", "(", "Date", "date", ")", "{", "if", "(", "date", "==", "null", ")", "{", "return", "NULL_VALUE", ";", "}", "CharBuf", "buffer", "=", "CharBuf", ".", "create", "(", "26", ")", ";", "writeDate", "(", "date", ",", "buffer", ")", ";", "return", "buffer", ".", "toString", "(", ")", ";", "}" ]
Format a date that is parseable from JavaScript, according to ISO-8601. @param date the date to format to a JSON string @return a formatted date in the form of a string
[ "Format", "a", "date", "that", "is", "parseable", "from", "JavaScript", "according", "to", "ISO", "-", "8601", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/subprojects/groovy-json/src/main/java/groovy/json/JsonOutput.java#L105-L114
156,611
groovy/groovy-core
subprojects/groovy-json/src/main/java/groovy/json/JsonOutput.java
JsonOutput.toJson
public static String toJson(Calendar cal) { if (cal == null) { return NULL_VALUE; } CharBuf buffer = CharBuf.create(26); writeDate(cal.getTime(), buffer); return buffer.toString(); }
java
public static String toJson(Calendar cal) { if (cal == null) { return NULL_VALUE; } CharBuf buffer = CharBuf.create(26); writeDate(cal.getTime(), buffer); return buffer.toString(); }
[ "public", "static", "String", "toJson", "(", "Calendar", "cal", ")", "{", "if", "(", "cal", "==", "null", ")", "{", "return", "NULL_VALUE", ";", "}", "CharBuf", "buffer", "=", "CharBuf", ".", "create", "(", "26", ")", ";", "writeDate", "(", "cal", ".", "getTime", "(", ")", ",", "buffer", ")", ";", "return", "buffer", ".", "toString", "(", ")", ";", "}" ]
Format a calendar instance that is parseable from JavaScript, according to ISO-8601. @param cal the calendar to format to a JSON string @return a formatted date in the form of a string
[ "Format", "a", "calendar", "instance", "that", "is", "parseable", "from", "JavaScript", "according", "to", "ISO", "-", "8601", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/subprojects/groovy-json/src/main/java/groovy/json/JsonOutput.java#L122-L131
156,612
groovy/groovy-core
subprojects/groovy-json/src/main/java/groovy/json/JsonOutput.java
JsonOutput.writeNumber
private static void writeNumber(Class<?> numberClass, Number value, CharBuf buffer) { if (numberClass == Integer.class) { buffer.addInt((Integer) value); } else if (numberClass == Long.class) { buffer.addLong((Long) value); } else if (numberClass == BigInteger.class) { buffer.addBigInteger((BigInteger) value); } else if (numberClass == BigDecimal.class) { buffer.addBigDecimal((BigDecimal) value); } else if (numberClass == Double.class) { Double doubleValue = (Double) value; if (doubleValue.isInfinite()) { throw new JsonException("Number " + value + " can't be serialized as JSON: infinite are not allowed in JSON."); } if (doubleValue.isNaN()) { throw new JsonException("Number " + value + " can't be serialized as JSON: NaN are not allowed in JSON."); } buffer.addDouble(doubleValue); } else if (numberClass == Float.class) { Float floatValue = (Float) value; if (floatValue.isInfinite()) { throw new JsonException("Number " + value + " can't be serialized as JSON: infinite are not allowed in JSON."); } if (floatValue.isNaN()) { throw new JsonException("Number " + value + " can't be serialized as JSON: NaN are not allowed in JSON."); } buffer.addFloat(floatValue); } else if (numberClass == Byte.class) { buffer.addByte((Byte) value); } else if (numberClass == Short.class) { buffer.addShort((Short) value); } else { // Handle other Number implementations buffer.addString(value.toString()); } }
java
private static void writeNumber(Class<?> numberClass, Number value, CharBuf buffer) { if (numberClass == Integer.class) { buffer.addInt((Integer) value); } else if (numberClass == Long.class) { buffer.addLong((Long) value); } else if (numberClass == BigInteger.class) { buffer.addBigInteger((BigInteger) value); } else if (numberClass == BigDecimal.class) { buffer.addBigDecimal((BigDecimal) value); } else if (numberClass == Double.class) { Double doubleValue = (Double) value; if (doubleValue.isInfinite()) { throw new JsonException("Number " + value + " can't be serialized as JSON: infinite are not allowed in JSON."); } if (doubleValue.isNaN()) { throw new JsonException("Number " + value + " can't be serialized as JSON: NaN are not allowed in JSON."); } buffer.addDouble(doubleValue); } else if (numberClass == Float.class) { Float floatValue = (Float) value; if (floatValue.isInfinite()) { throw new JsonException("Number " + value + " can't be serialized as JSON: infinite are not allowed in JSON."); } if (floatValue.isNaN()) { throw new JsonException("Number " + value + " can't be serialized as JSON: NaN are not allowed in JSON."); } buffer.addFloat(floatValue); } else if (numberClass == Byte.class) { buffer.addByte((Byte) value); } else if (numberClass == Short.class) { buffer.addShort((Short) value); } else { // Handle other Number implementations buffer.addString(value.toString()); } }
[ "private", "static", "void", "writeNumber", "(", "Class", "<", "?", ">", "numberClass", ",", "Number", "value", ",", "CharBuf", "buffer", ")", "{", "if", "(", "numberClass", "==", "Integer", ".", "class", ")", "{", "buffer", ".", "addInt", "(", "(", "Integer", ")", "value", ")", ";", "}", "else", "if", "(", "numberClass", "==", "Long", ".", "class", ")", "{", "buffer", ".", "addLong", "(", "(", "Long", ")", "value", ")", ";", "}", "else", "if", "(", "numberClass", "==", "BigInteger", ".", "class", ")", "{", "buffer", ".", "addBigInteger", "(", "(", "BigInteger", ")", "value", ")", ";", "}", "else", "if", "(", "numberClass", "==", "BigDecimal", ".", "class", ")", "{", "buffer", ".", "addBigDecimal", "(", "(", "BigDecimal", ")", "value", ")", ";", "}", "else", "if", "(", "numberClass", "==", "Double", ".", "class", ")", "{", "Double", "doubleValue", "=", "(", "Double", ")", "value", ";", "if", "(", "doubleValue", ".", "isInfinite", "(", ")", ")", "{", "throw", "new", "JsonException", "(", "\"Number \"", "+", "value", "+", "\" can't be serialized as JSON: infinite are not allowed in JSON.\"", ")", ";", "}", "if", "(", "doubleValue", ".", "isNaN", "(", ")", ")", "{", "throw", "new", "JsonException", "(", "\"Number \"", "+", "value", "+", "\" can't be serialized as JSON: NaN are not allowed in JSON.\"", ")", ";", "}", "buffer", ".", "addDouble", "(", "doubleValue", ")", ";", "}", "else", "if", "(", "numberClass", "==", "Float", ".", "class", ")", "{", "Float", "floatValue", "=", "(", "Float", ")", "value", ";", "if", "(", "floatValue", ".", "isInfinite", "(", ")", ")", "{", "throw", "new", "JsonException", "(", "\"Number \"", "+", "value", "+", "\" can't be serialized as JSON: infinite are not allowed in JSON.\"", ")", ";", "}", "if", "(", "floatValue", ".", "isNaN", "(", ")", ")", "{", "throw", "new", "JsonException", "(", "\"Number \"", "+", "value", "+", "\" can't be serialized as JSON: NaN are not allowed in JSON.\"", ")", ";", "}", "buffer", ".", "addFloat", "(", "floatValue", ")", ";", "}", "else", "if", "(", "numberClass", "==", "Byte", ".", "class", ")", "{", "buffer", ".", "addByte", "(", "(", "Byte", ")", "value", ")", ";", "}", "else", "if", "(", "numberClass", "==", "Short", ".", "class", ")", "{", "buffer", ".", "addShort", "(", "(", "Short", ")", "value", ")", ";", "}", "else", "{", "// Handle other Number implementations", "buffer", ".", "addString", "(", "value", ".", "toString", "(", ")", ")", ";", "}", "}" ]
Serializes Number value and writes it into specified buffer.
[ "Serializes", "Number", "value", "and", "writes", "it", "into", "specified", "buffer", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/subprojects/groovy-json/src/main/java/groovy/json/JsonOutput.java#L209-L245
156,613
groovy/groovy-core
subprojects/groovy-json/src/main/java/groovy/json/JsonOutput.java
JsonOutput.writeCharSequence
private static void writeCharSequence(CharSequence seq, CharBuf buffer) { if (seq.length() > 0) { buffer.addJsonEscapedString(seq.toString()); } else { buffer.addChars(EMPTY_STRING_CHARS); } }
java
private static void writeCharSequence(CharSequence seq, CharBuf buffer) { if (seq.length() > 0) { buffer.addJsonEscapedString(seq.toString()); } else { buffer.addChars(EMPTY_STRING_CHARS); } }
[ "private", "static", "void", "writeCharSequence", "(", "CharSequence", "seq", ",", "CharBuf", "buffer", ")", "{", "if", "(", "seq", ".", "length", "(", ")", ">", "0", ")", "{", "buffer", ".", "addJsonEscapedString", "(", "seq", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "buffer", ".", "addChars", "(", "EMPTY_STRING_CHARS", ")", ";", "}", "}" ]
Serializes any char sequence and writes it into specified buffer.
[ "Serializes", "any", "char", "sequence", "and", "writes", "it", "into", "specified", "buffer", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/subprojects/groovy-json/src/main/java/groovy/json/JsonOutput.java#L304-L310
156,614
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/typehandling/ShortTypeHandling.java
ShortTypeHandling.castToEnum
public static Enum castToEnum(Object object, Class<? extends Enum> type) { if (object==null) return null; if (type.isInstance(object)) return (Enum) object; if (object instanceof String || object instanceof GString) { return Enum.valueOf(type, object.toString()); } throw new GroovyCastException(object, type); }
java
public static Enum castToEnum(Object object, Class<? extends Enum> type) { if (object==null) return null; if (type.isInstance(object)) return (Enum) object; if (object instanceof String || object instanceof GString) { return Enum.valueOf(type, object.toString()); } throw new GroovyCastException(object, type); }
[ "public", "static", "Enum", "castToEnum", "(", "Object", "object", ",", "Class", "<", "?", "extends", "Enum", ">", "type", ")", "{", "if", "(", "object", "==", "null", ")", "return", "null", ";", "if", "(", "type", ".", "isInstance", "(", "object", ")", ")", "return", "(", "Enum", ")", "object", ";", "if", "(", "object", "instanceof", "String", "||", "object", "instanceof", "GString", ")", "{", "return", "Enum", ".", "valueOf", "(", "type", ",", "object", ".", "toString", "(", ")", ")", ";", "}", "throw", "new", "GroovyCastException", "(", "object", ",", "type", ")", ";", "}" ]
this class requires that the supplied enum is not fitting a Collection case for casting
[ "this", "class", "requires", "that", "the", "supplied", "enum", "is", "not", "fitting", "a", "Collection", "case", "for", "casting" ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/typehandling/ShortTypeHandling.java#L52-L59
156,615
groovy/groovy-core
subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovyc.java
Groovyc.setTargetBytecode
public void setTargetBytecode(String version) { if (CompilerConfiguration.PRE_JDK5.equals(version) || CompilerConfiguration.POST_JDK5.equals(version)) { this.targetBytecode = version; } }
java
public void setTargetBytecode(String version) { if (CompilerConfiguration.PRE_JDK5.equals(version) || CompilerConfiguration.POST_JDK5.equals(version)) { this.targetBytecode = version; } }
[ "public", "void", "setTargetBytecode", "(", "String", "version", ")", "{", "if", "(", "CompilerConfiguration", ".", "PRE_JDK5", ".", "equals", "(", "version", ")", "||", "CompilerConfiguration", ".", "POST_JDK5", ".", "equals", "(", "version", ")", ")", "{", "this", ".", "targetBytecode", "=", "version", ";", "}", "}" ]
Sets the bytecode compatibility mode @param version the bytecode compatibility mode
[ "Sets", "the", "bytecode", "compatibility", "mode" ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovyc.java#L292-L296
156,616
groovy/groovy-core
src/main/groovy/util/Node.java
Node.depthFirst
public List depthFirst() { List answer = new NodeList(); answer.add(this); answer.addAll(depthFirstRest()); return answer; }
java
public List depthFirst() { List answer = new NodeList(); answer.add(this); answer.addAll(depthFirstRest()); return answer; }
[ "public", "List", "depthFirst", "(", ")", "{", "List", "answer", "=", "new", "NodeList", "(", ")", ";", "answer", ".", "add", "(", "this", ")", ";", "answer", ".", "addAll", "(", "depthFirstRest", "(", ")", ")", ";", "return", "answer", ";", "}" ]
Provides a collection of all the nodes in the tree using a depth first traversal. @return the list of (depth-first) ordered nodes
[ "Provides", "a", "collection", "of", "all", "the", "nodes", "in", "the", "tree", "using", "a", "depth", "first", "traversal", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/groovy/util/Node.java#L544-L549
156,617
groovy/groovy-core
src/main/groovy/lang/MetaProperty.java
MetaProperty.getGetterName
public static String getGetterName(String propertyName, Class type) { String prefix = type == boolean.class || type == Boolean.class ? "is" : "get"; return prefix + MetaClassHelper.capitalize(propertyName); }
java
public static String getGetterName(String propertyName, Class type) { String prefix = type == boolean.class || type == Boolean.class ? "is" : "get"; return prefix + MetaClassHelper.capitalize(propertyName); }
[ "public", "static", "String", "getGetterName", "(", "String", "propertyName", ",", "Class", "type", ")", "{", "String", "prefix", "=", "type", "==", "boolean", ".", "class", "||", "type", "==", "Boolean", ".", "class", "?", "\"is\"", ":", "\"get\"", ";", "return", "prefix", "+", "MetaClassHelper", ".", "capitalize", "(", "propertyName", ")", ";", "}" ]
Gets the name for the getter for this property @return The name of the property. The name is "get"+ the capitalized propertyName or, in the case of boolean values, "is" + the capitalized propertyName
[ "Gets", "the", "name", "for", "the", "getter", "for", "this", "property" ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/groovy/lang/MetaProperty.java#L90-L93
156,618
groovy/groovy-core
src/main/groovy/lang/ProxyMetaClass.java
ProxyMetaClass.getInstance
public static ProxyMetaClass getInstance(Class theClass) throws IntrospectionException { MetaClassRegistry metaRegistry = GroovySystem.getMetaClassRegistry(); MetaClass meta = metaRegistry.getMetaClass(theClass); return new ProxyMetaClass(metaRegistry, theClass, meta); }
java
public static ProxyMetaClass getInstance(Class theClass) throws IntrospectionException { MetaClassRegistry metaRegistry = GroovySystem.getMetaClassRegistry(); MetaClass meta = metaRegistry.getMetaClass(theClass); return new ProxyMetaClass(metaRegistry, theClass, meta); }
[ "public", "static", "ProxyMetaClass", "getInstance", "(", "Class", "theClass", ")", "throws", "IntrospectionException", "{", "MetaClassRegistry", "metaRegistry", "=", "GroovySystem", ".", "getMetaClassRegistry", "(", ")", ";", "MetaClass", "meta", "=", "metaRegistry", ".", "getMetaClass", "(", "theClass", ")", ";", "return", "new", "ProxyMetaClass", "(", "metaRegistry", ",", "theClass", ",", "meta", ")", ";", "}" ]
convenience factory method for the most usual case.
[ "convenience", "factory", "method", "for", "the", "most", "usual", "case", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/groovy/lang/ProxyMetaClass.java#L47-L51
156,619
groovy/groovy-core
src/main/org/codehaus/groovy/control/ResolveVisitor.java
ResolveVisitor.correctClassClassChain
private Expression correctClassClassChain(PropertyExpression pe) { LinkedList<Expression> stack = new LinkedList<Expression>(); ClassExpression found = null; for (Expression it = pe; it != null; it = ((PropertyExpression) it).getObjectExpression()) { if (it instanceof ClassExpression) { found = (ClassExpression) it; break; } else if (!(it.getClass() == PropertyExpression.class)) { return pe; } stack.addFirst(it); } if (found == null) return pe; if (stack.isEmpty()) return pe; Object stackElement = stack.removeFirst(); if (!(stackElement.getClass() == PropertyExpression.class)) return pe; PropertyExpression classPropertyExpression = (PropertyExpression) stackElement; String propertyNamePart = classPropertyExpression.getPropertyAsString(); if (propertyNamePart == null || !propertyNamePart.equals("class")) return pe; found.setSourcePosition(classPropertyExpression); if (stack.isEmpty()) return found; stackElement = stack.removeFirst(); if (!(stackElement.getClass() == PropertyExpression.class)) return pe; PropertyExpression classPropertyExpressionContainer = (PropertyExpression) stackElement; classPropertyExpressionContainer.setObjectExpression(found); return pe; }
java
private Expression correctClassClassChain(PropertyExpression pe) { LinkedList<Expression> stack = new LinkedList<Expression>(); ClassExpression found = null; for (Expression it = pe; it != null; it = ((PropertyExpression) it).getObjectExpression()) { if (it instanceof ClassExpression) { found = (ClassExpression) it; break; } else if (!(it.getClass() == PropertyExpression.class)) { return pe; } stack.addFirst(it); } if (found == null) return pe; if (stack.isEmpty()) return pe; Object stackElement = stack.removeFirst(); if (!(stackElement.getClass() == PropertyExpression.class)) return pe; PropertyExpression classPropertyExpression = (PropertyExpression) stackElement; String propertyNamePart = classPropertyExpression.getPropertyAsString(); if (propertyNamePart == null || !propertyNamePart.equals("class")) return pe; found.setSourcePosition(classPropertyExpression); if (stack.isEmpty()) return found; stackElement = stack.removeFirst(); if (!(stackElement.getClass() == PropertyExpression.class)) return pe; PropertyExpression classPropertyExpressionContainer = (PropertyExpression) stackElement; classPropertyExpressionContainer.setObjectExpression(found); return pe; }
[ "private", "Expression", "correctClassClassChain", "(", "PropertyExpression", "pe", ")", "{", "LinkedList", "<", "Expression", ">", "stack", "=", "new", "LinkedList", "<", "Expression", ">", "(", ")", ";", "ClassExpression", "found", "=", "null", ";", "for", "(", "Expression", "it", "=", "pe", ";", "it", "!=", "null", ";", "it", "=", "(", "(", "PropertyExpression", ")", "it", ")", ".", "getObjectExpression", "(", ")", ")", "{", "if", "(", "it", "instanceof", "ClassExpression", ")", "{", "found", "=", "(", "ClassExpression", ")", "it", ";", "break", ";", "}", "else", "if", "(", "!", "(", "it", ".", "getClass", "(", ")", "==", "PropertyExpression", ".", "class", ")", ")", "{", "return", "pe", ";", "}", "stack", ".", "addFirst", "(", "it", ")", ";", "}", "if", "(", "found", "==", "null", ")", "return", "pe", ";", "if", "(", "stack", ".", "isEmpty", "(", ")", ")", "return", "pe", ";", "Object", "stackElement", "=", "stack", ".", "removeFirst", "(", ")", ";", "if", "(", "!", "(", "stackElement", ".", "getClass", "(", ")", "==", "PropertyExpression", ".", "class", ")", ")", "return", "pe", ";", "PropertyExpression", "classPropertyExpression", "=", "(", "PropertyExpression", ")", "stackElement", ";", "String", "propertyNamePart", "=", "classPropertyExpression", ".", "getPropertyAsString", "(", ")", ";", "if", "(", "propertyNamePart", "==", "null", "||", "!", "propertyNamePart", ".", "equals", "(", "\"class\"", ")", ")", "return", "pe", ";", "found", ".", "setSourcePosition", "(", "classPropertyExpression", ")", ";", "if", "(", "stack", ".", "isEmpty", "(", ")", ")", "return", "found", ";", "stackElement", "=", "stack", ".", "removeFirst", "(", ")", ";", "if", "(", "!", "(", "stackElement", ".", "getClass", "(", ")", "==", "PropertyExpression", ".", "class", ")", ")", "return", "pe", ";", "PropertyExpression", "classPropertyExpressionContainer", "=", "(", "PropertyExpression", ")", "stackElement", ";", "classPropertyExpressionContainer", ".", "setObjectExpression", "(", "found", ")", ";", "return", "pe", ";", "}" ]
and class as property
[ "and", "class", "as", "property" ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/control/ResolveVisitor.java#L781-L810
156,620
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/DefaultGroovyMethodsSupport.java
DefaultGroovyMethodsSupport.closeWithWarning
public static void closeWithWarning(Closeable c) { if (c != null) { try { c.close(); } catch (IOException e) { LOG.warning("Caught exception during close(): " + e); } } }
java
public static void closeWithWarning(Closeable c) { if (c != null) { try { c.close(); } catch (IOException e) { LOG.warning("Caught exception during close(): " + e); } } }
[ "public", "static", "void", "closeWithWarning", "(", "Closeable", "c", ")", "{", "if", "(", "c", "!=", "null", ")", "{", "try", "{", "c", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "warning", "(", "\"Caught exception during close(): \"", "+", "e", ")", ";", "}", "}", "}" ]
Close the Closeable. Logging a warning if any problems occur. @param c the thing to close
[ "Close", "the", "Closeable", ".", "Logging", "a", "warning", "if", "any", "problems", "occur", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethodsSupport.java#L88-L96
156,621
groovy/groovy-core
src/main/org/codehaus/groovy/util/ManagedConcurrentValueMap.java
ManagedConcurrentValueMap.get
public V get(K key) { ManagedReference<V> ref = internalMap.get(key); if (ref!=null) return ref.get(); return null; }
java
public V get(K key) { ManagedReference<V> ref = internalMap.get(key); if (ref!=null) return ref.get(); return null; }
[ "public", "V", "get", "(", "K", "key", ")", "{", "ManagedReference", "<", "V", ">", "ref", "=", "internalMap", ".", "get", "(", "key", ")", ";", "if", "(", "ref", "!=", "null", ")", "return", "ref", ".", "get", "(", ")", ";", "return", "null", ";", "}" ]
Returns the value stored for the given key at the point of call. @param key a non null key @return the value stored in the map for the given key
[ "Returns", "the", "value", "stored", "for", "the", "given", "key", "at", "the", "point", "of", "call", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/util/ManagedConcurrentValueMap.java#L55-L59
156,622
groovy/groovy-core
src/main/org/codehaus/groovy/util/ManagedConcurrentValueMap.java
ManagedConcurrentValueMap.put
public void put(final K key, V value) { ManagedReference<V> ref = new ManagedReference<V>(bundle, value) { @Override public void finalizeReference() { super.finalizeReference(); internalMap.remove(key, get()); } }; internalMap.put(key, ref); }
java
public void put(final K key, V value) { ManagedReference<V> ref = new ManagedReference<V>(bundle, value) { @Override public void finalizeReference() { super.finalizeReference(); internalMap.remove(key, get()); } }; internalMap.put(key, ref); }
[ "public", "void", "put", "(", "final", "K", "key", ",", "V", "value", ")", "{", "ManagedReference", "<", "V", ">", "ref", "=", "new", "ManagedReference", "<", "V", ">", "(", "bundle", ",", "value", ")", "{", "@", "Override", "public", "void", "finalizeReference", "(", ")", "{", "super", ".", "finalizeReference", "(", ")", ";", "internalMap", ".", "remove", "(", "key", ",", "get", "(", ")", ")", ";", "}", "}", ";", "internalMap", ".", "put", "(", "key", ",", "ref", ")", ";", "}" ]
Sets a new value for a given key. an older value is overwritten. @param key a non null key @param value the new value
[ "Sets", "a", "new", "value", "for", "a", "given", "key", ".", "an", "older", "value", "is", "overwritten", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/util/ManagedConcurrentValueMap.java#L66-L75
156,623
groovy/groovy-core
src/main/org/codehaus/groovy/control/SourceUnit.java
SourceUnit.getSample
public String getSample(int line, int column, Janitor janitor) { String sample = null; String text = source.getLine(line, janitor); if (text != null) { if (column > 0) { String marker = Utilities.repeatString(" ", column - 1) + "^"; if (column > 40) { int start = column - 30 - 1; int end = (column + 10 > text.length() ? text.length() : column + 10 - 1); sample = " " + text.substring(start, end) + Utilities.eol() + " " + marker.substring(start, marker.length()); } else { sample = " " + text + Utilities.eol() + " " + marker; } } else { sample = text; } } return sample; }
java
public String getSample(int line, int column, Janitor janitor) { String sample = null; String text = source.getLine(line, janitor); if (text != null) { if (column > 0) { String marker = Utilities.repeatString(" ", column - 1) + "^"; if (column > 40) { int start = column - 30 - 1; int end = (column + 10 > text.length() ? text.length() : column + 10 - 1); sample = " " + text.substring(start, end) + Utilities.eol() + " " + marker.substring(start, marker.length()); } else { sample = " " + text + Utilities.eol() + " " + marker; } } else { sample = text; } } return sample; }
[ "public", "String", "getSample", "(", "int", "line", ",", "int", "column", ",", "Janitor", "janitor", ")", "{", "String", "sample", "=", "null", ";", "String", "text", "=", "source", ".", "getLine", "(", "line", ",", "janitor", ")", ";", "if", "(", "text", "!=", "null", ")", "{", "if", "(", "column", ">", "0", ")", "{", "String", "marker", "=", "Utilities", ".", "repeatString", "(", "\" \"", ",", "column", "-", "1", ")", "+", "\"^\"", ";", "if", "(", "column", ">", "40", ")", "{", "int", "start", "=", "column", "-", "30", "-", "1", ";", "int", "end", "=", "(", "column", "+", "10", ">", "text", ".", "length", "(", ")", "?", "text", ".", "length", "(", ")", ":", "column", "+", "10", "-", "1", ")", ";", "sample", "=", "\" \"", "+", "text", ".", "substring", "(", "start", ",", "end", ")", "+", "Utilities", ".", "eol", "(", ")", "+", "\" \"", "+", "marker", ".", "substring", "(", "start", ",", "marker", ".", "length", "(", ")", ")", ";", "}", "else", "{", "sample", "=", "\" \"", "+", "text", "+", "Utilities", ".", "eol", "(", ")", "+", "\" \"", "+", "marker", ";", "}", "}", "else", "{", "sample", "=", "text", ";", "}", "}", "return", "sample", ";", "}" ]
Returns a sampling of the source at the specified line and column, of null if it is unavailable.
[ "Returns", "a", "sampling", "of", "the", "source", "at", "the", "specified", "line", "and", "column", "of", "null", "if", "it", "is", "unavailable", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/control/SourceUnit.java#L313-L335
156,624
groovy/groovy-core
subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java
Sql.withInstance
public static void withInstance(String url, Closure c) throws SQLException { Sql sql = null; try { sql = newInstance(url); c.call(sql); } finally { if (sql != null) sql.close(); } }
java
public static void withInstance(String url, Closure c) throws SQLException { Sql sql = null; try { sql = newInstance(url); c.call(sql); } finally { if (sql != null) sql.close(); } }
[ "public", "static", "void", "withInstance", "(", "String", "url", ",", "Closure", "c", ")", "throws", "SQLException", "{", "Sql", "sql", "=", "null", ";", "try", "{", "sql", "=", "newInstance", "(", "url", ")", ";", "c", ".", "call", "(", "sql", ")", ";", "}", "finally", "{", "if", "(", "sql", "!=", "null", ")", "sql", ".", "close", "(", ")", ";", "}", "}" ]
Invokes a closure passing it a new Sql instance created from the given JDBC connection URL. The created connection will be closed if required. @param url a database url of the form <code>jdbc:<em>subprotocol</em>:<em>subname</em></code> @param c the Closure to call @see #newInstance(String) @throws SQLException if a database access error occurs
[ "Invokes", "a", "closure", "passing", "it", "a", "new", "Sql", "instance", "created", "from", "the", "given", "JDBC", "connection", "URL", ".", "The", "created", "connection", "will", "be", "closed", "if", "required", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java#L293-L301
156,625
groovy/groovy-core
subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java
Sql.withTransaction
public synchronized void withTransaction(Closure closure) throws SQLException { boolean savedCacheConnection = cacheConnection; cacheConnection = true; Connection connection = null; boolean savedAutoCommit = true; try { connection = createConnection(); savedAutoCommit = connection.getAutoCommit(); connection.setAutoCommit(false); callClosurePossiblyWithConnection(closure, connection); connection.commit(); } catch (SQLException e) { handleError(connection, e); throw e; } catch (RuntimeException e) { handleError(connection, e); throw e; } catch (Error e) { handleError(connection, e); throw e; } catch (Exception e) { handleError(connection, e); throw new SQLException("Unexpected exception during transaction", e); } finally { if (connection != null) { try { connection.setAutoCommit(savedAutoCommit); } catch (SQLException e) { LOG.finest("Caught exception resetting auto commit: " + e.getMessage() + " - continuing"); } } cacheConnection = false; closeResources(connection, null); cacheConnection = savedCacheConnection; if (dataSource != null && !cacheConnection) { useConnection = null; } } }
java
public synchronized void withTransaction(Closure closure) throws SQLException { boolean savedCacheConnection = cacheConnection; cacheConnection = true; Connection connection = null; boolean savedAutoCommit = true; try { connection = createConnection(); savedAutoCommit = connection.getAutoCommit(); connection.setAutoCommit(false); callClosurePossiblyWithConnection(closure, connection); connection.commit(); } catch (SQLException e) { handleError(connection, e); throw e; } catch (RuntimeException e) { handleError(connection, e); throw e; } catch (Error e) { handleError(connection, e); throw e; } catch (Exception e) { handleError(connection, e); throw new SQLException("Unexpected exception during transaction", e); } finally { if (connection != null) { try { connection.setAutoCommit(savedAutoCommit); } catch (SQLException e) { LOG.finest("Caught exception resetting auto commit: " + e.getMessage() + " - continuing"); } } cacheConnection = false; closeResources(connection, null); cacheConnection = savedCacheConnection; if (dataSource != null && !cacheConnection) { useConnection = null; } } }
[ "public", "synchronized", "void", "withTransaction", "(", "Closure", "closure", ")", "throws", "SQLException", "{", "boolean", "savedCacheConnection", "=", "cacheConnection", ";", "cacheConnection", "=", "true", ";", "Connection", "connection", "=", "null", ";", "boolean", "savedAutoCommit", "=", "true", ";", "try", "{", "connection", "=", "createConnection", "(", ")", ";", "savedAutoCommit", "=", "connection", ".", "getAutoCommit", "(", ")", ";", "connection", ".", "setAutoCommit", "(", "false", ")", ";", "callClosurePossiblyWithConnection", "(", "closure", ",", "connection", ")", ";", "connection", ".", "commit", "(", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "handleError", "(", "connection", ",", "e", ")", ";", "throw", "e", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "handleError", "(", "connection", ",", "e", ")", ";", "throw", "e", ";", "}", "catch", "(", "Error", "e", ")", "{", "handleError", "(", "connection", ",", "e", ")", ";", "throw", "e", ";", "}", "catch", "(", "Exception", "e", ")", "{", "handleError", "(", "connection", ",", "e", ")", ";", "throw", "new", "SQLException", "(", "\"Unexpected exception during transaction\"", ",", "e", ")", ";", "}", "finally", "{", "if", "(", "connection", "!=", "null", ")", "{", "try", "{", "connection", ".", "setAutoCommit", "(", "savedAutoCommit", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "LOG", ".", "finest", "(", "\"Caught exception resetting auto commit: \"", "+", "e", ".", "getMessage", "(", ")", "+", "\" - continuing\"", ")", ";", "}", "}", "cacheConnection", "=", "false", ";", "closeResources", "(", "connection", ",", "null", ")", ";", "cacheConnection", "=", "savedCacheConnection", ";", "if", "(", "dataSource", "!=", "null", "&&", "!", "cacheConnection", ")", "{", "useConnection", "=", "null", ";", "}", "}", "}" ]
Performs the closure within a transaction using a cached connection. If the closure takes a single argument, it will be called with the connection, otherwise it will be called with no arguments. @param closure the given closure @throws SQLException if a database error occurs
[ "Performs", "the", "closure", "within", "a", "transaction", "using", "a", "cached", "connection", ".", "If", "the", "closure", "takes", "a", "single", "argument", "it", "will", "be", "called", "with", "the", "connection", "otherwise", "it", "will", "be", "called", "with", "no", "arguments", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java#L3515-L3554
156,626
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/ReflectionMethodInvoker.java
ReflectionMethodInvoker.invoke
public static Object invoke(Object object, String methodName, Object[] parameters) { try { Class[] classTypes = new Class[parameters.length]; for (int i = 0; i < classTypes.length; i++) { classTypes[i] = parameters[i].getClass(); } Method method = object.getClass().getMethod(methodName, classTypes); return method.invoke(object, parameters); } catch (Throwable t) { return InvokerHelper.invokeMethod(object, methodName, parameters); } }
java
public static Object invoke(Object object, String methodName, Object[] parameters) { try { Class[] classTypes = new Class[parameters.length]; for (int i = 0; i < classTypes.length; i++) { classTypes[i] = parameters[i].getClass(); } Method method = object.getClass().getMethod(methodName, classTypes); return method.invoke(object, parameters); } catch (Throwable t) { return InvokerHelper.invokeMethod(object, methodName, parameters); } }
[ "public", "static", "Object", "invoke", "(", "Object", "object", ",", "String", "methodName", ",", "Object", "[", "]", "parameters", ")", "{", "try", "{", "Class", "[", "]", "classTypes", "=", "new", "Class", "[", "parameters", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "classTypes", ".", "length", ";", "i", "++", ")", "{", "classTypes", "[", "i", "]", "=", "parameters", "[", "i", "]", ".", "getClass", "(", ")", ";", "}", "Method", "method", "=", "object", ".", "getClass", "(", ")", ".", "getMethod", "(", "methodName", ",", "classTypes", ")", ";", "return", "method", ".", "invoke", "(", "object", ",", "parameters", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "return", "InvokerHelper", ".", "invokeMethod", "(", "object", ",", "methodName", ",", "parameters", ")", ";", "}", "}" ]
Invoke a method through reflection. Falls through to using the Invoker to call the method in case the reflection call fails.. @param object the object on which to invoke a method @param methodName the name of the method to invoke @param parameters the parameters of the method call @return the result of the method call
[ "Invoke", "a", "method", "through", "reflection", ".", "Falls", "through", "to", "using", "the", "Invoker", "to", "call", "the", "method", "in", "case", "the", "reflection", "call", "fails", ".." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/ReflectionMethodInvoker.java#L43-L54
156,627
groovy/groovy-core
src/main/org/codehaus/groovy/tools/StringHelper.java
StringHelper.tokenizeUnquoted
public static String[] tokenizeUnquoted(String s) { List tokens = new LinkedList(); int first = 0; while (first < s.length()) { first = skipWhitespace(s, first); int last = scanToken(s, first); if (first < last) { tokens.add(s.substring(first, last)); } first = last; } return (String[])tokens.toArray(new String[tokens.size()]); }
java
public static String[] tokenizeUnquoted(String s) { List tokens = new LinkedList(); int first = 0; while (first < s.length()) { first = skipWhitespace(s, first); int last = scanToken(s, first); if (first < last) { tokens.add(s.substring(first, last)); } first = last; } return (String[])tokens.toArray(new String[tokens.size()]); }
[ "public", "static", "String", "[", "]", "tokenizeUnquoted", "(", "String", "s", ")", "{", "List", "tokens", "=", "new", "LinkedList", "(", ")", ";", "int", "first", "=", "0", ";", "while", "(", "first", "<", "s", ".", "length", "(", ")", ")", "{", "first", "=", "skipWhitespace", "(", "s", ",", "first", ")", ";", "int", "last", "=", "scanToken", "(", "s", ",", "first", ")", ";", "if", "(", "first", "<", "last", ")", "{", "tokens", ".", "add", "(", "s", ".", "substring", "(", "first", ",", "last", ")", ")", ";", "}", "first", "=", "last", ";", "}", "return", "(", "String", "[", "]", ")", "tokens", ".", "toArray", "(", "new", "String", "[", "tokens", ".", "size", "(", ")", "]", ")", ";", "}" ]
This method tokenizes a string by space characters, but ignores spaces in quoted parts,that are parts in '' or "". The method does allows the usage of "" in '' and '' in "". The space character between tokens is not returned. @param s the string to tokenize @return the tokens
[ "This", "method", "tokenizes", "a", "string", "by", "space", "characters", "but", "ignores", "spaces", "in", "quoted", "parts", "that", "are", "parts", "in", "or", ".", "The", "method", "does", "allows", "the", "usage", "of", "in", "and", "in", ".", "The", "space", "character", "between", "tokens", "is", "not", "returned", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/tools/StringHelper.java#L38-L50
156,628
groovy/groovy-core
src/main/org/codehaus/groovy/transform/sc/StaticCompilationVisitor.java
StaticCompilationVisitor.addPrivateFieldsAccessors
@SuppressWarnings("unchecked") private void addPrivateFieldsAccessors(ClassNode node) { Set<ASTNode> accessedFields = (Set<ASTNode>) node.getNodeMetaData(StaticTypesMarker.PV_FIELDS_ACCESS); if (accessedFields==null) return; Map<String, MethodNode> privateConstantAccessors = (Map<String, MethodNode>) node.getNodeMetaData(PRIVATE_FIELDS_ACCESSORS); if (privateConstantAccessors!=null) { // already added return; } int acc = -1; privateConstantAccessors = new HashMap<String, MethodNode>(); final int access = Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC; for (FieldNode fieldNode : node.getFields()) { if (accessedFields.contains(fieldNode)) { acc++; Parameter param = new Parameter(node.getPlainNodeReference(), "$that"); Expression receiver = fieldNode.isStatic()?new ClassExpression(node):new VariableExpression(param); Statement stmt = new ExpressionStatement(new PropertyExpression( receiver, fieldNode.getName() )); MethodNode accessor = node.addMethod("pfaccess$"+acc, access, fieldNode.getOriginType(), new Parameter[]{param}, ClassNode.EMPTY_ARRAY, stmt); privateConstantAccessors.put(fieldNode.getName(), accessor); } } node.setNodeMetaData(PRIVATE_FIELDS_ACCESSORS, privateConstantAccessors); }
java
@SuppressWarnings("unchecked") private void addPrivateFieldsAccessors(ClassNode node) { Set<ASTNode> accessedFields = (Set<ASTNode>) node.getNodeMetaData(StaticTypesMarker.PV_FIELDS_ACCESS); if (accessedFields==null) return; Map<String, MethodNode> privateConstantAccessors = (Map<String, MethodNode>) node.getNodeMetaData(PRIVATE_FIELDS_ACCESSORS); if (privateConstantAccessors!=null) { // already added return; } int acc = -1; privateConstantAccessors = new HashMap<String, MethodNode>(); final int access = Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC; for (FieldNode fieldNode : node.getFields()) { if (accessedFields.contains(fieldNode)) { acc++; Parameter param = new Parameter(node.getPlainNodeReference(), "$that"); Expression receiver = fieldNode.isStatic()?new ClassExpression(node):new VariableExpression(param); Statement stmt = new ExpressionStatement(new PropertyExpression( receiver, fieldNode.getName() )); MethodNode accessor = node.addMethod("pfaccess$"+acc, access, fieldNode.getOriginType(), new Parameter[]{param}, ClassNode.EMPTY_ARRAY, stmt); privateConstantAccessors.put(fieldNode.getName(), accessor); } } node.setNodeMetaData(PRIVATE_FIELDS_ACCESSORS, privateConstantAccessors); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "void", "addPrivateFieldsAccessors", "(", "ClassNode", "node", ")", "{", "Set", "<", "ASTNode", ">", "accessedFields", "=", "(", "Set", "<", "ASTNode", ">", ")", "node", ".", "getNodeMetaData", "(", "StaticTypesMarker", ".", "PV_FIELDS_ACCESS", ")", ";", "if", "(", "accessedFields", "==", "null", ")", "return", ";", "Map", "<", "String", ",", "MethodNode", ">", "privateConstantAccessors", "=", "(", "Map", "<", "String", ",", "MethodNode", ">", ")", "node", ".", "getNodeMetaData", "(", "PRIVATE_FIELDS_ACCESSORS", ")", ";", "if", "(", "privateConstantAccessors", "!=", "null", ")", "{", "// already added", "return", ";", "}", "int", "acc", "=", "-", "1", ";", "privateConstantAccessors", "=", "new", "HashMap", "<", "String", ",", "MethodNode", ">", "(", ")", ";", "final", "int", "access", "=", "Opcodes", ".", "ACC_STATIC", "|", "Opcodes", ".", "ACC_PUBLIC", "|", "Opcodes", ".", "ACC_SYNTHETIC", ";", "for", "(", "FieldNode", "fieldNode", ":", "node", ".", "getFields", "(", ")", ")", "{", "if", "(", "accessedFields", ".", "contains", "(", "fieldNode", ")", ")", "{", "acc", "++", ";", "Parameter", "param", "=", "new", "Parameter", "(", "node", ".", "getPlainNodeReference", "(", ")", ",", "\"$that\"", ")", ";", "Expression", "receiver", "=", "fieldNode", ".", "isStatic", "(", ")", "?", "new", "ClassExpression", "(", "node", ")", ":", "new", "VariableExpression", "(", "param", ")", ";", "Statement", "stmt", "=", "new", "ExpressionStatement", "(", "new", "PropertyExpression", "(", "receiver", ",", "fieldNode", ".", "getName", "(", ")", ")", ")", ";", "MethodNode", "accessor", "=", "node", ".", "addMethod", "(", "\"pfaccess$\"", "+", "acc", ",", "access", ",", "fieldNode", ".", "getOriginType", "(", ")", ",", "new", "Parameter", "[", "]", "{", "param", "}", ",", "ClassNode", ".", "EMPTY_ARRAY", ",", "stmt", ")", ";", "privateConstantAccessors", ".", "put", "(", "fieldNode", ".", "getName", "(", ")", ",", "accessor", ")", ";", "}", "}", "node", ".", "setNodeMetaData", "(", "PRIVATE_FIELDS_ACCESSORS", ",", "privateConstantAccessors", ")", ";", "}" ]
Adds special accessors for private constants so that inner classes can retrieve them.
[ "Adds", "special", "accessors", "for", "private", "constants", "so", "that", "inner", "classes", "can", "retrieve", "them", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/transform/sc/StaticCompilationVisitor.java#L170-L197
156,629
groovy/groovy-core
src/main/org/codehaus/groovy/control/CompilerConfiguration.java
CompilerConfiguration.isPostJDK5
public static boolean isPostJDK5(String bytecodeVersion) { return JDK5.equals(bytecodeVersion) || JDK6.equals(bytecodeVersion) || JDK7.equals(bytecodeVersion) || JDK8.equals(bytecodeVersion); }
java
public static boolean isPostJDK5(String bytecodeVersion) { return JDK5.equals(bytecodeVersion) || JDK6.equals(bytecodeVersion) || JDK7.equals(bytecodeVersion) || JDK8.equals(bytecodeVersion); }
[ "public", "static", "boolean", "isPostJDK5", "(", "String", "bytecodeVersion", ")", "{", "return", "JDK5", ".", "equals", "(", "bytecodeVersion", ")", "||", "JDK6", ".", "equals", "(", "bytecodeVersion", ")", "||", "JDK7", ".", "equals", "(", "bytecodeVersion", ")", "||", "JDK8", ".", "equals", "(", "bytecodeVersion", ")", ";", "}" ]
Checks if the specified bytecode version string represents a JDK 1.5+ compatible bytecode version. @param bytecodeVersion the bytecode version string (1.4, 1.5, 1.6, 1.7 or 1.8) @return true if the bytecode version is JDK 1.5+
[ "Checks", "if", "the", "specified", "bytecode", "version", "string", "represents", "a", "JDK", "1", ".", "5", "+", "compatible", "bytecode", "version", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/control/CompilerConfiguration.java#L363-L368
156,630
groovy/groovy-core
src/main/org/codehaus/groovy/control/CompilerConfiguration.java
CompilerConfiguration.setTargetDirectory
public void setTargetDirectory(String directory) { if (directory != null && directory.length() > 0) { this.targetDirectory = new File(directory); } else { this.targetDirectory = null; } }
java
public void setTargetDirectory(String directory) { if (directory != null && directory.length() > 0) { this.targetDirectory = new File(directory); } else { this.targetDirectory = null; } }
[ "public", "void", "setTargetDirectory", "(", "String", "directory", ")", "{", "if", "(", "directory", "!=", "null", "&&", "directory", ".", "length", "(", ")", ">", "0", ")", "{", "this", ".", "targetDirectory", "=", "new", "File", "(", "directory", ")", ";", "}", "else", "{", "this", ".", "targetDirectory", "=", "null", ";", "}", "}" ]
Sets the target directory.
[ "Sets", "the", "target", "directory", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/control/CompilerConfiguration.java#L566-L572
156,631
groovy/groovy-core
src/main/org/codehaus/groovy/tools/RootLoader.java
RootLoader.loadClass
protected synchronized Class loadClass(final String name, boolean resolve) throws ClassNotFoundException { Class c = this.findLoadedClass(name); if (c != null) return c; c = (Class) customClasses.get(name); if (c != null) return c; try { c = oldFindClass(name); } catch (ClassNotFoundException cnfe) { // IGNORE } if (c == null) c = super.loadClass(name, resolve); if (resolve) resolveClass(c); return c; }
java
protected synchronized Class loadClass(final String name, boolean resolve) throws ClassNotFoundException { Class c = this.findLoadedClass(name); if (c != null) return c; c = (Class) customClasses.get(name); if (c != null) return c; try { c = oldFindClass(name); } catch (ClassNotFoundException cnfe) { // IGNORE } if (c == null) c = super.loadClass(name, resolve); if (resolve) resolveClass(c); return c; }
[ "protected", "synchronized", "Class", "loadClass", "(", "final", "String", "name", ",", "boolean", "resolve", ")", "throws", "ClassNotFoundException", "{", "Class", "c", "=", "this", ".", "findLoadedClass", "(", "name", ")", ";", "if", "(", "c", "!=", "null", ")", "return", "c", ";", "c", "=", "(", "Class", ")", "customClasses", ".", "get", "(", "name", ")", ";", "if", "(", "c", "!=", "null", ")", "return", "c", ";", "try", "{", "c", "=", "oldFindClass", "(", "name", ")", ";", "}", "catch", "(", "ClassNotFoundException", "cnfe", ")", "{", "// IGNORE", "}", "if", "(", "c", "==", "null", ")", "c", "=", "super", ".", "loadClass", "(", "name", ",", "resolve", ")", ";", "if", "(", "resolve", ")", "resolveClass", "(", "c", ")", ";", "return", "c", ";", "}" ]
loads a class using the name of the class
[ "loads", "a", "class", "using", "the", "name", "of", "the", "class" ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/tools/RootLoader.java#L140-L156
156,632
groovy/groovy-core
src/main/groovy/util/NodeList.java
NodeList.getAt
public NodeList getAt(String name) { NodeList answer = new NodeList(); for (Object child : this) { if (child instanceof Node) { Node childNode = (Node) child; Object temp = childNode.get(name); if (temp instanceof Collection) { answer.addAll((Collection) temp); } else { answer.add(temp); } } } return answer; }
java
public NodeList getAt(String name) { NodeList answer = new NodeList(); for (Object child : this) { if (child instanceof Node) { Node childNode = (Node) child; Object temp = childNode.get(name); if (temp instanceof Collection) { answer.addAll((Collection) temp); } else { answer.add(temp); } } } return answer; }
[ "public", "NodeList", "getAt", "(", "String", "name", ")", "{", "NodeList", "answer", "=", "new", "NodeList", "(", ")", ";", "for", "(", "Object", "child", ":", "this", ")", "{", "if", "(", "child", "instanceof", "Node", ")", "{", "Node", "childNode", "=", "(", "Node", ")", "child", ";", "Object", "temp", "=", "childNode", ".", "get", "(", "name", ")", ";", "if", "(", "temp", "instanceof", "Collection", ")", "{", "answer", ".", "addAll", "(", "(", "Collection", ")", "temp", ")", ";", "}", "else", "{", "answer", ".", "add", "(", "temp", ")", ";", "}", "}", "}", "return", "answer", ";", "}" ]
Provides lookup of elements by non-namespaced name. @param name the name or shortcut key for nodes of interest @return the nodes of interest which match name
[ "Provides", "lookup", "of", "elements", "by", "non", "-", "namespaced", "name", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/groovy/util/NodeList.java#L118-L132
156,633
groovy/groovy-core
src/main/groovy/util/NodeList.java
NodeList.text
public String text() { String previousText = null; StringBuilder buffer = null; for (Object child : this) { String text = null; if (child instanceof String) { text = (String) child; } else if (child instanceof Node) { text = ((Node) child).text(); } if (text != null) { if (previousText == null) { previousText = text; } else { if (buffer == null) { buffer = new StringBuilder(); buffer.append(previousText); } buffer.append(text); } } } if (buffer != null) { return buffer.toString(); } if (previousText != null) { return previousText; } return ""; }
java
public String text() { String previousText = null; StringBuilder buffer = null; for (Object child : this) { String text = null; if (child instanceof String) { text = (String) child; } else if (child instanceof Node) { text = ((Node) child).text(); } if (text != null) { if (previousText == null) { previousText = text; } else { if (buffer == null) { buffer = new StringBuilder(); buffer.append(previousText); } buffer.append(text); } } } if (buffer != null) { return buffer.toString(); } if (previousText != null) { return previousText; } return ""; }
[ "public", "String", "text", "(", ")", "{", "String", "previousText", "=", "null", ";", "StringBuilder", "buffer", "=", "null", ";", "for", "(", "Object", "child", ":", "this", ")", "{", "String", "text", "=", "null", ";", "if", "(", "child", "instanceof", "String", ")", "{", "text", "=", "(", "String", ")", "child", ";", "}", "else", "if", "(", "child", "instanceof", "Node", ")", "{", "text", "=", "(", "(", "Node", ")", "child", ")", ".", "text", "(", ")", ";", "}", "if", "(", "text", "!=", "null", ")", "{", "if", "(", "previousText", "==", "null", ")", "{", "previousText", "=", "text", ";", "}", "else", "{", "if", "(", "buffer", "==", "null", ")", "{", "buffer", "=", "new", "StringBuilder", "(", ")", ";", "buffer", ".", "append", "(", "previousText", ")", ";", "}", "buffer", ".", "append", "(", "text", ")", ";", "}", "}", "}", "if", "(", "buffer", "!=", "null", ")", "{", "return", "buffer", ".", "toString", "(", ")", ";", "}", "if", "(", "previousText", "!=", "null", ")", "{", "return", "previousText", ";", "}", "return", "\"\"", ";", "}" ]
Returns the text value of all of the elements in the collection. @return the text value of all the elements in the collection or null
[ "Returns", "the", "text", "value", "of", "all", "of", "the", "elements", "in", "the", "collection", "." ]
01309f9d4be34ddf93c4a9943b5a97843bff6181
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/groovy/util/NodeList.java#L157-L186
156,634
joestelmach/natty
src/main/java/com/joestelmach/natty/Parser.java
Parser.isAllNumeric
private boolean isAllNumeric(TokenStream stream) { List<Token> tokens = ((NattyTokenSource) stream.getTokenSource()).getTokens(); for(Token token:tokens) { try { Integer.parseInt(token.getText()); } catch(NumberFormatException e) { return false; } } return true; }
java
private boolean isAllNumeric(TokenStream stream) { List<Token> tokens = ((NattyTokenSource) stream.getTokenSource()).getTokens(); for(Token token:tokens) { try { Integer.parseInt(token.getText()); } catch(NumberFormatException e) { return false; } } return true; }
[ "private", "boolean", "isAllNumeric", "(", "TokenStream", "stream", ")", "{", "List", "<", "Token", ">", "tokens", "=", "(", "(", "NattyTokenSource", ")", "stream", ".", "getTokenSource", "(", ")", ")", ".", "getTokens", "(", ")", ";", "for", "(", "Token", "token", ":", "tokens", ")", "{", "try", "{", "Integer", ".", "parseInt", "(", "token", ".", "getText", "(", ")", ")", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Determines if a token stream contains only numeric tokens @param stream @return true if all tokens in the given stream can be parsed as an integer
[ "Determines", "if", "a", "token", "stream", "contains", "only", "numeric", "tokens" ]
74389feb4c9372e51cd51eb0800a0177fec3e5a0
https://github.com/joestelmach/natty/blob/74389feb4c9372e51cd51eb0800a0177fec3e5a0/src/main/java/com/joestelmach/natty/Parser.java#L166-L176
156,635
joestelmach/natty
src/main/java/com/joestelmach/natty/Parser.java
Parser.collectTokenStreams
private List<TokenStream> collectTokenStreams(TokenStream stream) { // walk through the token stream and build a collection // of sub token streams that represent possible date locations List<Token> currentGroup = null; List<List<Token>> groups = new ArrayList<List<Token>>(); Token currentToken; int currentTokenType; StringBuilder tokenString = new StringBuilder(); while((currentToken = stream.getTokenSource().nextToken()).getType() != DateLexer.EOF) { currentTokenType = currentToken.getType(); tokenString.append(DateParser.tokenNames[currentTokenType]).append(" "); // we're currently NOT collecting for a possible date group if(currentGroup == null) { // skip over white space and known tokens that cannot be the start of a date if(currentTokenType != DateLexer.WHITE_SPACE && DateParser.FOLLOW_empty_in_parse186.member(currentTokenType)) { currentGroup = new ArrayList<Token>(); currentGroup.add(currentToken); } } // we're currently collecting else { // preserve white space if(currentTokenType == DateLexer.WHITE_SPACE) { currentGroup.add(currentToken); } else { // if this is an unknown token, we'll close out the current group if(currentTokenType == DateLexer.UNKNOWN) { addGroup(currentGroup, groups); currentGroup = null; } // otherwise, the token is known and we're currently collecting for // a group, so we'll add it to the current group else { currentGroup.add(currentToken); } } } } if(currentGroup != null) { addGroup(currentGroup, groups); } _logger.info("STREAM: " + tokenString.toString()); List<TokenStream> streams = new ArrayList<TokenStream>(); for(List<Token> group:groups) { if(!group.isEmpty()) { StringBuilder builder = new StringBuilder(); builder.append("GROUP: "); for (Token token : group) { builder.append(DateParser.tokenNames[token.getType()]).append(" "); } _logger.info(builder.toString()); streams.add(new CommonTokenStream(new NattyTokenSource(group))); } } return streams; }
java
private List<TokenStream> collectTokenStreams(TokenStream stream) { // walk through the token stream and build a collection // of sub token streams that represent possible date locations List<Token> currentGroup = null; List<List<Token>> groups = new ArrayList<List<Token>>(); Token currentToken; int currentTokenType; StringBuilder tokenString = new StringBuilder(); while((currentToken = stream.getTokenSource().nextToken()).getType() != DateLexer.EOF) { currentTokenType = currentToken.getType(); tokenString.append(DateParser.tokenNames[currentTokenType]).append(" "); // we're currently NOT collecting for a possible date group if(currentGroup == null) { // skip over white space and known tokens that cannot be the start of a date if(currentTokenType != DateLexer.WHITE_SPACE && DateParser.FOLLOW_empty_in_parse186.member(currentTokenType)) { currentGroup = new ArrayList<Token>(); currentGroup.add(currentToken); } } // we're currently collecting else { // preserve white space if(currentTokenType == DateLexer.WHITE_SPACE) { currentGroup.add(currentToken); } else { // if this is an unknown token, we'll close out the current group if(currentTokenType == DateLexer.UNKNOWN) { addGroup(currentGroup, groups); currentGroup = null; } // otherwise, the token is known and we're currently collecting for // a group, so we'll add it to the current group else { currentGroup.add(currentToken); } } } } if(currentGroup != null) { addGroup(currentGroup, groups); } _logger.info("STREAM: " + tokenString.toString()); List<TokenStream> streams = new ArrayList<TokenStream>(); for(List<Token> group:groups) { if(!group.isEmpty()) { StringBuilder builder = new StringBuilder(); builder.append("GROUP: "); for (Token token : group) { builder.append(DateParser.tokenNames[token.getType()]).append(" "); } _logger.info(builder.toString()); streams.add(new CommonTokenStream(new NattyTokenSource(group))); } } return streams; }
[ "private", "List", "<", "TokenStream", ">", "collectTokenStreams", "(", "TokenStream", "stream", ")", "{", "// walk through the token stream and build a collection ", "// of sub token streams that represent possible date locations", "List", "<", "Token", ">", "currentGroup", "=", "null", ";", "List", "<", "List", "<", "Token", ">", ">", "groups", "=", "new", "ArrayList", "<", "List", "<", "Token", ">", ">", "(", ")", ";", "Token", "currentToken", ";", "int", "currentTokenType", ";", "StringBuilder", "tokenString", "=", "new", "StringBuilder", "(", ")", ";", "while", "(", "(", "currentToken", "=", "stream", ".", "getTokenSource", "(", ")", ".", "nextToken", "(", ")", ")", ".", "getType", "(", ")", "!=", "DateLexer", ".", "EOF", ")", "{", "currentTokenType", "=", "currentToken", ".", "getType", "(", ")", ";", "tokenString", ".", "append", "(", "DateParser", ".", "tokenNames", "[", "currentTokenType", "]", ")", ".", "append", "(", "\" \"", ")", ";", "// we're currently NOT collecting for a possible date group", "if", "(", "currentGroup", "==", "null", ")", "{", "// skip over white space and known tokens that cannot be the start of a date", "if", "(", "currentTokenType", "!=", "DateLexer", ".", "WHITE_SPACE", "&&", "DateParser", ".", "FOLLOW_empty_in_parse186", ".", "member", "(", "currentTokenType", ")", ")", "{", "currentGroup", "=", "new", "ArrayList", "<", "Token", ">", "(", ")", ";", "currentGroup", ".", "add", "(", "currentToken", ")", ";", "}", "}", "// we're currently collecting", "else", "{", "// preserve white space", "if", "(", "currentTokenType", "==", "DateLexer", ".", "WHITE_SPACE", ")", "{", "currentGroup", ".", "add", "(", "currentToken", ")", ";", "}", "else", "{", "// if this is an unknown token, we'll close out the current group", "if", "(", "currentTokenType", "==", "DateLexer", ".", "UNKNOWN", ")", "{", "addGroup", "(", "currentGroup", ",", "groups", ")", ";", "currentGroup", "=", "null", ";", "}", "// otherwise, the token is known and we're currently collecting for", "// a group, so we'll add it to the current group", "else", "{", "currentGroup", ".", "add", "(", "currentToken", ")", ";", "}", "}", "}", "}", "if", "(", "currentGroup", "!=", "null", ")", "{", "addGroup", "(", "currentGroup", ",", "groups", ")", ";", "}", "_logger", ".", "info", "(", "\"STREAM: \"", "+", "tokenString", ".", "toString", "(", ")", ")", ";", "List", "<", "TokenStream", ">", "streams", "=", "new", "ArrayList", "<", "TokenStream", ">", "(", ")", ";", "for", "(", "List", "<", "Token", ">", "group", ":", "groups", ")", "{", "if", "(", "!", "group", ".", "isEmpty", "(", ")", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "builder", ".", "append", "(", "\"GROUP: \"", ")", ";", "for", "(", "Token", "token", ":", "group", ")", "{", "builder", ".", "append", "(", "DateParser", ".", "tokenNames", "[", "token", ".", "getType", "(", ")", "]", ")", ".", "append", "(", "\" \"", ")", ";", "}", "_logger", ".", "info", "(", "builder", ".", "toString", "(", ")", ")", ";", "streams", ".", "add", "(", "new", "CommonTokenStream", "(", "new", "NattyTokenSource", "(", "group", ")", ")", ")", ";", "}", "}", "return", "streams", ";", "}" ]
Scans the given token global token stream for a list of sub-token streams representing those portions of the global stream that may contain date time information @param stream @return
[ "Scans", "the", "given", "token", "global", "token", "stream", "for", "a", "list", "of", "sub", "-", "token", "streams", "representing", "those", "portions", "of", "the", "global", "stream", "that", "may", "contain", "date", "time", "information" ]
74389feb4c9372e51cd51eb0800a0177fec3e5a0
https://github.com/joestelmach/natty/blob/74389feb4c9372e51cd51eb0800a0177fec3e5a0/src/main/java/com/joestelmach/natty/Parser.java#L260-L326
156,636
joestelmach/natty
src/main/java/com/joestelmach/natty/Parser.java
Parser.addGroup
private void addGroup(List<Token> group, List<List<Token>> groups) { if(group.isEmpty()) return; // remove trailing tokens that should be ignored while(!group.isEmpty() && IGNORED_TRAILING_TOKENS.contains( group.get(group.size() - 1).getType())) { group.remove(group.size() - 1); } // if the group still has some tokens left, we'll add it to our list of groups if(!group.isEmpty()) { groups.add(group); } }
java
private void addGroup(List<Token> group, List<List<Token>> groups) { if(group.isEmpty()) return; // remove trailing tokens that should be ignored while(!group.isEmpty() && IGNORED_TRAILING_TOKENS.contains( group.get(group.size() - 1).getType())) { group.remove(group.size() - 1); } // if the group still has some tokens left, we'll add it to our list of groups if(!group.isEmpty()) { groups.add(group); } }
[ "private", "void", "addGroup", "(", "List", "<", "Token", ">", "group", ",", "List", "<", "List", "<", "Token", ">", ">", "groups", ")", "{", "if", "(", "group", ".", "isEmpty", "(", ")", ")", "return", ";", "// remove trailing tokens that should be ignored", "while", "(", "!", "group", ".", "isEmpty", "(", ")", "&&", "IGNORED_TRAILING_TOKENS", ".", "contains", "(", "group", ".", "get", "(", "group", ".", "size", "(", ")", "-", "1", ")", ".", "getType", "(", ")", ")", ")", "{", "group", ".", "remove", "(", "group", ".", "size", "(", ")", "-", "1", ")", ";", "}", "// if the group still has some tokens left, we'll add it to our list of groups", "if", "(", "!", "group", ".", "isEmpty", "(", ")", ")", "{", "groups", ".", "add", "(", "group", ")", ";", "}", "}" ]
Cleans up the given group and adds it to the list of groups if still valid @param group @param groups
[ "Cleans", "up", "the", "given", "group", "and", "adds", "it", "to", "the", "list", "of", "groups", "if", "still", "valid" ]
74389feb4c9372e51cd51eb0800a0177fec3e5a0
https://github.com/joestelmach/natty/blob/74389feb4c9372e51cd51eb0800a0177fec3e5a0/src/main/java/com/joestelmach/natty/Parser.java#L333-L347
156,637
joestelmach/natty
src/main/java/com/joestelmach/natty/WalkerState.java
WalkerState.seekToDayOfWeek
public void seekToDayOfWeek(String direction, String seekType, String seekAmount, String dayOfWeek) { int dayOfWeekInt = Integer.parseInt(dayOfWeek); int seekAmountInt = Integer.parseInt(seekAmount); assert(direction.equals(DIR_LEFT) || direction.equals(DIR_RIGHT)); assert(seekType.equals(SEEK_BY_DAY) || seekType.equals(SEEK_BY_WEEK)); assert(dayOfWeekInt >= 1 && dayOfWeekInt <= 7); markDateInvocation(); int sign = direction.equals(DIR_RIGHT) ? 1 : -1; if(seekType.equals(SEEK_BY_WEEK)) { // set our calendar to this weeks requested day of the week, // then add or subtract the week(s) _calendar.set(Calendar.DAY_OF_WEEK, dayOfWeekInt); _calendar.add(Calendar.DAY_OF_YEAR, seekAmountInt * 7 * sign); } else if(seekType.equals(SEEK_BY_DAY)) { // find the closest day do { _calendar.add(Calendar.DAY_OF_YEAR, sign); } while(_calendar.get(Calendar.DAY_OF_WEEK) != dayOfWeekInt); // now add/subtract any additional days if(seekAmountInt > 0) { _calendar.add(Calendar.WEEK_OF_YEAR, (seekAmountInt - 1) * sign); } } }
java
public void seekToDayOfWeek(String direction, String seekType, String seekAmount, String dayOfWeek) { int dayOfWeekInt = Integer.parseInt(dayOfWeek); int seekAmountInt = Integer.parseInt(seekAmount); assert(direction.equals(DIR_LEFT) || direction.equals(DIR_RIGHT)); assert(seekType.equals(SEEK_BY_DAY) || seekType.equals(SEEK_BY_WEEK)); assert(dayOfWeekInt >= 1 && dayOfWeekInt <= 7); markDateInvocation(); int sign = direction.equals(DIR_RIGHT) ? 1 : -1; if(seekType.equals(SEEK_BY_WEEK)) { // set our calendar to this weeks requested day of the week, // then add or subtract the week(s) _calendar.set(Calendar.DAY_OF_WEEK, dayOfWeekInt); _calendar.add(Calendar.DAY_OF_YEAR, seekAmountInt * 7 * sign); } else if(seekType.equals(SEEK_BY_DAY)) { // find the closest day do { _calendar.add(Calendar.DAY_OF_YEAR, sign); } while(_calendar.get(Calendar.DAY_OF_WEEK) != dayOfWeekInt); // now add/subtract any additional days if(seekAmountInt > 0) { _calendar.add(Calendar.WEEK_OF_YEAR, (seekAmountInt - 1) * sign); } } }
[ "public", "void", "seekToDayOfWeek", "(", "String", "direction", ",", "String", "seekType", ",", "String", "seekAmount", ",", "String", "dayOfWeek", ")", "{", "int", "dayOfWeekInt", "=", "Integer", ".", "parseInt", "(", "dayOfWeek", ")", ";", "int", "seekAmountInt", "=", "Integer", ".", "parseInt", "(", "seekAmount", ")", ";", "assert", "(", "direction", ".", "equals", "(", "DIR_LEFT", ")", "||", "direction", ".", "equals", "(", "DIR_RIGHT", ")", ")", ";", "assert", "(", "seekType", ".", "equals", "(", "SEEK_BY_DAY", ")", "||", "seekType", ".", "equals", "(", "SEEK_BY_WEEK", ")", ")", ";", "assert", "(", "dayOfWeekInt", ">=", "1", "&&", "dayOfWeekInt", "<=", "7", ")", ";", "markDateInvocation", "(", ")", ";", "int", "sign", "=", "direction", ".", "equals", "(", "DIR_RIGHT", ")", "?", "1", ":", "-", "1", ";", "if", "(", "seekType", ".", "equals", "(", "SEEK_BY_WEEK", ")", ")", "{", "// set our calendar to this weeks requested day of the week,", "// then add or subtract the week(s)", "_calendar", ".", "set", "(", "Calendar", ".", "DAY_OF_WEEK", ",", "dayOfWeekInt", ")", ";", "_calendar", ".", "add", "(", "Calendar", ".", "DAY_OF_YEAR", ",", "seekAmountInt", "*", "7", "*", "sign", ")", ";", "}", "else", "if", "(", "seekType", ".", "equals", "(", "SEEK_BY_DAY", ")", ")", "{", "// find the closest day", "do", "{", "_calendar", ".", "add", "(", "Calendar", ".", "DAY_OF_YEAR", ",", "sign", ")", ";", "}", "while", "(", "_calendar", ".", "get", "(", "Calendar", ".", "DAY_OF_WEEK", ")", "!=", "dayOfWeekInt", ")", ";", "// now add/subtract any additional days", "if", "(", "seekAmountInt", ">", "0", ")", "{", "_calendar", ".", "add", "(", "Calendar", ".", "WEEK_OF_YEAR", ",", "(", "seekAmountInt", "-", "1", ")", "*", "sign", ")", ";", "}", "}", "}" ]
seeks to a specified day of the week in the past or future. @param direction the direction to seek: two possibilities '<' go backward '>' go forward @param seekType the type of seek to perform (by_day or by_week) by_day means we seek to the very next occurrence of the given day by_week means we seek to the first occurrence of the given day week in the next (or previous,) week (or multiple of next or previous week depending on the seek amount.) @param seekAmount the amount to seek. Must be guaranteed to parse as an integer @param dayOfWeek the day of the week to seek to, represented as an integer from 1 to 7 (1 being Sunday, 7 being Saturday.) Must be guaranteed to parse as an Integer
[ "seeks", "to", "a", "specified", "day", "of", "the", "week", "in", "the", "past", "or", "future", "." ]
74389feb4c9372e51cd51eb0800a0177fec3e5a0
https://github.com/joestelmach/natty/blob/74389feb4c9372e51cd51eb0800a0177fec3e5a0/src/main/java/com/joestelmach/natty/WalkerState.java#L80-L108
156,638
joestelmach/natty
src/main/java/com/joestelmach/natty/WalkerState.java
WalkerState.seekToDayOfMonth
public void seekToDayOfMonth(String dayOfMonth) { int dayOfMonthInt = Integer.parseInt(dayOfMonth); assert(dayOfMonthInt >= 1 && dayOfMonthInt <= 31); markDateInvocation(); dayOfMonthInt = Math.min(dayOfMonthInt, _calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); _calendar.set(Calendar.DAY_OF_MONTH, dayOfMonthInt); }
java
public void seekToDayOfMonth(String dayOfMonth) { int dayOfMonthInt = Integer.parseInt(dayOfMonth); assert(dayOfMonthInt >= 1 && dayOfMonthInt <= 31); markDateInvocation(); dayOfMonthInt = Math.min(dayOfMonthInt, _calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); _calendar.set(Calendar.DAY_OF_MONTH, dayOfMonthInt); }
[ "public", "void", "seekToDayOfMonth", "(", "String", "dayOfMonth", ")", "{", "int", "dayOfMonthInt", "=", "Integer", ".", "parseInt", "(", "dayOfMonth", ")", ";", "assert", "(", "dayOfMonthInt", ">=", "1", "&&", "dayOfMonthInt", "<=", "31", ")", ";", "markDateInvocation", "(", ")", ";", "dayOfMonthInt", "=", "Math", ".", "min", "(", "dayOfMonthInt", ",", "_calendar", ".", "getActualMaximum", "(", "Calendar", ".", "DAY_OF_MONTH", ")", ")", ";", "_calendar", ".", "set", "(", "Calendar", ".", "DAY_OF_MONTH", ",", "dayOfMonthInt", ")", ";", "}" ]
Seeks to the given day within the current month @param dayOfMonth the day of the month to seek to, represented as an integer from 1 to 31. Must be guaranteed to parse as an Integer. If this day is beyond the last day of the current month, the actual last day of the month will be used.
[ "Seeks", "to", "the", "given", "day", "within", "the", "current", "month" ]
74389feb4c9372e51cd51eb0800a0177fec3e5a0
https://github.com/joestelmach/natty/blob/74389feb4c9372e51cd51eb0800a0177fec3e5a0/src/main/java/com/joestelmach/natty/WalkerState.java#L117-L125
156,639
joestelmach/natty
src/main/java/com/joestelmach/natty/WalkerState.java
WalkerState.seekToDayOfYear
public void seekToDayOfYear(String dayOfYear) { int dayOfYearInt = Integer.parseInt(dayOfYear); assert(dayOfYearInt >= 1 && dayOfYearInt <= 366); markDateInvocation(); dayOfYearInt = Math.min(dayOfYearInt, _calendar.getActualMaximum(Calendar.DAY_OF_YEAR)); _calendar.set(Calendar.DAY_OF_YEAR, dayOfYearInt); }
java
public void seekToDayOfYear(String dayOfYear) { int dayOfYearInt = Integer.parseInt(dayOfYear); assert(dayOfYearInt >= 1 && dayOfYearInt <= 366); markDateInvocation(); dayOfYearInt = Math.min(dayOfYearInt, _calendar.getActualMaximum(Calendar.DAY_OF_YEAR)); _calendar.set(Calendar.DAY_OF_YEAR, dayOfYearInt); }
[ "public", "void", "seekToDayOfYear", "(", "String", "dayOfYear", ")", "{", "int", "dayOfYearInt", "=", "Integer", ".", "parseInt", "(", "dayOfYear", ")", ";", "assert", "(", "dayOfYearInt", ">=", "1", "&&", "dayOfYearInt", "<=", "366", ")", ";", "markDateInvocation", "(", ")", ";", "dayOfYearInt", "=", "Math", ".", "min", "(", "dayOfYearInt", ",", "_calendar", ".", "getActualMaximum", "(", "Calendar", ".", "DAY_OF_YEAR", ")", ")", ";", "_calendar", ".", "set", "(", "Calendar", ".", "DAY_OF_YEAR", ",", "dayOfYearInt", ")", ";", "}" ]
Seeks to the given day within the current year @param dayOfYear the day of the year to seek to, represented as an integer from 1 to 366. Must be guaranteed to parse as an Integer. If this day is beyond the last day of the current year, the actual last day of the year will be used.
[ "Seeks", "to", "the", "given", "day", "within", "the", "current", "year" ]
74389feb4c9372e51cd51eb0800a0177fec3e5a0
https://github.com/joestelmach/natty/blob/74389feb4c9372e51cd51eb0800a0177fec3e5a0/src/main/java/com/joestelmach/natty/WalkerState.java#L134-L142
156,640
joestelmach/natty
src/main/java/com/joestelmach/natty/WalkerState.java
WalkerState.seekToMonth
public void seekToMonth(String direction, String seekAmount, String month) { int seekAmountInt = Integer.parseInt(seekAmount); int monthInt = Integer.parseInt(month); assert(direction.equals(DIR_LEFT) || direction.equals(DIR_RIGHT)); assert(monthInt >= 1 && monthInt <= 12); markDateInvocation(); // set the day to the first of month. This step is necessary because if we seek to the // current day of a month whose number of days is less than the current day, we will // pushed into the next month. _calendar.set(Calendar.DAY_OF_MONTH, 1); // seek to the appropriate year if(seekAmountInt > 0) { int currentMonth = _calendar.get(Calendar.MONTH) + 1; int sign = direction.equals(DIR_RIGHT) ? 1 : -1; int numYearsToShift = seekAmountInt + (currentMonth == monthInt ? 0 : (currentMonth < monthInt ? sign > 0 ? -1 : 0 : sign > 0 ? 0 : -1)); _calendar.add(Calendar.YEAR, (numYearsToShift * sign)); } // now set the month _calendar.set(Calendar.MONTH, monthInt - 1); }
java
public void seekToMonth(String direction, String seekAmount, String month) { int seekAmountInt = Integer.parseInt(seekAmount); int monthInt = Integer.parseInt(month); assert(direction.equals(DIR_LEFT) || direction.equals(DIR_RIGHT)); assert(monthInt >= 1 && monthInt <= 12); markDateInvocation(); // set the day to the first of month. This step is necessary because if we seek to the // current day of a month whose number of days is less than the current day, we will // pushed into the next month. _calendar.set(Calendar.DAY_OF_MONTH, 1); // seek to the appropriate year if(seekAmountInt > 0) { int currentMonth = _calendar.get(Calendar.MONTH) + 1; int sign = direction.equals(DIR_RIGHT) ? 1 : -1; int numYearsToShift = seekAmountInt + (currentMonth == monthInt ? 0 : (currentMonth < monthInt ? sign > 0 ? -1 : 0 : sign > 0 ? 0 : -1)); _calendar.add(Calendar.YEAR, (numYearsToShift * sign)); } // now set the month _calendar.set(Calendar.MONTH, monthInt - 1); }
[ "public", "void", "seekToMonth", "(", "String", "direction", ",", "String", "seekAmount", ",", "String", "month", ")", "{", "int", "seekAmountInt", "=", "Integer", ".", "parseInt", "(", "seekAmount", ")", ";", "int", "monthInt", "=", "Integer", ".", "parseInt", "(", "month", ")", ";", "assert", "(", "direction", ".", "equals", "(", "DIR_LEFT", ")", "||", "direction", ".", "equals", "(", "DIR_RIGHT", ")", ")", ";", "assert", "(", "monthInt", ">=", "1", "&&", "monthInt", "<=", "12", ")", ";", "markDateInvocation", "(", ")", ";", "// set the day to the first of month. This step is necessary because if we seek to the ", "// current day of a month whose number of days is less than the current day, we will ", "// pushed into the next month.", "_calendar", ".", "set", "(", "Calendar", ".", "DAY_OF_MONTH", ",", "1", ")", ";", "// seek to the appropriate year", "if", "(", "seekAmountInt", ">", "0", ")", "{", "int", "currentMonth", "=", "_calendar", ".", "get", "(", "Calendar", ".", "MONTH", ")", "+", "1", ";", "int", "sign", "=", "direction", ".", "equals", "(", "DIR_RIGHT", ")", "?", "1", ":", "-", "1", ";", "int", "numYearsToShift", "=", "seekAmountInt", "+", "(", "currentMonth", "==", "monthInt", "?", "0", ":", "(", "currentMonth", "<", "monthInt", "?", "sign", ">", "0", "?", "-", "1", ":", "0", ":", "sign", ">", "0", "?", "0", ":", "-", "1", ")", ")", ";", "_calendar", ".", "add", "(", "Calendar", ".", "YEAR", ",", "(", "numYearsToShift", "*", "sign", ")", ")", ";", "}", "// now set the month", "_calendar", ".", "set", "(", "Calendar", ".", "MONTH", ",", "monthInt", "-", "1", ")", ";", "}" ]
seeks to a particular month @param direction the direction to seek: two possibilities '<' go backward '>' go forward @param seekAmount the amount to seek. Must be guaranteed to parse as an integer @param month the month to seek to. Must be guaranteed to parse as an integer between 1 and 12
[ "seeks", "to", "a", "particular", "month" ]
74389feb4c9372e51cd51eb0800a0177fec3e5a0
https://github.com/joestelmach/natty/blob/74389feb4c9372e51cd51eb0800a0177fec3e5a0/src/main/java/com/joestelmach/natty/WalkerState.java#L169-L194
156,641
joestelmach/natty
src/main/java/com/joestelmach/natty/WalkerState.java
WalkerState.setExplicitTime
public void setExplicitTime(String hours, String minutes, String seconds, String amPm, String zoneString) { int hoursInt = Integer.parseInt(hours); int minutesInt = minutes != null ? Integer.parseInt(minutes) : 0; assert(amPm == null || amPm.equals(AM) || amPm.equals(PM)); assert(hoursInt >= 0); assert(minutesInt >= 0 && minutesInt < 60); markTimeInvocation(amPm); // reset milliseconds to 0 _calendar.set(Calendar.MILLISECOND, 0); // if no explicit zone is given, we use our own TimeZone zone = null; if(zoneString != null) { if(zoneString.startsWith(PLUS) || zoneString.startsWith(MINUS)) { zoneString = GMT + zoneString; } zone = TimeZone.getTimeZone(zoneString); } _calendar.setTimeZone(zone != null ? zone : _defaultTimeZone); _calendar.set(Calendar.HOUR_OF_DAY, hoursInt); // hours greater than 12 are in 24-hour time if(hoursInt <= 12) { int amPmInt = amPm == null ? (hoursInt >= 12 ? Calendar.PM : Calendar.AM) : amPm.equals(PM) ? Calendar.PM : Calendar.AM; _calendar.set(Calendar.AM_PM, amPmInt); // calendar is whacky at 12 o'clock (must use 0) if(hoursInt == 12) hoursInt = 0; _calendar.set(Calendar.HOUR, hoursInt); } if(seconds != null) { int secondsInt = Integer.parseInt(seconds); assert(secondsInt >= 0 && secondsInt < 60); _calendar.set(Calendar.SECOND, secondsInt); } else { _calendar.set(Calendar.SECOND, 0); } _calendar.set(Calendar.MINUTE, minutesInt); }
java
public void setExplicitTime(String hours, String minutes, String seconds, String amPm, String zoneString) { int hoursInt = Integer.parseInt(hours); int minutesInt = minutes != null ? Integer.parseInt(minutes) : 0; assert(amPm == null || amPm.equals(AM) || amPm.equals(PM)); assert(hoursInt >= 0); assert(minutesInt >= 0 && minutesInt < 60); markTimeInvocation(amPm); // reset milliseconds to 0 _calendar.set(Calendar.MILLISECOND, 0); // if no explicit zone is given, we use our own TimeZone zone = null; if(zoneString != null) { if(zoneString.startsWith(PLUS) || zoneString.startsWith(MINUS)) { zoneString = GMT + zoneString; } zone = TimeZone.getTimeZone(zoneString); } _calendar.setTimeZone(zone != null ? zone : _defaultTimeZone); _calendar.set(Calendar.HOUR_OF_DAY, hoursInt); // hours greater than 12 are in 24-hour time if(hoursInt <= 12) { int amPmInt = amPm == null ? (hoursInt >= 12 ? Calendar.PM : Calendar.AM) : amPm.equals(PM) ? Calendar.PM : Calendar.AM; _calendar.set(Calendar.AM_PM, amPmInt); // calendar is whacky at 12 o'clock (must use 0) if(hoursInt == 12) hoursInt = 0; _calendar.set(Calendar.HOUR, hoursInt); } if(seconds != null) { int secondsInt = Integer.parseInt(seconds); assert(secondsInt >= 0 && secondsInt < 60); _calendar.set(Calendar.SECOND, secondsInt); } else { _calendar.set(Calendar.SECOND, 0); } _calendar.set(Calendar.MINUTE, minutesInt); }
[ "public", "void", "setExplicitTime", "(", "String", "hours", ",", "String", "minutes", ",", "String", "seconds", ",", "String", "amPm", ",", "String", "zoneString", ")", "{", "int", "hoursInt", "=", "Integer", ".", "parseInt", "(", "hours", ")", ";", "int", "minutesInt", "=", "minutes", "!=", "null", "?", "Integer", ".", "parseInt", "(", "minutes", ")", ":", "0", ";", "assert", "(", "amPm", "==", "null", "||", "amPm", ".", "equals", "(", "AM", ")", "||", "amPm", ".", "equals", "(", "PM", ")", ")", ";", "assert", "(", "hoursInt", ">=", "0", ")", ";", "assert", "(", "minutesInt", ">=", "0", "&&", "minutesInt", "<", "60", ")", ";", "markTimeInvocation", "(", "amPm", ")", ";", "// reset milliseconds to 0", "_calendar", ".", "set", "(", "Calendar", ".", "MILLISECOND", ",", "0", ")", ";", "// if no explicit zone is given, we use our own", "TimeZone", "zone", "=", "null", ";", "if", "(", "zoneString", "!=", "null", ")", "{", "if", "(", "zoneString", ".", "startsWith", "(", "PLUS", ")", "||", "zoneString", ".", "startsWith", "(", "MINUS", ")", ")", "{", "zoneString", "=", "GMT", "+", "zoneString", ";", "}", "zone", "=", "TimeZone", ".", "getTimeZone", "(", "zoneString", ")", ";", "}", "_calendar", ".", "setTimeZone", "(", "zone", "!=", "null", "?", "zone", ":", "_defaultTimeZone", ")", ";", "_calendar", ".", "set", "(", "Calendar", ".", "HOUR_OF_DAY", ",", "hoursInt", ")", ";", "// hours greater than 12 are in 24-hour time", "if", "(", "hoursInt", "<=", "12", ")", "{", "int", "amPmInt", "=", "amPm", "==", "null", "?", "(", "hoursInt", ">=", "12", "?", "Calendar", ".", "PM", ":", "Calendar", ".", "AM", ")", ":", "amPm", ".", "equals", "(", "PM", ")", "?", "Calendar", ".", "PM", ":", "Calendar", ".", "AM", ";", "_calendar", ".", "set", "(", "Calendar", ".", "AM_PM", ",", "amPmInt", ")", ";", "// calendar is whacky at 12 o'clock (must use 0)", "if", "(", "hoursInt", "==", "12", ")", "hoursInt", "=", "0", ";", "_calendar", ".", "set", "(", "Calendar", ".", "HOUR", ",", "hoursInt", ")", ";", "}", "if", "(", "seconds", "!=", "null", ")", "{", "int", "secondsInt", "=", "Integer", ".", "parseInt", "(", "seconds", ")", ";", "assert", "(", "secondsInt", ">=", "0", "&&", "secondsInt", "<", "60", ")", ";", "_calendar", ".", "set", "(", "Calendar", ".", "SECOND", ",", "secondsInt", ")", ";", "}", "else", "{", "_calendar", ".", "set", "(", "Calendar", ".", "SECOND", ",", "0", ")", ";", "}", "_calendar", ".", "set", "(", "Calendar", ".", "MINUTE", ",", "minutesInt", ")", ";", "}" ]
Sets the the time of day @param hours the hours to set. Must be guaranteed to parse as an integer between 0 and 23 @param minutes the minutes to set. Must be guaranteed to parse as an integer between 0 and 59 @param seconds the optional seconds to set. Must be guaranteed to parse as an integer between 0 and 59 @param amPm the meridian indicator to use. Must be either 'am' or 'pm' @param zoneString the time zone to use in one of two formats: - zoneinfo format (America/New_York, America/Los_Angeles, etc) - GMT offset (+05:00, -0500, +5, etc)
[ "Sets", "the", "the", "time", "of", "day" ]
74389feb4c9372e51cd51eb0800a0177fec3e5a0
https://github.com/joestelmach/natty/blob/74389feb4c9372e51cd51eb0800a0177fec3e5a0/src/main/java/com/joestelmach/natty/WalkerState.java#L334-L380
156,642
joestelmach/natty
src/main/java/com/joestelmach/natty/WalkerState.java
WalkerState.seekToHoliday
public void seekToHoliday(String holidayString, String direction, String seekAmount) { Holiday holiday = Holiday.valueOf(holidayString); assert(holiday != null); seekToIcsEvent(HOLIDAY_ICS_FILE, holiday.getSummary(), direction, seekAmount); }
java
public void seekToHoliday(String holidayString, String direction, String seekAmount) { Holiday holiday = Holiday.valueOf(holidayString); assert(holiday != null); seekToIcsEvent(HOLIDAY_ICS_FILE, holiday.getSummary(), direction, seekAmount); }
[ "public", "void", "seekToHoliday", "(", "String", "holidayString", ",", "String", "direction", ",", "String", "seekAmount", ")", "{", "Holiday", "holiday", "=", "Holiday", ".", "valueOf", "(", "holidayString", ")", ";", "assert", "(", "holiday", "!=", "null", ")", ";", "seekToIcsEvent", "(", "HOLIDAY_ICS_FILE", ",", "holiday", ".", "getSummary", "(", ")", ",", "direction", ",", "seekAmount", ")", ";", "}" ]
Seeks forward or backwards to a particular holiday based on the current date @param holidayString The holiday to seek to @param direction The direction to seek @param seekAmount The number of years to seek
[ "Seeks", "forward", "or", "backwards", "to", "a", "particular", "holiday", "based", "on", "the", "current", "date" ]
74389feb4c9372e51cd51eb0800a0177fec3e5a0
https://github.com/joestelmach/natty/blob/74389feb4c9372e51cd51eb0800a0177fec3e5a0/src/main/java/com/joestelmach/natty/WalkerState.java#L389-L394
156,643
joestelmach/natty
src/main/java/com/joestelmach/natty/WalkerState.java
WalkerState.seekToHolidayYear
public void seekToHolidayYear(String holidayString, String yearString) { Holiday holiday = Holiday.valueOf(holidayString); assert(holiday != null); seekToIcsEventYear(HOLIDAY_ICS_FILE, yearString, holiday.getSummary()); }
java
public void seekToHolidayYear(String holidayString, String yearString) { Holiday holiday = Holiday.valueOf(holidayString); assert(holiday != null); seekToIcsEventYear(HOLIDAY_ICS_FILE, yearString, holiday.getSummary()); }
[ "public", "void", "seekToHolidayYear", "(", "String", "holidayString", ",", "String", "yearString", ")", "{", "Holiday", "holiday", "=", "Holiday", ".", "valueOf", "(", "holidayString", ")", ";", "assert", "(", "holiday", "!=", "null", ")", ";", "seekToIcsEventYear", "(", "HOLIDAY_ICS_FILE", ",", "yearString", ",", "holiday", ".", "getSummary", "(", ")", ")", ";", "}" ]
Seeks to the given holiday within the given year @param holidayString @param yearString
[ "Seeks", "to", "the", "given", "holiday", "within", "the", "given", "year" ]
74389feb4c9372e51cd51eb0800a0177fec3e5a0
https://github.com/joestelmach/natty/blob/74389feb4c9372e51cd51eb0800a0177fec3e5a0/src/main/java/com/joestelmach/natty/WalkerState.java#L402-L407
156,644
joestelmach/natty
src/main/java/com/joestelmach/natty/WalkerState.java
WalkerState.seekToSeason
public void seekToSeason(String seasonString, String direction, String seekAmount) { Season season = Season.valueOf(seasonString); assert(season!= null); seekToIcsEvent(SEASON_ICS_FILE, season.getSummary(), direction, seekAmount); }
java
public void seekToSeason(String seasonString, String direction, String seekAmount) { Season season = Season.valueOf(seasonString); assert(season!= null); seekToIcsEvent(SEASON_ICS_FILE, season.getSummary(), direction, seekAmount); }
[ "public", "void", "seekToSeason", "(", "String", "seasonString", ",", "String", "direction", ",", "String", "seekAmount", ")", "{", "Season", "season", "=", "Season", ".", "valueOf", "(", "seasonString", ")", ";", "assert", "(", "season", "!=", "null", ")", ";", "seekToIcsEvent", "(", "SEASON_ICS_FILE", ",", "season", ".", "getSummary", "(", ")", ",", "direction", ",", "seekAmount", ")", ";", "}" ]
Seeks forward or backwards to a particular season based on the current date @param seasonString The season to seek to @param direction The direction to seek @param seekAmount The number of years to seek
[ "Seeks", "forward", "or", "backwards", "to", "a", "particular", "season", "based", "on", "the", "current", "date" ]
74389feb4c9372e51cd51eb0800a0177fec3e5a0
https://github.com/joestelmach/natty/blob/74389feb4c9372e51cd51eb0800a0177fec3e5a0/src/main/java/com/joestelmach/natty/WalkerState.java#L416-L421
156,645
joestelmach/natty
src/main/java/com/joestelmach/natty/WalkerState.java
WalkerState.seekToSeasonYear
public void seekToSeasonYear(String seasonString, String yearString) { Season season = Season.valueOf(seasonString); assert(season != null); seekToIcsEventYear(SEASON_ICS_FILE, yearString, season.getSummary()); }
java
public void seekToSeasonYear(String seasonString, String yearString) { Season season = Season.valueOf(seasonString); assert(season != null); seekToIcsEventYear(SEASON_ICS_FILE, yearString, season.getSummary()); }
[ "public", "void", "seekToSeasonYear", "(", "String", "seasonString", ",", "String", "yearString", ")", "{", "Season", "season", "=", "Season", ".", "valueOf", "(", "seasonString", ")", ";", "assert", "(", "season", "!=", "null", ")", ";", "seekToIcsEventYear", "(", "SEASON_ICS_FILE", ",", "yearString", ",", "season", ".", "getSummary", "(", ")", ")", ";", "}" ]
Seeks to the given season within the given year @param seasonString @param yearString
[ "Seeks", "to", "the", "given", "season", "within", "the", "given", "year" ]
74389feb4c9372e51cd51eb0800a0177fec3e5a0
https://github.com/joestelmach/natty/blob/74389feb4c9372e51cd51eb0800a0177fec3e5a0/src/main/java/com/joestelmach/natty/WalkerState.java#L429-L434
156,646
joestelmach/natty
src/main/java/com/joestelmach/natty/WalkerState.java
WalkerState.resetCalendar
private void resetCalendar() { _calendar = getCalendar(); if (_defaultTimeZone != null) { _calendar.setTimeZone(_defaultTimeZone); } _currentYear = _calendar.get(Calendar.YEAR); }
java
private void resetCalendar() { _calendar = getCalendar(); if (_defaultTimeZone != null) { _calendar.setTimeZone(_defaultTimeZone); } _currentYear = _calendar.get(Calendar.YEAR); }
[ "private", "void", "resetCalendar", "(", ")", "{", "_calendar", "=", "getCalendar", "(", ")", ";", "if", "(", "_defaultTimeZone", "!=", "null", ")", "{", "_calendar", ".", "setTimeZone", "(", "_defaultTimeZone", ")", ";", "}", "_currentYear", "=", "_calendar", ".", "get", "(", "Calendar", ".", "YEAR", ")", ";", "}" ]
Resets the calendar
[ "Resets", "the", "calendar" ]
74389feb4c9372e51cd51eb0800a0177fec3e5a0
https://github.com/joestelmach/natty/blob/74389feb4c9372e51cd51eb0800a0177fec3e5a0/src/main/java/com/joestelmach/natty/WalkerState.java#L543-L549
156,647
joestelmach/natty
src/main/java/com/joestelmach/natty/WalkerState.java
WalkerState.seasonalDateFromIcs
private Date seasonalDateFromIcs(String icsFileName, String eventSummary, int year) { Map<Integer, Date> dates = getDatesFromIcs(icsFileName, eventSummary, year, year); return dates.get(year - (eventSummary.equals(Holiday.NEW_YEARS_EVE.getSummary()) ? 1 : 0)); }
java
private Date seasonalDateFromIcs(String icsFileName, String eventSummary, int year) { Map<Integer, Date> dates = getDatesFromIcs(icsFileName, eventSummary, year, year); return dates.get(year - (eventSummary.equals(Holiday.NEW_YEARS_EVE.getSummary()) ? 1 : 0)); }
[ "private", "Date", "seasonalDateFromIcs", "(", "String", "icsFileName", ",", "String", "eventSummary", ",", "int", "year", ")", "{", "Map", "<", "Integer", ",", "Date", ">", "dates", "=", "getDatesFromIcs", "(", "icsFileName", ",", "eventSummary", ",", "year", ",", "year", ")", ";", "return", "dates", ".", "get", "(", "year", "-", "(", "eventSummary", ".", "equals", "(", "Holiday", ".", "NEW_YEARS_EVE", ".", "getSummary", "(", ")", ")", "?", "1", ":", "0", ")", ")", ";", "}" ]
Finds and returns the date for the given event summary and year within the given ics file, or null if not present.
[ "Finds", "and", "returns", "the", "date", "for", "the", "given", "event", "summary", "and", "year", "within", "the", "given", "ics", "file", "or", "null", "if", "not", "present", "." ]
74389feb4c9372e51cd51eb0800a0177fec3e5a0
https://github.com/joestelmach/natty/blob/74389feb4c9372e51cd51eb0800a0177fec3e5a0/src/main/java/com/joestelmach/natty/WalkerState.java#L619-L622
156,648
joestelmach/natty
src/main/java/com/joestelmach/natty/WalkerState.java
WalkerState.markDateInvocation
private void markDateInvocation() { _updatePreviousDates = !_dateGivenInGroup; _dateGivenInGroup = true; _dateGroup.setDateInferred(false); if(_firstDateInvocationInGroup) { // if a time has been given within the current date group, // we capture the current time before resetting the calendar if(_timeGivenInGroup) { int hours = _calendar.get(Calendar.HOUR_OF_DAY); int minutes = _calendar.get(Calendar.MINUTE); int seconds = _calendar.get(Calendar.SECOND); resetCalendar(); _calendar.set(Calendar.HOUR_OF_DAY, hours); _calendar.set(Calendar.MINUTE, minutes); _calendar.set(Calendar.SECOND, seconds); } else { resetCalendar(); } _firstDateInvocationInGroup = false; } }
java
private void markDateInvocation() { _updatePreviousDates = !_dateGivenInGroup; _dateGivenInGroup = true; _dateGroup.setDateInferred(false); if(_firstDateInvocationInGroup) { // if a time has been given within the current date group, // we capture the current time before resetting the calendar if(_timeGivenInGroup) { int hours = _calendar.get(Calendar.HOUR_OF_DAY); int minutes = _calendar.get(Calendar.MINUTE); int seconds = _calendar.get(Calendar.SECOND); resetCalendar(); _calendar.set(Calendar.HOUR_OF_DAY, hours); _calendar.set(Calendar.MINUTE, minutes); _calendar.set(Calendar.SECOND, seconds); } else { resetCalendar(); } _firstDateInvocationInGroup = false; } }
[ "private", "void", "markDateInvocation", "(", ")", "{", "_updatePreviousDates", "=", "!", "_dateGivenInGroup", ";", "_dateGivenInGroup", "=", "true", ";", "_dateGroup", ".", "setDateInferred", "(", "false", ")", ";", "if", "(", "_firstDateInvocationInGroup", ")", "{", "// if a time has been given within the current date group, ", "// we capture the current time before resetting the calendar", "if", "(", "_timeGivenInGroup", ")", "{", "int", "hours", "=", "_calendar", ".", "get", "(", "Calendar", ".", "HOUR_OF_DAY", ")", ";", "int", "minutes", "=", "_calendar", ".", "get", "(", "Calendar", ".", "MINUTE", ")", ";", "int", "seconds", "=", "_calendar", ".", "get", "(", "Calendar", ".", "SECOND", ")", ";", "resetCalendar", "(", ")", ";", "_calendar", ".", "set", "(", "Calendar", ".", "HOUR_OF_DAY", ",", "hours", ")", ";", "_calendar", ".", "set", "(", "Calendar", ".", "MINUTE", ",", "minutes", ")", ";", "_calendar", ".", "set", "(", "Calendar", ".", "SECOND", ",", "seconds", ")", ";", "}", "else", "{", "resetCalendar", "(", ")", ";", "}", "_firstDateInvocationInGroup", "=", "false", ";", "}", "}" ]
ensures that the first invocation of a date seeking rule is captured
[ "ensures", "that", "the", "first", "invocation", "of", "a", "date", "seeking", "rule", "is", "captured" ]
74389feb4c9372e51cd51eb0800a0177fec3e5a0
https://github.com/joestelmach/natty/blob/74389feb4c9372e51cd51eb0800a0177fec3e5a0/src/main/java/com/joestelmach/natty/WalkerState.java#L628-L651
156,649
sstrickx/yahoofinance-api
src/main/java/yahoofinance/histquotes/HistQuotesRequest.java
HistQuotesRequest.cleanHistCalendar
private Calendar cleanHistCalendar(Calendar cal) { cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR, 0); return cal; }
java
private Calendar cleanHistCalendar(Calendar cal) { cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR, 0); return cal; }
[ "private", "Calendar", "cleanHistCalendar", "(", "Calendar", "cal", ")", "{", "cal", ".", "set", "(", "Calendar", ".", "MILLISECOND", ",", "0", ")", ";", "cal", ".", "set", "(", "Calendar", ".", "SECOND", ",", "0", ")", ";", "cal", ".", "set", "(", "Calendar", ".", "MINUTE", ",", "0", ")", ";", "cal", ".", "set", "(", "Calendar", ".", "HOUR", ",", "0", ")", ";", "return", "cal", ";", "}" ]
Put everything smaller than days at 0 @param cal calendar to be cleaned
[ "Put", "everything", "smaller", "than", "days", "at", "0" ]
2766ba52fc5cccf9b4da5c06423d68059cf0a6e6
https://github.com/sstrickx/yahoofinance-api/blob/2766ba52fc5cccf9b4da5c06423d68059cf0a6e6/src/main/java/yahoofinance/histquotes/HistQuotesRequest.java#L79-L85
156,650
sstrickx/yahoofinance-api
src/main/java/yahoofinance/Utils.java
Utils.parseDividendDate
public static Calendar parseDividendDate(String date) { if (!Utils.isParseable(date)) { return null; } date = date.trim(); SimpleDateFormat format = new SimpleDateFormat(Utils.getDividendDateFormat(date), Locale.US); format.setTimeZone(TimeZone.getTimeZone(YahooFinance.TIMEZONE)); try { Calendar today = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE)); Calendar parsedDate = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE)); parsedDate.setTime(format.parse(date)); if (parsedDate.get(Calendar.YEAR) == 1970) { // Not really clear which year the dividend date is... making a reasonable guess. int monthDiff = parsedDate.get(Calendar.MONTH) - today.get(Calendar.MONTH); int year = today.get(Calendar.YEAR); if (monthDiff > 6) { year -= 1; } else if (monthDiff < -6) { year += 1; } parsedDate.set(Calendar.YEAR, year); } return parsedDate; } catch (ParseException ex) { log.warn("Failed to parse dividend date: " + date); log.debug("Failed to parse dividend date: " + date, ex); return null; } }
java
public static Calendar parseDividendDate(String date) { if (!Utils.isParseable(date)) { return null; } date = date.trim(); SimpleDateFormat format = new SimpleDateFormat(Utils.getDividendDateFormat(date), Locale.US); format.setTimeZone(TimeZone.getTimeZone(YahooFinance.TIMEZONE)); try { Calendar today = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE)); Calendar parsedDate = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE)); parsedDate.setTime(format.parse(date)); if (parsedDate.get(Calendar.YEAR) == 1970) { // Not really clear which year the dividend date is... making a reasonable guess. int monthDiff = parsedDate.get(Calendar.MONTH) - today.get(Calendar.MONTH); int year = today.get(Calendar.YEAR); if (monthDiff > 6) { year -= 1; } else if (monthDiff < -6) { year += 1; } parsedDate.set(Calendar.YEAR, year); } return parsedDate; } catch (ParseException ex) { log.warn("Failed to parse dividend date: " + date); log.debug("Failed to parse dividend date: " + date, ex); return null; } }
[ "public", "static", "Calendar", "parseDividendDate", "(", "String", "date", ")", "{", "if", "(", "!", "Utils", ".", "isParseable", "(", "date", ")", ")", "{", "return", "null", ";", "}", "date", "=", "date", ".", "trim", "(", ")", ";", "SimpleDateFormat", "format", "=", "new", "SimpleDateFormat", "(", "Utils", ".", "getDividendDateFormat", "(", "date", ")", ",", "Locale", ".", "US", ")", ";", "format", ".", "setTimeZone", "(", "TimeZone", ".", "getTimeZone", "(", "YahooFinance", ".", "TIMEZONE", ")", ")", ";", "try", "{", "Calendar", "today", "=", "Calendar", ".", "getInstance", "(", "TimeZone", ".", "getTimeZone", "(", "YahooFinance", ".", "TIMEZONE", ")", ")", ";", "Calendar", "parsedDate", "=", "Calendar", ".", "getInstance", "(", "TimeZone", ".", "getTimeZone", "(", "YahooFinance", ".", "TIMEZONE", ")", ")", ";", "parsedDate", ".", "setTime", "(", "format", ".", "parse", "(", "date", ")", ")", ";", "if", "(", "parsedDate", ".", "get", "(", "Calendar", ".", "YEAR", ")", "==", "1970", ")", "{", "// Not really clear which year the dividend date is... making a reasonable guess.", "int", "monthDiff", "=", "parsedDate", ".", "get", "(", "Calendar", ".", "MONTH", ")", "-", "today", ".", "get", "(", "Calendar", ".", "MONTH", ")", ";", "int", "year", "=", "today", ".", "get", "(", "Calendar", ".", "YEAR", ")", ";", "if", "(", "monthDiff", ">", "6", ")", "{", "year", "-=", "1", ";", "}", "else", "if", "(", "monthDiff", "<", "-", "6", ")", "{", "year", "+=", "1", ";", "}", "parsedDate", ".", "set", "(", "Calendar", ".", "YEAR", ",", "year", ")", ";", "}", "return", "parsedDate", ";", "}", "catch", "(", "ParseException", "ex", ")", "{", "log", ".", "warn", "(", "\"Failed to parse dividend date: \"", "+", "date", ")", ";", "log", ".", "debug", "(", "\"Failed to parse dividend date: \"", "+", "date", ",", "ex", ")", ";", "return", "null", ";", "}", "}" ]
Used to parse the dividend dates. Returns null if the date cannot be parsed. @param date String received that represents the date @return Calendar object representing the parsed date
[ "Used", "to", "parse", "the", "dividend", "dates", ".", "Returns", "null", "if", "the", "date", "cannot", "be", "parsed", "." ]
2766ba52fc5cccf9b4da5c06423d68059cf0a6e6
https://github.com/sstrickx/yahoofinance-api/blob/2766ba52fc5cccf9b4da5c06423d68059cf0a6e6/src/main/java/yahoofinance/Utils.java#L194-L224
156,651
sstrickx/yahoofinance-api
src/main/java/yahoofinance/exchanges/ExchangeTimeZone.java
ExchangeTimeZone.get
public static TimeZone get(String suffix) { if(SUFFIX_TIMEZONES.containsKey(suffix)) { return SUFFIX_TIMEZONES.get(suffix); } log.warn("Cannot find time zone for exchange suffix: '{}'. Using default: America/New_York", suffix); return SUFFIX_TIMEZONES.get(""); }
java
public static TimeZone get(String suffix) { if(SUFFIX_TIMEZONES.containsKey(suffix)) { return SUFFIX_TIMEZONES.get(suffix); } log.warn("Cannot find time zone for exchange suffix: '{}'. Using default: America/New_York", suffix); return SUFFIX_TIMEZONES.get(""); }
[ "public", "static", "TimeZone", "get", "(", "String", "suffix", ")", "{", "if", "(", "SUFFIX_TIMEZONES", ".", "containsKey", "(", "suffix", ")", ")", "{", "return", "SUFFIX_TIMEZONES", ".", "get", "(", "suffix", ")", ";", "}", "log", ".", "warn", "(", "\"Cannot find time zone for exchange suffix: '{}'. Using default: America/New_York\"", ",", "suffix", ")", ";", "return", "SUFFIX_TIMEZONES", ".", "get", "(", "\"\"", ")", ";", "}" ]
Get the time zone for a specific exchange suffix @param suffix suffix for the exchange in YahooFinance @return time zone of the exchange
[ "Get", "the", "time", "zone", "for", "a", "specific", "exchange", "suffix" ]
2766ba52fc5cccf9b4da5c06423d68059cf0a6e6
https://github.com/sstrickx/yahoofinance-api/blob/2766ba52fc5cccf9b4da5c06423d68059cf0a6e6/src/main/java/yahoofinance/exchanges/ExchangeTimeZone.java#L168-L174
156,652
sstrickx/yahoofinance-api
src/main/java/yahoofinance/exchanges/ExchangeTimeZone.java
ExchangeTimeZone.getStockTimeZone
public static TimeZone getStockTimeZone(String symbol) { // First check if it's a known stock index if(INDEX_TIMEZONES.containsKey(symbol)) { return INDEX_TIMEZONES.get(symbol); } if(!symbol.contains(".")) { return ExchangeTimeZone.get(""); } String[] split = symbol.split("\\."); return ExchangeTimeZone.get(split[split.length - 1]); }
java
public static TimeZone getStockTimeZone(String symbol) { // First check if it's a known stock index if(INDEX_TIMEZONES.containsKey(symbol)) { return INDEX_TIMEZONES.get(symbol); } if(!symbol.contains(".")) { return ExchangeTimeZone.get(""); } String[] split = symbol.split("\\."); return ExchangeTimeZone.get(split[split.length - 1]); }
[ "public", "static", "TimeZone", "getStockTimeZone", "(", "String", "symbol", ")", "{", "// First check if it's a known stock index", "if", "(", "INDEX_TIMEZONES", ".", "containsKey", "(", "symbol", ")", ")", "{", "return", "INDEX_TIMEZONES", ".", "get", "(", "symbol", ")", ";", "}", "if", "(", "!", "symbol", ".", "contains", "(", "\".\"", ")", ")", "{", "return", "ExchangeTimeZone", ".", "get", "(", "\"\"", ")", ";", "}", "String", "[", "]", "split", "=", "symbol", ".", "split", "(", "\"\\\\.\"", ")", ";", "return", "ExchangeTimeZone", ".", "get", "(", "split", "[", "split", ".", "length", "-", "1", "]", ")", ";", "}" ]
Get the time zone for a specific stock or index. For stocks, the exchange suffix is extracted from the stock symbol to retrieve the time zone. @param symbol stock symbol in YahooFinance @return time zone of the exchange on which this stock is traded
[ "Get", "the", "time", "zone", "for", "a", "specific", "stock", "or", "index", ".", "For", "stocks", "the", "exchange", "suffix", "is", "extracted", "from", "the", "stock", "symbol", "to", "retrieve", "the", "time", "zone", "." ]
2766ba52fc5cccf9b4da5c06423d68059cf0a6e6
https://github.com/sstrickx/yahoofinance-api/blob/2766ba52fc5cccf9b4da5c06423d68059cf0a6e6/src/main/java/yahoofinance/exchanges/ExchangeTimeZone.java#L183-L194
156,653
pedrovgs/Renderers
sample/src/main/java/com/pedrogomez/renderers/sample/ui/builder/VideoRendererBuilder.java
VideoRendererBuilder.getPrototypeClass
@Override protected Class getPrototypeClass(Video content) { Class prototypeClass; if (content.isFavorite()) { prototypeClass = FavoriteVideoRenderer.class; } else if (content.isLive()) { prototypeClass = LiveVideoRenderer.class; } else { prototypeClass = LikeVideoRenderer.class; } return prototypeClass; }
java
@Override protected Class getPrototypeClass(Video content) { Class prototypeClass; if (content.isFavorite()) { prototypeClass = FavoriteVideoRenderer.class; } else if (content.isLive()) { prototypeClass = LiveVideoRenderer.class; } else { prototypeClass = LikeVideoRenderer.class; } return prototypeClass; }
[ "@", "Override", "protected", "Class", "getPrototypeClass", "(", "Video", "content", ")", "{", "Class", "prototypeClass", ";", "if", "(", "content", ".", "isFavorite", "(", ")", ")", "{", "prototypeClass", "=", "FavoriteVideoRenderer", ".", "class", ";", "}", "else", "if", "(", "content", ".", "isLive", "(", ")", ")", "{", "prototypeClass", "=", "LiveVideoRenderer", ".", "class", ";", "}", "else", "{", "prototypeClass", "=", "LikeVideoRenderer", ".", "class", ";", "}", "return", "prototypeClass", ";", "}" ]
Method to declare Video-VideoRenderer mapping. Favorite videos will be rendered using FavoriteVideoRenderer. Live videos will be rendered using LiveVideoRenderer. Liked videos will be rendered using LikeVideoRenderer. @param content used to map object-renderers. @return VideoRenderer subtype class.
[ "Method", "to", "declare", "Video", "-", "VideoRenderer", "mapping", ".", "Favorite", "videos", "will", "be", "rendered", "using", "FavoriteVideoRenderer", ".", "Live", "videos", "will", "be", "rendered", "using", "LiveVideoRenderer", ".", "Liked", "videos", "will", "be", "rendered", "using", "LikeVideoRenderer", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/sample/src/main/java/com/pedrogomez/renderers/sample/ui/builder/VideoRendererBuilder.java#L49-L59
156,654
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RVRendererAdapter.java
RVRendererAdapter.getItemViewType
@Override public int getItemViewType(int position) { T content = getItem(position); return rendererBuilder.getItemViewType(content); }
java
@Override public int getItemViewType(int position) { T content = getItem(position); return rendererBuilder.getItemViewType(content); }
[ "@", "Override", "public", "int", "getItemViewType", "(", "int", "position", ")", "{", "T", "content", "=", "getItem", "(", "position", ")", ";", "return", "rendererBuilder", ".", "getItemViewType", "(", "content", ")", ";", "}" ]
Indicate to the RecyclerView the type of Renderer used to one position using a numeric value. @param position to analyze. @return the id associated to the Renderer used to render the content given a position.
[ "Indicate", "to", "the", "RecyclerView", "the", "type", "of", "Renderer", "used", "to", "one", "position", "using", "a", "numeric", "value", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RVRendererAdapter.java#L81-L84
156,655
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RVRendererAdapter.java
RVRendererAdapter.onCreateViewHolder
@Override public RendererViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { rendererBuilder.withParent(viewGroup); rendererBuilder.withLayoutInflater(LayoutInflater.from(viewGroup.getContext())); rendererBuilder.withViewType(viewType); RendererViewHolder viewHolder = rendererBuilder.buildRendererViewHolder(); if (viewHolder == null) { throw new NullRendererBuiltException("RendererBuilder have to return a not null viewHolder"); } return viewHolder; }
java
@Override public RendererViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { rendererBuilder.withParent(viewGroup); rendererBuilder.withLayoutInflater(LayoutInflater.from(viewGroup.getContext())); rendererBuilder.withViewType(viewType); RendererViewHolder viewHolder = rendererBuilder.buildRendererViewHolder(); if (viewHolder == null) { throw new NullRendererBuiltException("RendererBuilder have to return a not null viewHolder"); } return viewHolder; }
[ "@", "Override", "public", "RendererViewHolder", "onCreateViewHolder", "(", "ViewGroup", "viewGroup", ",", "int", "viewType", ")", "{", "rendererBuilder", ".", "withParent", "(", "viewGroup", ")", ";", "rendererBuilder", ".", "withLayoutInflater", "(", "LayoutInflater", ".", "from", "(", "viewGroup", ".", "getContext", "(", ")", ")", ")", ";", "rendererBuilder", ".", "withViewType", "(", "viewType", ")", ";", "RendererViewHolder", "viewHolder", "=", "rendererBuilder", ".", "buildRendererViewHolder", "(", ")", ";", "if", "(", "viewHolder", "==", "null", ")", "{", "throw", "new", "NullRendererBuiltException", "(", "\"RendererBuilder have to return a not null viewHolder\"", ")", ";", "}", "return", "viewHolder", ";", "}" ]
One of the two main methods in this class. Creates a RendererViewHolder instance with a Renderer inside ready to be used. The RendererBuilder to create a RendererViewHolder using the information given as parameter. @param viewGroup used to create the ViewHolder. @param viewType associated to the renderer. @return ViewHolder extension with the Renderer it has to use inside.
[ "One", "of", "the", "two", "main", "methods", "in", "this", "class", ".", "Creates", "a", "RendererViewHolder", "instance", "with", "a", "Renderer", "inside", "ready", "to", "be", "used", ".", "The", "RendererBuilder", "to", "create", "a", "RendererViewHolder", "using", "the", "information", "given", "as", "parameter", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RVRendererAdapter.java#L95-L104
156,656
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RVRendererAdapter.java
RVRendererAdapter.onBindViewHolder
@Override public void onBindViewHolder(RendererViewHolder viewHolder, int position) { T content = getItem(position); Renderer<T> renderer = viewHolder.getRenderer(); if (renderer == null) { throw new NullRendererBuiltException("RendererBuilder have to return a not null renderer"); } renderer.setContent(content); updateRendererExtraValues(content, renderer, position); renderer.render(); }
java
@Override public void onBindViewHolder(RendererViewHolder viewHolder, int position) { T content = getItem(position); Renderer<T> renderer = viewHolder.getRenderer(); if (renderer == null) { throw new NullRendererBuiltException("RendererBuilder have to return a not null renderer"); } renderer.setContent(content); updateRendererExtraValues(content, renderer, position); renderer.render(); }
[ "@", "Override", "public", "void", "onBindViewHolder", "(", "RendererViewHolder", "viewHolder", ",", "int", "position", ")", "{", "T", "content", "=", "getItem", "(", "position", ")", ";", "Renderer", "<", "T", ">", "renderer", "=", "viewHolder", ".", "getRenderer", "(", ")", ";", "if", "(", "renderer", "==", "null", ")", "{", "throw", "new", "NullRendererBuiltException", "(", "\"RendererBuilder have to return a not null renderer\"", ")", ";", "}", "renderer", ".", "setContent", "(", "content", ")", ";", "updateRendererExtraValues", "(", "content", ",", "renderer", ",", "position", ")", ";", "renderer", ".", "render", "(", ")", ";", "}" ]
Given a RendererViewHolder passed as argument and a position renders the view using the Renderer previously stored into the RendererViewHolder. @param viewHolder with a Renderer class inside. @param position to render.
[ "Given", "a", "RendererViewHolder", "passed", "as", "argument", "and", "a", "position", "renders", "the", "view", "using", "the", "Renderer", "previously", "stored", "into", "the", "RendererViewHolder", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RVRendererAdapter.java#L113-L122
156,657
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RVRendererAdapter.java
RVRendererAdapter.diffUpdate
public void diffUpdate(List<T> newList) { if (getCollection().size() == 0) { addAll(newList); notifyDataSetChanged(); } else { DiffCallback diffCallback = new DiffCallback(collection, newList); DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback); clear(); addAll(newList); diffResult.dispatchUpdatesTo(this); } }
java
public void diffUpdate(List<T> newList) { if (getCollection().size() == 0) { addAll(newList); notifyDataSetChanged(); } else { DiffCallback diffCallback = new DiffCallback(collection, newList); DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback); clear(); addAll(newList); diffResult.dispatchUpdatesTo(this); } }
[ "public", "void", "diffUpdate", "(", "List", "<", "T", ">", "newList", ")", "{", "if", "(", "getCollection", "(", ")", ".", "size", "(", ")", "==", "0", ")", "{", "addAll", "(", "newList", ")", ";", "notifyDataSetChanged", "(", ")", ";", "}", "else", "{", "DiffCallback", "diffCallback", "=", "new", "DiffCallback", "(", "collection", ",", "newList", ")", ";", "DiffUtil", ".", "DiffResult", "diffResult", "=", "DiffUtil", ".", "calculateDiff", "(", "diffCallback", ")", ";", "clear", "(", ")", ";", "addAll", "(", "newList", ")", ";", "diffResult", ".", "dispatchUpdatesTo", "(", "this", ")", ";", "}", "}" ]
Provides a ready to use diff update for our adapter based on the implementation of the standard equals method from Object. @param newList to refresh our content
[ "Provides", "a", "ready", "to", "use", "diff", "update", "for", "our", "adapter", "based", "on", "the", "implementation", "of", "the", "standard", "equals", "method", "from", "Object", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RVRendererAdapter.java#L201-L212
156,658
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java
RendererBuilder.withPrototype
public RendererBuilder<T> withPrototype(Renderer<? extends T> renderer) { if (renderer == null) { throw new NeedsPrototypesException( "RendererBuilder can't use a null Renderer<T> instance as prototype"); } this.prototypes.add(renderer); return this; }
java
public RendererBuilder<T> withPrototype(Renderer<? extends T> renderer) { if (renderer == null) { throw new NeedsPrototypesException( "RendererBuilder can't use a null Renderer<T> instance as prototype"); } this.prototypes.add(renderer); return this; }
[ "public", "RendererBuilder", "<", "T", ">", "withPrototype", "(", "Renderer", "<", "?", "extends", "T", ">", "renderer", ")", "{", "if", "(", "renderer", "==", "null", ")", "{", "throw", "new", "NeedsPrototypesException", "(", "\"RendererBuilder can't use a null Renderer<T> instance as prototype\"", ")", ";", "}", "this", ".", "prototypes", ".", "add", "(", "renderer", ")", ";", "return", "this", ";", "}" ]
Add a Renderer instance as prototype. @param renderer to use as prototype. @return the current RendererBuilder instance.
[ "Add", "a", "Renderer", "instance", "as", "prototype", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java#L134-L141
156,659
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java
RendererBuilder.bind
public <G extends T> RendererBuilder<T> bind(Class<G> clazz, Renderer<? extends G> prototype) { if (clazz == null || prototype == null) { throw new IllegalArgumentException( "The binding RecyclerView binding can't be configured using null instances"); } prototypes.add(prototype); binding.put(clazz, prototype.getClass()); return this; }
java
public <G extends T> RendererBuilder<T> bind(Class<G> clazz, Renderer<? extends G> prototype) { if (clazz == null || prototype == null) { throw new IllegalArgumentException( "The binding RecyclerView binding can't be configured using null instances"); } prototypes.add(prototype); binding.put(clazz, prototype.getClass()); return this; }
[ "public", "<", "G", "extends", "T", ">", "RendererBuilder", "<", "T", ">", "bind", "(", "Class", "<", "G", ">", "clazz", ",", "Renderer", "<", "?", "extends", "G", ">", "prototype", ")", "{", "if", "(", "clazz", "==", "null", "||", "prototype", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The binding RecyclerView binding can't be configured using null instances\"", ")", ";", "}", "prototypes", ".", "add", "(", "prototype", ")", ";", "binding", ".", "put", "(", "clazz", ",", "prototype", ".", "getClass", "(", ")", ")", ";", "return", "this", ";", "}" ]
Given a class configures the binding between a class and a Renderer class. @param clazz to bind. @param prototype used as Renderer. @return the current RendererBuilder instance.
[ "Given", "a", "class", "configures", "the", "binding", "between", "a", "class", "and", "a", "Renderer", "class", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java#L150-L158
156,660
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java
RendererBuilder.getItemViewType
int getItemViewType(T content) { Class prototypeClass = getPrototypeClass(content); validatePrototypeClass(prototypeClass); return getItemViewType(prototypeClass); }
java
int getItemViewType(T content) { Class prototypeClass = getPrototypeClass(content); validatePrototypeClass(prototypeClass); return getItemViewType(prototypeClass); }
[ "int", "getItemViewType", "(", "T", "content", ")", "{", "Class", "prototypeClass", "=", "getPrototypeClass", "(", "content", ")", ";", "validatePrototypeClass", "(", "prototypeClass", ")", ";", "return", "getItemViewType", "(", "prototypeClass", ")", ";", "}" ]
Return the item view type used by the adapter to implement recycle mechanism. @param content to be rendered. @return an integer that represents the renderer inside the adapter.
[ "Return", "the", "item", "view", "type", "used", "by", "the", "adapter", "to", "implement", "recycle", "mechanism", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java#L200-L204
156,661
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java
RendererBuilder.build
protected Renderer build() { validateAttributes(); Renderer renderer; if (isRecyclable(convertView, content)) { renderer = recycle(convertView, content); } else { renderer = createRenderer(content, parent); } return renderer; }
java
protected Renderer build() { validateAttributes(); Renderer renderer; if (isRecyclable(convertView, content)) { renderer = recycle(convertView, content); } else { renderer = createRenderer(content, parent); } return renderer; }
[ "protected", "Renderer", "build", "(", ")", "{", "validateAttributes", "(", ")", ";", "Renderer", "renderer", ";", "if", "(", "isRecyclable", "(", "convertView", ",", "content", ")", ")", "{", "renderer", "=", "recycle", "(", "convertView", ",", "content", ")", ";", "}", "else", "{", "renderer", "=", "createRenderer", "(", "content", ",", "parent", ")", ";", "}", "return", "renderer", ";", "}" ]
Main method of this class related to ListView widget. This method is the responsible of recycle or create a new Renderer instance with all the needed information to implement the rendering. This method will validate all the attributes passed in the builder constructor and will check if can recycle or has to create a new Renderer instance. This method is used with ListView because the view recycling mechanism is implemented in this class. RecyclerView widget will use buildRendererViewHolder method. @return ready to use Renderer instance.
[ "Main", "method", "of", "this", "class", "related", "to", "ListView", "widget", ".", "This", "method", "is", "the", "responsible", "of", "recycle", "or", "create", "a", "new", "Renderer", "instance", "with", "all", "the", "needed", "information", "to", "implement", "the", "rendering", ".", "This", "method", "will", "validate", "all", "the", "attributes", "passed", "in", "the", "builder", "constructor", "and", "will", "check", "if", "can", "recycle", "or", "has", "to", "create", "a", "new", "Renderer", "instance", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java#L227-L237
156,662
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java
RendererBuilder.buildRendererViewHolder
protected RendererViewHolder buildRendererViewHolder() { validateAttributesToCreateANewRendererViewHolder(); Renderer renderer = getPrototypeByIndex(viewType).copy(); renderer.onCreate(null, layoutInflater, parent); return new RendererViewHolder(renderer); }
java
protected RendererViewHolder buildRendererViewHolder() { validateAttributesToCreateANewRendererViewHolder(); Renderer renderer = getPrototypeByIndex(viewType).copy(); renderer.onCreate(null, layoutInflater, parent); return new RendererViewHolder(renderer); }
[ "protected", "RendererViewHolder", "buildRendererViewHolder", "(", ")", "{", "validateAttributesToCreateANewRendererViewHolder", "(", ")", ";", "Renderer", "renderer", "=", "getPrototypeByIndex", "(", "viewType", ")", ".", "copy", "(", ")", ";", "renderer", ".", "onCreate", "(", "null", ",", "layoutInflater", ",", "parent", ")", ";", "return", "new", "RendererViewHolder", "(", "renderer", ")", ";", "}" ]
Main method of this class related to RecyclerView widget. This method is the responsible of create a new Renderer instance with all the needed information to implement the rendering. This method will validate all the attributes passed in the builder constructor and will create a RendererViewHolder instance. This method is used with RecyclerView because the view recycling mechanism is implemented out of this class and we only have to return new RendererViewHolder instances. @return ready to use RendererViewHolder instance.
[ "Main", "method", "of", "this", "class", "related", "to", "RecyclerView", "widget", ".", "This", "method", "is", "the", "responsible", "of", "create", "a", "new", "Renderer", "instance", "with", "all", "the", "needed", "information", "to", "implement", "the", "rendering", ".", "This", "method", "will", "validate", "all", "the", "attributes", "passed", "in", "the", "builder", "constructor", "and", "will", "create", "a", "RendererViewHolder", "instance", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java#L250-L256
156,663
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java
RendererBuilder.recycle
private Renderer recycle(View convertView, T content) { Renderer renderer = (Renderer) convertView.getTag(); renderer.onRecycle(content); return renderer; }
java
private Renderer recycle(View convertView, T content) { Renderer renderer = (Renderer) convertView.getTag(); renderer.onRecycle(content); return renderer; }
[ "private", "Renderer", "recycle", "(", "View", "convertView", ",", "T", "content", ")", "{", "Renderer", "renderer", "=", "(", "Renderer", ")", "convertView", ".", "getTag", "(", ")", ";", "renderer", ".", "onRecycle", "(", "content", ")", ";", "return", "renderer", ";", "}" ]
Recycles the Renderer getting it from the tag associated to the renderer root view. This view is not used with RecyclerView widget. @param convertView that contains the tag. @param content to be updated in the recycled renderer. @return a recycled renderer.
[ "Recycles", "the", "Renderer", "getting", "it", "from", "the", "tag", "associated", "to", "the", "renderer", "root", "view", ".", "This", "view", "is", "not", "used", "with", "RecyclerView", "widget", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java#L266-L270
156,664
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java
RendererBuilder.createRenderer
private Renderer createRenderer(T content, ViewGroup parent) { int prototypeIndex = getPrototypeIndex(content); Renderer renderer = getPrototypeByIndex(prototypeIndex).copy(); renderer.onCreate(content, layoutInflater, parent); return renderer; }
java
private Renderer createRenderer(T content, ViewGroup parent) { int prototypeIndex = getPrototypeIndex(content); Renderer renderer = getPrototypeByIndex(prototypeIndex).copy(); renderer.onCreate(content, layoutInflater, parent); return renderer; }
[ "private", "Renderer", "createRenderer", "(", "T", "content", ",", "ViewGroup", "parent", ")", "{", "int", "prototypeIndex", "=", "getPrototypeIndex", "(", "content", ")", ";", "Renderer", "renderer", "=", "getPrototypeByIndex", "(", "prototypeIndex", ")", ".", "copy", "(", ")", ";", "renderer", ".", "onCreate", "(", "content", ",", "layoutInflater", ",", "parent", ")", ";", "return", "renderer", ";", "}" ]
Create a Renderer getting a copy from the prototypes collection. @param content to render. @param parent used to inflate the view. @return a new renderer.
[ "Create", "a", "Renderer", "getting", "a", "copy", "from", "the", "prototypes", "collection", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java#L279-L284
156,665
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java
RendererBuilder.getPrototypeByIndex
private Renderer getPrototypeByIndex(final int prototypeIndex) { Renderer prototypeSelected = null; int i = 0; for (Renderer prototype : prototypes) { if (i == prototypeIndex) { prototypeSelected = prototype; } i++; } return prototypeSelected; }
java
private Renderer getPrototypeByIndex(final int prototypeIndex) { Renderer prototypeSelected = null; int i = 0; for (Renderer prototype : prototypes) { if (i == prototypeIndex) { prototypeSelected = prototype; } i++; } return prototypeSelected; }
[ "private", "Renderer", "getPrototypeByIndex", "(", "final", "int", "prototypeIndex", ")", "{", "Renderer", "prototypeSelected", "=", "null", ";", "int", "i", "=", "0", ";", "for", "(", "Renderer", "prototype", ":", "prototypes", ")", "{", "if", "(", "i", "==", "prototypeIndex", ")", "{", "prototypeSelected", "=", "prototype", ";", "}", "i", "++", ";", "}", "return", "prototypeSelected", ";", "}" ]
Search one prototype using the prototype index which is equals to the view type. This method has to be implemented because prototypes member is declared with Collection and that interface doesn't allow the client code to get one element by index. @param prototypeIndex used to search. @return prototype renderer.
[ "Search", "one", "prototype", "using", "the", "prototype", "index", "which", "is", "equals", "to", "the", "view", "type", ".", "This", "method", "has", "to", "be", "implemented", "because", "prototypes", "member", "is", "declared", "with", "Collection", "and", "that", "interface", "doesn", "t", "allow", "the", "client", "code", "to", "get", "one", "element", "by", "index", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java#L294-L304
156,666
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java
RendererBuilder.isRecyclable
private boolean isRecyclable(View convertView, T content) { boolean isRecyclable = false; if (convertView != null && convertView.getTag() != null) { Class prototypeClass = getPrototypeClass(content); validatePrototypeClass(prototypeClass); isRecyclable = prototypeClass.equals(convertView.getTag().getClass()); } return isRecyclable; }
java
private boolean isRecyclable(View convertView, T content) { boolean isRecyclable = false; if (convertView != null && convertView.getTag() != null) { Class prototypeClass = getPrototypeClass(content); validatePrototypeClass(prototypeClass); isRecyclable = prototypeClass.equals(convertView.getTag().getClass()); } return isRecyclable; }
[ "private", "boolean", "isRecyclable", "(", "View", "convertView", ",", "T", "content", ")", "{", "boolean", "isRecyclable", "=", "false", ";", "if", "(", "convertView", "!=", "null", "&&", "convertView", ".", "getTag", "(", ")", "!=", "null", ")", "{", "Class", "prototypeClass", "=", "getPrototypeClass", "(", "content", ")", ";", "validatePrototypeClass", "(", "prototypeClass", ")", ";", "isRecyclable", "=", "prototypeClass", ".", "equals", "(", "convertView", ".", "getTag", "(", ")", ".", "getClass", "(", ")", ")", ";", "}", "return", "isRecyclable", ";", "}" ]
Check if one Renderer is recyclable getting it from the convertView's tag and checking the class used. @param convertView to get the renderer if is not null. @param content used to get the prototype class. @return true if the renderer is recyclable.
[ "Check", "if", "one", "Renderer", "is", "recyclable", "getting", "it", "from", "the", "convertView", "s", "tag", "and", "checking", "the", "class", "used", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java#L314-L322
156,667
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java
RendererBuilder.getItemViewType
private int getItemViewType(Class prototypeClass) { int itemViewType = -1; for (Renderer renderer : prototypes) { if (renderer.getClass().equals(prototypeClass)) { itemViewType = getPrototypeIndex(renderer); break; } } if (itemViewType == -1) { throw new PrototypeNotFoundException( "Review your RendererBuilder implementation, you are returning one" + " prototype class not found in prototypes collection"); } return itemViewType; }
java
private int getItemViewType(Class prototypeClass) { int itemViewType = -1; for (Renderer renderer : prototypes) { if (renderer.getClass().equals(prototypeClass)) { itemViewType = getPrototypeIndex(renderer); break; } } if (itemViewType == -1) { throw new PrototypeNotFoundException( "Review your RendererBuilder implementation, you are returning one" + " prototype class not found in prototypes collection"); } return itemViewType; }
[ "private", "int", "getItemViewType", "(", "Class", "prototypeClass", ")", "{", "int", "itemViewType", "=", "-", "1", ";", "for", "(", "Renderer", "renderer", ":", "prototypes", ")", "{", "if", "(", "renderer", ".", "getClass", "(", ")", ".", "equals", "(", "prototypeClass", ")", ")", "{", "itemViewType", "=", "getPrototypeIndex", "(", "renderer", ")", ";", "break", ";", "}", "}", "if", "(", "itemViewType", "==", "-", "1", ")", "{", "throw", "new", "PrototypeNotFoundException", "(", "\"Review your RendererBuilder implementation, you are returning one\"", "+", "\" prototype class not found in prototypes collection\"", ")", ";", "}", "return", "itemViewType", ";", "}" ]
Return the Renderer class associated to the prototype. @param prototypeClass used to search the renderer in the prototypes collection. @return the prototype index associated to the prototypeClass.
[ "Return", "the", "Renderer", "class", "associated", "to", "the", "prototype", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java#L347-L361
156,668
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java
RendererBuilder.getPrototypeIndex
private int getPrototypeIndex(Renderer renderer) { int index = 0; for (Renderer prototype : prototypes) { if (prototype.getClass().equals(renderer.getClass())) { break; } index++; } return index; }
java
private int getPrototypeIndex(Renderer renderer) { int index = 0; for (Renderer prototype : prototypes) { if (prototype.getClass().equals(renderer.getClass())) { break; } index++; } return index; }
[ "private", "int", "getPrototypeIndex", "(", "Renderer", "renderer", ")", "{", "int", "index", "=", "0", ";", "for", "(", "Renderer", "prototype", ":", "prototypes", ")", "{", "if", "(", "prototype", ".", "getClass", "(", ")", ".", "equals", "(", "renderer", ".", "getClass", "(", ")", ")", ")", "{", "break", ";", "}", "index", "++", ";", "}", "return", "index", ";", "}" ]
Return the index associated to the Renderer. @param renderer used to search in the prototypes collection. @return the prototype index associated to the renderer passed as argument.
[ "Return", "the", "index", "associated", "to", "the", "Renderer", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java#L369-L378
156,669
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java
RendererBuilder.validateAttributes
private void validateAttributes() { if (content == null) { throw new NullContentException("RendererBuilder needs content to create Renderer instances"); } if (parent == null) { throw new NullParentException("RendererBuilder needs a parent to inflate Renderer instances"); } if (layoutInflater == null) { throw new NullLayoutInflaterException( "RendererBuilder needs a LayoutInflater to inflate Renderer instances"); } }
java
private void validateAttributes() { if (content == null) { throw new NullContentException("RendererBuilder needs content to create Renderer instances"); } if (parent == null) { throw new NullParentException("RendererBuilder needs a parent to inflate Renderer instances"); } if (layoutInflater == null) { throw new NullLayoutInflaterException( "RendererBuilder needs a LayoutInflater to inflate Renderer instances"); } }
[ "private", "void", "validateAttributes", "(", ")", "{", "if", "(", "content", "==", "null", ")", "{", "throw", "new", "NullContentException", "(", "\"RendererBuilder needs content to create Renderer instances\"", ")", ";", "}", "if", "(", "parent", "==", "null", ")", "{", "throw", "new", "NullParentException", "(", "\"RendererBuilder needs a parent to inflate Renderer instances\"", ")", ";", "}", "if", "(", "layoutInflater", "==", "null", ")", "{", "throw", "new", "NullLayoutInflaterException", "(", "\"RendererBuilder needs a LayoutInflater to inflate Renderer instances\"", ")", ";", "}", "}" ]
Throws one RendererException if the content parent or layoutInflater are null.
[ "Throws", "one", "RendererException", "if", "the", "content", "parent", "or", "layoutInflater", "are", "null", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java#L383-L396
156,670
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java
RendererBuilder.validateAttributesToCreateANewRendererViewHolder
private void validateAttributesToCreateANewRendererViewHolder() { if (viewType == null) { throw new NullContentException( "RendererBuilder needs a view type to create a RendererViewHolder"); } if (layoutInflater == null) { throw new NullLayoutInflaterException( "RendererBuilder needs a LayoutInflater to create a RendererViewHolder"); } if (parent == null) { throw new NullParentException( "RendererBuilder needs a parent to create a RendererViewHolder"); } }
java
private void validateAttributesToCreateANewRendererViewHolder() { if (viewType == null) { throw new NullContentException( "RendererBuilder needs a view type to create a RendererViewHolder"); } if (layoutInflater == null) { throw new NullLayoutInflaterException( "RendererBuilder needs a LayoutInflater to create a RendererViewHolder"); } if (parent == null) { throw new NullParentException( "RendererBuilder needs a parent to create a RendererViewHolder"); } }
[ "private", "void", "validateAttributesToCreateANewRendererViewHolder", "(", ")", "{", "if", "(", "viewType", "==", "null", ")", "{", "throw", "new", "NullContentException", "(", "\"RendererBuilder needs a view type to create a RendererViewHolder\"", ")", ";", "}", "if", "(", "layoutInflater", "==", "null", ")", "{", "throw", "new", "NullLayoutInflaterException", "(", "\"RendererBuilder needs a LayoutInflater to create a RendererViewHolder\"", ")", ";", "}", "if", "(", "parent", "==", "null", ")", "{", "throw", "new", "NullParentException", "(", "\"RendererBuilder needs a parent to create a RendererViewHolder\"", ")", ";", "}", "}" ]
Throws one RendererException if the viewType, layoutInflater or parent are null.
[ "Throws", "one", "RendererException", "if", "the", "viewType", "layoutInflater", "or", "parent", "are", "null", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java#L401-L414
156,671
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java
RendererBuilder.getPrototypeClass
protected Class getPrototypeClass(T content) { if (prototypes.size() == 1) { return prototypes.get(0).getClass(); } else { return binding.get(content.getClass()); } }
java
protected Class getPrototypeClass(T content) { if (prototypes.size() == 1) { return prototypes.get(0).getClass(); } else { return binding.get(content.getClass()); } }
[ "protected", "Class", "getPrototypeClass", "(", "T", "content", ")", "{", "if", "(", "prototypes", ".", "size", "(", ")", "==", "1", ")", "{", "return", "prototypes", ".", "get", "(", "0", ")", ".", "getClass", "(", ")", ";", "}", "else", "{", "return", "binding", ".", "get", "(", "content", ".", "getClass", "(", ")", ")", ";", "}", "}" ]
Method to be implemented by the RendererBuilder subtypes. In this method the library user will define the mapping between content and renderer class. @param content used to map object to Renderers. @return the class associated to the renderer.
[ "Method", "to", "be", "implemented", "by", "the", "RendererBuilder", "subtypes", ".", "In", "this", "method", "the", "library", "user", "will", "define", "the", "mapping", "between", "content", "and", "renderer", "class", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RendererBuilder.java#L423-L429
156,672
pedrovgs/Renderers
sample/src/main/java/com/pedrogomez/renderers/sample/ui/renderers/VideoRenderer.java
VideoRenderer.inflate
@Override protected View inflate(LayoutInflater inflater, ViewGroup parent) { View inflatedView = inflater.inflate(R.layout.video_renderer, parent, false); /* * You don't have to use ButterKnife library to implement the mapping between your layout * and your widgets you can implement setUpView and hookListener methods declared in * Renderer<T> class. */ ButterKnife.bind(this, inflatedView); return inflatedView; }
java
@Override protected View inflate(LayoutInflater inflater, ViewGroup parent) { View inflatedView = inflater.inflate(R.layout.video_renderer, parent, false); /* * You don't have to use ButterKnife library to implement the mapping between your layout * and your widgets you can implement setUpView and hookListener methods declared in * Renderer<T> class. */ ButterKnife.bind(this, inflatedView); return inflatedView; }
[ "@", "Override", "protected", "View", "inflate", "(", "LayoutInflater", "inflater", ",", "ViewGroup", "parent", ")", "{", "View", "inflatedView", "=", "inflater", ".", "inflate", "(", "R", ".", "layout", ".", "video_renderer", ",", "parent", ",", "false", ")", ";", "/*\n * You don't have to use ButterKnife library to implement the mapping between your layout\n * and your widgets you can implement setUpView and hookListener methods declared in\n * Renderer<T> class.\n */", "ButterKnife", ".", "bind", "(", "this", ",", "inflatedView", ")", ";", "return", "inflatedView", ";", "}" ]
Inflate the main layout used to render videos in the list view. @param inflater LayoutInflater service to inflate. @param parent ViewGroup used to inflate xml. @return view inflated.
[ "Inflate", "the", "main", "layout", "used", "to", "render", "videos", "in", "the", "list", "view", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/sample/src/main/java/com/pedrogomez/renderers/sample/ui/renderers/VideoRenderer.java#L52-L61
156,673
pedrovgs/Renderers
sample/src/main/java/com/pedrogomez/renderers/sample/ui/renderers/VideoRenderer.java
VideoRenderer.render
@Override public void render() { Video video = getContent(); renderThumbnail(video); renderTitle(video); renderMarker(video); renderLabel(); }
java
@Override public void render() { Video video = getContent(); renderThumbnail(video); renderTitle(video); renderMarker(video); renderLabel(); }
[ "@", "Override", "public", "void", "render", "(", ")", "{", "Video", "video", "=", "getContent", "(", ")", ";", "renderThumbnail", "(", "video", ")", ";", "renderTitle", "(", "video", ")", ";", "renderMarker", "(", "video", ")", ";", "renderLabel", "(", ")", ";", "}" ]
Main render algorithm based on render the video thumbnail, render the title, render the marker and the label.
[ "Main", "render", "algorithm", "based", "on", "render", "the", "video", "thumbnail", "render", "the", "title", "render", "the", "marker", "and", "the", "label", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/sample/src/main/java/com/pedrogomez/renderers/sample/ui/renderers/VideoRenderer.java#L73-L79
156,674
pedrovgs/Renderers
sample/src/main/java/com/pedrogomez/renderers/sample/ui/renderers/VideoRenderer.java
VideoRenderer.renderThumbnail
private void renderThumbnail(Video video) { Picasso.with(getContext()).cancelRequest(thumbnail); Picasso.with(getContext()) .load(video.getThumbnail()) .placeholder(R.drawable.placeholder) .into(thumbnail); }
java
private void renderThumbnail(Video video) { Picasso.with(getContext()).cancelRequest(thumbnail); Picasso.with(getContext()) .load(video.getThumbnail()) .placeholder(R.drawable.placeholder) .into(thumbnail); }
[ "private", "void", "renderThumbnail", "(", "Video", "video", ")", "{", "Picasso", ".", "with", "(", "getContext", "(", ")", ")", ".", "cancelRequest", "(", "thumbnail", ")", ";", "Picasso", ".", "with", "(", "getContext", "(", ")", ")", ".", "load", "(", "video", ".", "getThumbnail", "(", ")", ")", ".", "placeholder", "(", "R", ".", "drawable", ".", "placeholder", ")", ".", "into", "(", "thumbnail", ")", ";", "}" ]
Use picasso to render the video thumbnail into the thumbnail widget using a temporal placeholder. @param video to get the rendered thumbnail.
[ "Use", "picasso", "to", "render", "the", "video", "thumbnail", "into", "the", "thumbnail", "widget", "using", "a", "temporal", "placeholder", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/sample/src/main/java/com/pedrogomez/renderers/sample/ui/renderers/VideoRenderer.java#L87-L93
156,675
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/Renderer.java
Renderer.onCreate
public void onCreate(T content, LayoutInflater layoutInflater, ViewGroup parent) { this.content = content; this.rootView = inflate(layoutInflater, parent); if (rootView == null) { throw new NotInflateViewException( "Renderer instances have to return a not null view in inflateView method"); } this.rootView.setTag(this); setUpView(rootView); hookListeners(rootView); }
java
public void onCreate(T content, LayoutInflater layoutInflater, ViewGroup parent) { this.content = content; this.rootView = inflate(layoutInflater, parent); if (rootView == null) { throw new NotInflateViewException( "Renderer instances have to return a not null view in inflateView method"); } this.rootView.setTag(this); setUpView(rootView); hookListeners(rootView); }
[ "public", "void", "onCreate", "(", "T", "content", ",", "LayoutInflater", "layoutInflater", ",", "ViewGroup", "parent", ")", "{", "this", ".", "content", "=", "content", ";", "this", ".", "rootView", "=", "inflate", "(", "layoutInflater", ",", "parent", ")", ";", "if", "(", "rootView", "==", "null", ")", "{", "throw", "new", "NotInflateViewException", "(", "\"Renderer instances have to return a not null view in inflateView method\"", ")", ";", "}", "this", ".", "rootView", ".", "setTag", "(", "this", ")", ";", "setUpView", "(", "rootView", ")", ";", "hookListeners", "(", "rootView", ")", ";", "}" ]
Method called when the renderer is going to be created. This method has the responsibility of inflate the xml layout using the layoutInflater and the parent ViewGroup, set itself to the tag and call setUpView and hookListeners methods. @param content to render. If you are using Renderers with RecyclerView widget the content will be null in this method. @param layoutInflater used to inflate the view. @param parent used to inflate the view.
[ "Method", "called", "when", "the", "renderer", "is", "going", "to", "be", "created", ".", "This", "method", "has", "the", "responsibility", "of", "inflate", "the", "xml", "layout", "using", "the", "layoutInflater", "and", "the", "parent", "ViewGroup", "set", "itself", "to", "the", "tag", "and", "call", "setUpView", "and", "hookListeners", "methods", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/Renderer.java#L54-L64
156,676
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/Renderer.java
Renderer.copy
Renderer copy() { Renderer copy = null; try { copy = (Renderer) this.clone(); } catch (CloneNotSupportedException e) { Log.e("Renderer", "All your renderers should be clonables."); } return copy; }
java
Renderer copy() { Renderer copy = null; try { copy = (Renderer) this.clone(); } catch (CloneNotSupportedException e) { Log.e("Renderer", "All your renderers should be clonables."); } return copy; }
[ "Renderer", "copy", "(", ")", "{", "Renderer", "copy", "=", "null", ";", "try", "{", "copy", "=", "(", "Renderer", ")", "this", ".", "clone", "(", ")", ";", "}", "catch", "(", "CloneNotSupportedException", "e", ")", "{", "Log", ".", "e", "(", "\"Renderer\"", ",", "\"All your renderers should be clonables.\"", ")", ";", "}", "return", "copy", ";", "}" ]
Create a clone of the Renderer. This method is the base of the prototype mechanism implemented to avoid create new objects from RendererBuilder. Pay an special attention implementing clone method in Renderer subtypes. @return a copy of the current renderer.
[ "Create", "a", "clone", "of", "the", "Renderer", ".", "This", "method", "is", "the", "base", "of", "the", "prototype", "mechanism", "implemented", "to", "avoid", "create", "new", "objects", "from", "RendererBuilder", ".", "Pay", "an", "special", "attention", "implementing", "clone", "method", "in", "Renderer", "subtypes", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/Renderer.java#L147-L155
156,677
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RendererAdapter.java
RendererAdapter.getView
@Override public View getView(int position, View convertView, ViewGroup parent) { T content = getItem(position); rendererBuilder.withContent(content); rendererBuilder.withConvertView(convertView); rendererBuilder.withParent(parent); rendererBuilder.withLayoutInflater(LayoutInflater.from(parent.getContext())); Renderer<T> renderer = rendererBuilder.build(); if (renderer == null) { throw new NullRendererBuiltException("RendererBuilder have to return a not null Renderer"); } updateRendererExtraValues(content, renderer, position); renderer.render(); return renderer.getRootView(); }
java
@Override public View getView(int position, View convertView, ViewGroup parent) { T content = getItem(position); rendererBuilder.withContent(content); rendererBuilder.withConvertView(convertView); rendererBuilder.withParent(parent); rendererBuilder.withLayoutInflater(LayoutInflater.from(parent.getContext())); Renderer<T> renderer = rendererBuilder.build(); if (renderer == null) { throw new NullRendererBuiltException("RendererBuilder have to return a not null Renderer"); } updateRendererExtraValues(content, renderer, position); renderer.render(); return renderer.getRootView(); }
[ "@", "Override", "public", "View", "getView", "(", "int", "position", ",", "View", "convertView", ",", "ViewGroup", "parent", ")", "{", "T", "content", "=", "getItem", "(", "position", ")", ";", "rendererBuilder", ".", "withContent", "(", "content", ")", ";", "rendererBuilder", ".", "withConvertView", "(", "convertView", ")", ";", "rendererBuilder", ".", "withParent", "(", "parent", ")", ";", "rendererBuilder", ".", "withLayoutInflater", "(", "LayoutInflater", ".", "from", "(", "parent", ".", "getContext", "(", ")", ")", ")", ";", "Renderer", "<", "T", ">", "renderer", "=", "rendererBuilder", ".", "build", "(", ")", ";", "if", "(", "renderer", "==", "null", ")", "{", "throw", "new", "NullRendererBuiltException", "(", "\"RendererBuilder have to return a not null Renderer\"", ")", ";", "}", "updateRendererExtraValues", "(", "content", ",", "renderer", ",", "position", ")", ";", "renderer", ".", "render", "(", ")", ";", "return", "renderer", ".", "getRootView", "(", ")", ";", "}" ]
Main method of RendererAdapter. This method has the responsibility of update the RendererBuilder values and create or recycle a new Renderer. Once the renderer has been obtained the RendereBuilder will call the render method in the renderer and will return the Renderer root view to the ListView. If rRendererBuilder returns a null Renderer this method will throw a NullRendererBuiltException. @param position to render. @param convertView to use to recycle. @param parent used to inflate views. @return view rendered.
[ "Main", "method", "of", "RendererAdapter", ".", "This", "method", "has", "the", "responsibility", "of", "update", "the", "RendererBuilder", "values", "and", "create", "or", "recycle", "a", "new", "Renderer", ".", "Once", "the", "renderer", "has", "been", "obtained", "the", "RendereBuilder", "will", "call", "the", "render", "method", "in", "the", "renderer", "and", "will", "return", "the", "Renderer", "root", "view", "to", "the", "ListView", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RendererAdapter.java#L86-L99
156,678
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/VPRendererAdapter.java
VPRendererAdapter.instantiateItem
@Override public Object instantiateItem(ViewGroup parent, int position) { T content = getItem(position); rendererBuilder.withContent(content); rendererBuilder.withParent(parent); rendererBuilder.withLayoutInflater(LayoutInflater.from(parent.getContext())); Renderer<T> renderer = rendererBuilder.build(); if (renderer == null) { throw new NullRendererBuiltException("RendererBuilder have to return a not null Renderer"); } updateRendererExtraValues(content, renderer, position); renderer.render(); View view = renderer.getRootView(); parent.addView(view); return view; }
java
@Override public Object instantiateItem(ViewGroup parent, int position) { T content = getItem(position); rendererBuilder.withContent(content); rendererBuilder.withParent(parent); rendererBuilder.withLayoutInflater(LayoutInflater.from(parent.getContext())); Renderer<T> renderer = rendererBuilder.build(); if (renderer == null) { throw new NullRendererBuiltException("RendererBuilder have to return a not null Renderer"); } updateRendererExtraValues(content, renderer, position); renderer.render(); View view = renderer.getRootView(); parent.addView(view); return view; }
[ "@", "Override", "public", "Object", "instantiateItem", "(", "ViewGroup", "parent", ",", "int", "position", ")", "{", "T", "content", "=", "getItem", "(", "position", ")", ";", "rendererBuilder", ".", "withContent", "(", "content", ")", ";", "rendererBuilder", ".", "withParent", "(", "parent", ")", ";", "rendererBuilder", ".", "withLayoutInflater", "(", "LayoutInflater", ".", "from", "(", "parent", ".", "getContext", "(", ")", ")", ")", ";", "Renderer", "<", "T", ">", "renderer", "=", "rendererBuilder", ".", "build", "(", ")", ";", "if", "(", "renderer", "==", "null", ")", "{", "throw", "new", "NullRendererBuiltException", "(", "\"RendererBuilder have to return a not null Renderer\"", ")", ";", "}", "updateRendererExtraValues", "(", "content", ",", "renderer", ",", "position", ")", ";", "renderer", ".", "render", "(", ")", ";", "View", "view", "=", "renderer", ".", "getRootView", "(", ")", ";", "parent", ".", "addView", "(", "view", ")", ";", "return", "view", ";", "}" ]
Main method of VPRendererAdapter. This method has the responsibility of update the RendererBuilder values and create or recycle a new Renderer. Once the renderer has been obtained the RendereBuilder will call the render method in the renderer and will return the Renderer root view to the ViewPager. If RendererBuilder returns a null Renderer this method will throw a NullRendererBuiltException. @param parent The containing View in which the page will be shown. @param position to render. @return view rendered.
[ "Main", "method", "of", "VPRendererAdapter", ".", "This", "method", "has", "the", "responsibility", "of", "update", "the", "RendererBuilder", "values", "and", "create", "or", "recycle", "a", "new", "Renderer", ".", "Once", "the", "renderer", "has", "been", "obtained", "the", "RendereBuilder", "will", "call", "the", "render", "method", "in", "the", "renderer", "and", "will", "return", "the", "Renderer", "root", "view", "to", "the", "ViewPager", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/VPRendererAdapter.java#L66-L80
156,679
pedrovgs/Renderers
sample/src/main/java/com/pedrogomez/renderers/sample/model/RandomVideoCollectionGenerator.java
RandomVideoCollectionGenerator.generate
public VideoCollection generate(final int videoCount) { List<Video> videos = new LinkedList<Video>(); for (int i = 0; i < videoCount; i++) { Video video = generateRandomVideo(); videos.add(video); } return new VideoCollection(videos); }
java
public VideoCollection generate(final int videoCount) { List<Video> videos = new LinkedList<Video>(); for (int i = 0; i < videoCount; i++) { Video video = generateRandomVideo(); videos.add(video); } return new VideoCollection(videos); }
[ "public", "VideoCollection", "generate", "(", "final", "int", "videoCount", ")", "{", "List", "<", "Video", ">", "videos", "=", "new", "LinkedList", "<", "Video", ">", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "videoCount", ";", "i", "++", ")", "{", "Video", "video", "=", "generateRandomVideo", "(", ")", ";", "videos", ".", "add", "(", "video", ")", ";", "}", "return", "new", "VideoCollection", "(", "videos", ")", ";", "}" ]
Generate a VideoCollection with random data obtained form VIDEO_INFO map. You don't need o create your own AdapteeCollections. Review ListAdapteeCollection if needed. @param videoCount size of the collection. @return VideoCollection generated.
[ "Generate", "a", "VideoCollection", "with", "random", "data", "obtained", "form", "VIDEO_INFO", "map", ".", "You", "don", "t", "need", "o", "create", "your", "own", "AdapteeCollections", ".", "Review", "ListAdapteeCollection", "if", "needed", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/sample/src/main/java/com/pedrogomez/renderers/sample/model/RandomVideoCollectionGenerator.java#L49-L56
156,680
pedrovgs/Renderers
sample/src/main/java/com/pedrogomez/renderers/sample/model/RandomVideoCollectionGenerator.java
RandomVideoCollectionGenerator.initializeVideoInfo
private void initializeVideoInfo() { VIDEO_INFO.put("The Big Bang Theory", "http://thetvdb.com/banners/_cache/posters/80379-9.jpg"); VIDEO_INFO.put("Breaking Bad", "http://thetvdb.com/banners/_cache/posters/81189-22.jpg"); VIDEO_INFO.put("Arrow", "http://thetvdb.com/banners/_cache/posters/257655-15.jpg"); VIDEO_INFO.put("Game of Thrones", "http://thetvdb.com/banners/_cache/posters/121361-26.jpg"); VIDEO_INFO.put("Lost", "http://thetvdb.com/banners/_cache/posters/73739-2.jpg"); VIDEO_INFO.put("How I met your mother", "http://thetvdb.com/banners/_cache/posters/75760-29.jpg"); VIDEO_INFO.put("Dexter", "http://thetvdb.com/banners/_cache/posters/79349-24.jpg"); VIDEO_INFO.put("Sleepy Hollow", "http://thetvdb.com/banners/_cache/posters/269578-5.jpg"); VIDEO_INFO.put("The Vampire Diaries", "http://thetvdb.com/banners/_cache/posters/95491-27.jpg"); VIDEO_INFO.put("Friends", "http://thetvdb.com/banners/_cache/posters/79168-4.jpg"); VIDEO_INFO.put("New Girl", "http://thetvdb.com/banners/_cache/posters/248682-9.jpg"); VIDEO_INFO.put("The Mentalist", "http://thetvdb.com/banners/_cache/posters/82459-1.jpg"); VIDEO_INFO.put("Sons of Anarchy", "http://thetvdb.com/banners/_cache/posters/82696-1.jpg"); }
java
private void initializeVideoInfo() { VIDEO_INFO.put("The Big Bang Theory", "http://thetvdb.com/banners/_cache/posters/80379-9.jpg"); VIDEO_INFO.put("Breaking Bad", "http://thetvdb.com/banners/_cache/posters/81189-22.jpg"); VIDEO_INFO.put("Arrow", "http://thetvdb.com/banners/_cache/posters/257655-15.jpg"); VIDEO_INFO.put("Game of Thrones", "http://thetvdb.com/banners/_cache/posters/121361-26.jpg"); VIDEO_INFO.put("Lost", "http://thetvdb.com/banners/_cache/posters/73739-2.jpg"); VIDEO_INFO.put("How I met your mother", "http://thetvdb.com/banners/_cache/posters/75760-29.jpg"); VIDEO_INFO.put("Dexter", "http://thetvdb.com/banners/_cache/posters/79349-24.jpg"); VIDEO_INFO.put("Sleepy Hollow", "http://thetvdb.com/banners/_cache/posters/269578-5.jpg"); VIDEO_INFO.put("The Vampire Diaries", "http://thetvdb.com/banners/_cache/posters/95491-27.jpg"); VIDEO_INFO.put("Friends", "http://thetvdb.com/banners/_cache/posters/79168-4.jpg"); VIDEO_INFO.put("New Girl", "http://thetvdb.com/banners/_cache/posters/248682-9.jpg"); VIDEO_INFO.put("The Mentalist", "http://thetvdb.com/banners/_cache/posters/82459-1.jpg"); VIDEO_INFO.put("Sons of Anarchy", "http://thetvdb.com/banners/_cache/posters/82696-1.jpg"); }
[ "private", "void", "initializeVideoInfo", "(", ")", "{", "VIDEO_INFO", ".", "put", "(", "\"The Big Bang Theory\"", ",", "\"http://thetvdb.com/banners/_cache/posters/80379-9.jpg\"", ")", ";", "VIDEO_INFO", ".", "put", "(", "\"Breaking Bad\"", ",", "\"http://thetvdb.com/banners/_cache/posters/81189-22.jpg\"", ")", ";", "VIDEO_INFO", ".", "put", "(", "\"Arrow\"", ",", "\"http://thetvdb.com/banners/_cache/posters/257655-15.jpg\"", ")", ";", "VIDEO_INFO", ".", "put", "(", "\"Game of Thrones\"", ",", "\"http://thetvdb.com/banners/_cache/posters/121361-26.jpg\"", ")", ";", "VIDEO_INFO", ".", "put", "(", "\"Lost\"", ",", "\"http://thetvdb.com/banners/_cache/posters/73739-2.jpg\"", ")", ";", "VIDEO_INFO", ".", "put", "(", "\"How I met your mother\"", ",", "\"http://thetvdb.com/banners/_cache/posters/75760-29.jpg\"", ")", ";", "VIDEO_INFO", ".", "put", "(", "\"Dexter\"", ",", "\"http://thetvdb.com/banners/_cache/posters/79349-24.jpg\"", ")", ";", "VIDEO_INFO", ".", "put", "(", "\"Sleepy Hollow\"", ",", "\"http://thetvdb.com/banners/_cache/posters/269578-5.jpg\"", ")", ";", "VIDEO_INFO", ".", "put", "(", "\"The Vampire Diaries\"", ",", "\"http://thetvdb.com/banners/_cache/posters/95491-27.jpg\"", ")", ";", "VIDEO_INFO", ".", "put", "(", "\"Friends\"", ",", "\"http://thetvdb.com/banners/_cache/posters/79168-4.jpg\"", ")", ";", "VIDEO_INFO", ".", "put", "(", "\"New Girl\"", ",", "\"http://thetvdb.com/banners/_cache/posters/248682-9.jpg\"", ")", ";", "VIDEO_INFO", ".", "put", "(", "\"The Mentalist\"", ",", "\"http://thetvdb.com/banners/_cache/posters/82459-1.jpg\"", ")", ";", "VIDEO_INFO", ".", "put", "(", "\"Sons of Anarchy\"", ",", "\"http://thetvdb.com/banners/_cache/posters/82696-1.jpg\"", ")", ";", "}" ]
Initialize VIDEO_INFO data.
[ "Initialize", "VIDEO_INFO", "data", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/sample/src/main/java/com/pedrogomez/renderers/sample/model/RandomVideoCollectionGenerator.java#L70-L85
156,681
pedrovgs/Renderers
sample/src/main/java/com/pedrogomez/renderers/sample/model/RandomVideoCollectionGenerator.java
RandomVideoCollectionGenerator.generateRandomVideo
private Video generateRandomVideo() { Video video = new Video(); configureFavoriteStatus(video); configureLikeStatus(video); configureLiveStatus(video); configureTitleAndThumbnail(video); return video; }
java
private Video generateRandomVideo() { Video video = new Video(); configureFavoriteStatus(video); configureLikeStatus(video); configureLiveStatus(video); configureTitleAndThumbnail(video); return video; }
[ "private", "Video", "generateRandomVideo", "(", ")", "{", "Video", "video", "=", "new", "Video", "(", ")", ";", "configureFavoriteStatus", "(", "video", ")", ";", "configureLikeStatus", "(", "video", ")", ";", "configureLiveStatus", "(", "video", ")", ";", "configureTitleAndThumbnail", "(", "video", ")", ";", "return", "video", ";", "}" ]
Create a random video. @return random video.
[ "Create", "a", "random", "video", "." ]
7477fb6e3984468b32b59c8520b66afb765081ea
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/sample/src/main/java/com/pedrogomez/renderers/sample/model/RandomVideoCollectionGenerator.java#L92-L99
156,682
http4s/blaze
http/src/main/java/org/http4s/blaze/http/parser/BodyAndHeaderParser.java
BodyAndHeaderParser.parseContent
protected final ByteBuffer parseContent(ByteBuffer in) throws BaseExceptions.ParserException { if (contentComplete()) { throw new BaseExceptions.InvalidState("content already complete: " + _endOfContent); } else { switch (_endOfContent) { case UNKNOWN_CONTENT: // This makes sense only for response parsing. Requests must always have // either Content-Length or Transfer-Encoding _endOfContent = EndOfContent.EOF_CONTENT; _contentLength = Long.MAX_VALUE; // Its up to the user to limit a body size return parseContent(in); case CONTENT_LENGTH: case EOF_CONTENT: return nonChunkedContent(in); case CHUNKED_CONTENT: return chunkedContent(in); default: throw new BaseExceptions.InvalidState("not implemented: " + _endOfContent); } } }
java
protected final ByteBuffer parseContent(ByteBuffer in) throws BaseExceptions.ParserException { if (contentComplete()) { throw new BaseExceptions.InvalidState("content already complete: " + _endOfContent); } else { switch (_endOfContent) { case UNKNOWN_CONTENT: // This makes sense only for response parsing. Requests must always have // either Content-Length or Transfer-Encoding _endOfContent = EndOfContent.EOF_CONTENT; _contentLength = Long.MAX_VALUE; // Its up to the user to limit a body size return parseContent(in); case CONTENT_LENGTH: case EOF_CONTENT: return nonChunkedContent(in); case CHUNKED_CONTENT: return chunkedContent(in); default: throw new BaseExceptions.InvalidState("not implemented: " + _endOfContent); } } }
[ "protected", "final", "ByteBuffer", "parseContent", "(", "ByteBuffer", "in", ")", "throws", "BaseExceptions", ".", "ParserException", "{", "if", "(", "contentComplete", "(", ")", ")", "{", "throw", "new", "BaseExceptions", ".", "InvalidState", "(", "\"content already complete: \"", "+", "_endOfContent", ")", ";", "}", "else", "{", "switch", "(", "_endOfContent", ")", "{", "case", "UNKNOWN_CONTENT", ":", "// This makes sense only for response parsing. Requests must always have", "// either Content-Length or Transfer-Encoding", "_endOfContent", "=", "EndOfContent", ".", "EOF_CONTENT", ";", "_contentLength", "=", "Long", ".", "MAX_VALUE", ";", "// Its up to the user to limit a body size", "return", "parseContent", "(", "in", ")", ";", "case", "CONTENT_LENGTH", ":", "case", "EOF_CONTENT", ":", "return", "nonChunkedContent", "(", "in", ")", ";", "case", "CHUNKED_CONTENT", ":", "return", "chunkedContent", "(", "in", ")", ";", "default", ":", "throw", "new", "BaseExceptions", ".", "InvalidState", "(", "\"not implemented: \"", "+", "_endOfContent", ")", ";", "}", "}", "}" ]
Parses the buffer into body content @param in ByteBuffer to parse @return a ByteBuffer with the parsed body content. Buffer in may not be depleted. If more data is needed, null is returned. In the case of content complete, an empty ByteBuffer is returned. @throws BaseExceptions.ParserException
[ "Parses", "the", "buffer", "into", "body", "content" ]
699e6b478d66e5e1b426cf71c5bd47987d884b8a
https://github.com/http4s/blaze/blob/699e6b478d66e5e1b426cf71c5bd47987d884b8a/http/src/main/java/org/http4s/blaze/http/parser/BodyAndHeaderParser.java#L286-L310
156,683
http4s/blaze
http/src/main/java/org/http4s/blaze/http/parser/ParserBase.java
ParserBase.putChar
final protected void putChar(char c) { final int clen = _internalBuffer.length; if (clen == _bufferPosition) { final char[] next = new char[2 * clen + 1]; System.arraycopy(_internalBuffer, 0, next, 0, _bufferPosition); _internalBuffer = next; } _internalBuffer[_bufferPosition++] = c; }
java
final protected void putChar(char c) { final int clen = _internalBuffer.length; if (clen == _bufferPosition) { final char[] next = new char[2 * clen + 1]; System.arraycopy(_internalBuffer, 0, next, 0, _bufferPosition); _internalBuffer = next; } _internalBuffer[_bufferPosition++] = c; }
[ "final", "protected", "void", "putChar", "(", "char", "c", ")", "{", "final", "int", "clen", "=", "_internalBuffer", ".", "length", ";", "if", "(", "clen", "==", "_bufferPosition", ")", "{", "final", "char", "[", "]", "next", "=", "new", "char", "[", "2", "*", "clen", "+", "1", "]", ";", "System", ".", "arraycopy", "(", "_internalBuffer", ",", "0", ",", "next", ",", "0", ",", "_bufferPosition", ")", ";", "_internalBuffer", "=", "next", ";", "}", "_internalBuffer", "[", "_bufferPosition", "++", "]", "=", "c", ";", "}" ]
Store the char in the internal buffer
[ "Store", "the", "char", "in", "the", "internal", "buffer" ]
699e6b478d66e5e1b426cf71c5bd47987d884b8a
https://github.com/http4s/blaze/blob/699e6b478d66e5e1b426cf71c5bd47987d884b8a/http/src/main/java/org/http4s/blaze/http/parser/ParserBase.java#L40-L50
156,684
http4s/blaze
http/src/main/java/org/http4s/blaze/http/parser/ParserBase.java
ParserBase.getTrimmedString
final protected String getTrimmedString() throws BadMessage { if (_bufferPosition == 0) return ""; int start = 0; boolean quoted = false; // Look for start while (start < _bufferPosition) { final char ch = _internalBuffer[start]; if (ch == '"') { quoted = true; break; } else if (ch != HttpTokens.SPACE && ch != HttpTokens.TAB) { break; } start++; } int end = _bufferPosition; // Position is of next write // Look for end while(end > start) { final char ch = _internalBuffer[end - 1]; if (quoted) { if (ch == '"') break; else if (ch != HttpTokens.SPACE && ch != HttpTokens.TAB) { throw new BadMessage("String might not quoted correctly: '" + getString() + "'"); } } else if (ch != HttpTokens.SPACE && ch != HttpTokens.TAB) break; end--; } String str = new String(_internalBuffer, start, end - start); return str; }
java
final protected String getTrimmedString() throws BadMessage { if (_bufferPosition == 0) return ""; int start = 0; boolean quoted = false; // Look for start while (start < _bufferPosition) { final char ch = _internalBuffer[start]; if (ch == '"') { quoted = true; break; } else if (ch != HttpTokens.SPACE && ch != HttpTokens.TAB) { break; } start++; } int end = _bufferPosition; // Position is of next write // Look for end while(end > start) { final char ch = _internalBuffer[end - 1]; if (quoted) { if (ch == '"') break; else if (ch != HttpTokens.SPACE && ch != HttpTokens.TAB) { throw new BadMessage("String might not quoted correctly: '" + getString() + "'"); } } else if (ch != HttpTokens.SPACE && ch != HttpTokens.TAB) break; end--; } String str = new String(_internalBuffer, start, end - start); return str; }
[ "final", "protected", "String", "getTrimmedString", "(", ")", "throws", "BadMessage", "{", "if", "(", "_bufferPosition", "==", "0", ")", "return", "\"\"", ";", "int", "start", "=", "0", ";", "boolean", "quoted", "=", "false", ";", "// Look for start", "while", "(", "start", "<", "_bufferPosition", ")", "{", "final", "char", "ch", "=", "_internalBuffer", "[", "start", "]", ";", "if", "(", "ch", "==", "'", "'", ")", "{", "quoted", "=", "true", ";", "break", ";", "}", "else", "if", "(", "ch", "!=", "HttpTokens", ".", "SPACE", "&&", "ch", "!=", "HttpTokens", ".", "TAB", ")", "{", "break", ";", "}", "start", "++", ";", "}", "int", "end", "=", "_bufferPosition", ";", "// Position is of next write", "// Look for end", "while", "(", "end", ">", "start", ")", "{", "final", "char", "ch", "=", "_internalBuffer", "[", "end", "-", "1", "]", ";", "if", "(", "quoted", ")", "{", "if", "(", "ch", "==", "'", "'", ")", "break", ";", "else", "if", "(", "ch", "!=", "HttpTokens", ".", "SPACE", "&&", "ch", "!=", "HttpTokens", ".", "TAB", ")", "{", "throw", "new", "BadMessage", "(", "\"String might not quoted correctly: '\"", "+", "getString", "(", ")", "+", "\"'\"", ")", ";", "}", "}", "else", "if", "(", "ch", "!=", "HttpTokens", ".", "SPACE", "&&", "ch", "!=", "HttpTokens", ".", "TAB", ")", "break", ";", "end", "--", ";", "}", "String", "str", "=", "new", "String", "(", "_internalBuffer", ",", "start", ",", "end", "-", "start", ")", ";", "return", "str", ";", "}" ]
Returns the string in the buffer minus an leading or trailing whitespace or quotes
[ "Returns", "the", "string", "in", "the", "buffer", "minus", "an", "leading", "or", "trailing", "whitespace", "or", "quotes" ]
699e6b478d66e5e1b426cf71c5bd47987d884b8a
https://github.com/http4s/blaze/blob/699e6b478d66e5e1b426cf71c5bd47987d884b8a/http/src/main/java/org/http4s/blaze/http/parser/ParserBase.java#L82-L119
156,685
http4s/blaze
http/src/main/java/org/http4s/blaze/http/parser/ParserBase.java
ParserBase.next
final protected char next(final ByteBuffer buffer, boolean allow8859) throws BaseExceptions.BadMessage { if (!buffer.hasRemaining()) return HttpTokens.EMPTY_BUFF; if (_segmentByteLimit <= _segmentBytePosition) { shutdownParser(); throw new BaseExceptions.BadMessage("Request length limit exceeded: " + _segmentByteLimit); } final byte b = buffer.get(); _segmentBytePosition++; // If we ended on a CR, make sure we are if (_cr) { if (b != HttpTokens.LF) { throw new BadCharacter("Invalid sequence: LF didn't follow CR: " + b); } _cr = false; return (char)b; // must be LF } // Make sure its a valid character if (b < HttpTokens.SPACE) { if (b == HttpTokens.CR) { // Set the flag to check for _cr and just run again _cr = true; return next(buffer, allow8859); } else if (b == HttpTokens.TAB || allow8859 && b < 0) { return (char)(b & 0xff); } else if (b == HttpTokens.LF) { return (char)b; // A backend should accept a bare linefeed. http://tools.ietf.org/html/rfc2616#section-19.3 } else if (isLenient()) { return HttpTokens.REPLACEMENT; } else { shutdownParser(); throw new BadCharacter("Invalid char: '" + (char)(b & 0xff) + "', 0x" + Integer.toHexString(b)); } } // valid ascii char return (char)b; }
java
final protected char next(final ByteBuffer buffer, boolean allow8859) throws BaseExceptions.BadMessage { if (!buffer.hasRemaining()) return HttpTokens.EMPTY_BUFF; if (_segmentByteLimit <= _segmentBytePosition) { shutdownParser(); throw new BaseExceptions.BadMessage("Request length limit exceeded: " + _segmentByteLimit); } final byte b = buffer.get(); _segmentBytePosition++; // If we ended on a CR, make sure we are if (_cr) { if (b != HttpTokens.LF) { throw new BadCharacter("Invalid sequence: LF didn't follow CR: " + b); } _cr = false; return (char)b; // must be LF } // Make sure its a valid character if (b < HttpTokens.SPACE) { if (b == HttpTokens.CR) { // Set the flag to check for _cr and just run again _cr = true; return next(buffer, allow8859); } else if (b == HttpTokens.TAB || allow8859 && b < 0) { return (char)(b & 0xff); } else if (b == HttpTokens.LF) { return (char)b; // A backend should accept a bare linefeed. http://tools.ietf.org/html/rfc2616#section-19.3 } else if (isLenient()) { return HttpTokens.REPLACEMENT; } else { shutdownParser(); throw new BadCharacter("Invalid char: '" + (char)(b & 0xff) + "', 0x" + Integer.toHexString(b)); } } // valid ascii char return (char)b; }
[ "final", "protected", "char", "next", "(", "final", "ByteBuffer", "buffer", ",", "boolean", "allow8859", ")", "throws", "BaseExceptions", ".", "BadMessage", "{", "if", "(", "!", "buffer", ".", "hasRemaining", "(", ")", ")", "return", "HttpTokens", ".", "EMPTY_BUFF", ";", "if", "(", "_segmentByteLimit", "<=", "_segmentBytePosition", ")", "{", "shutdownParser", "(", ")", ";", "throw", "new", "BaseExceptions", ".", "BadMessage", "(", "\"Request length limit exceeded: \"", "+", "_segmentByteLimit", ")", ";", "}", "final", "byte", "b", "=", "buffer", ".", "get", "(", ")", ";", "_segmentBytePosition", "++", ";", "// If we ended on a CR, make sure we are", "if", "(", "_cr", ")", "{", "if", "(", "b", "!=", "HttpTokens", ".", "LF", ")", "{", "throw", "new", "BadCharacter", "(", "\"Invalid sequence: LF didn't follow CR: \"", "+", "b", ")", ";", "}", "_cr", "=", "false", ";", "return", "(", "char", ")", "b", ";", "// must be LF", "}", "// Make sure its a valid character", "if", "(", "b", "<", "HttpTokens", ".", "SPACE", ")", "{", "if", "(", "b", "==", "HttpTokens", ".", "CR", ")", "{", "// Set the flag to check for _cr and just run again", "_cr", "=", "true", ";", "return", "next", "(", "buffer", ",", "allow8859", ")", ";", "}", "else", "if", "(", "b", "==", "HttpTokens", ".", "TAB", "||", "allow8859", "&&", "b", "<", "0", ")", "{", "return", "(", "char", ")", "(", "b", "&", "0xff", ")", ";", "}", "else", "if", "(", "b", "==", "HttpTokens", ".", "LF", ")", "{", "return", "(", "char", ")", "b", ";", "// A backend should accept a bare linefeed. http://tools.ietf.org/html/rfc2616#section-19.3", "}", "else", "if", "(", "isLenient", "(", ")", ")", "{", "return", "HttpTokens", ".", "REPLACEMENT", ";", "}", "else", "{", "shutdownParser", "(", ")", ";", "throw", "new", "BadCharacter", "(", "\"Invalid char: '\"", "+", "(", "char", ")", "(", "b", "&", "0xff", ")", "+", "\"', 0x\"", "+", "Integer", ".", "toHexString", "(", "b", ")", ")", ";", "}", "}", "// valid ascii char", "return", "(", "char", ")", "b", ";", "}" ]
Removes CRs but returns LFs
[ "Removes", "CRs", "but", "returns", "LFs" ]
699e6b478d66e5e1b426cf71c5bd47987d884b8a
https://github.com/http4s/blaze/blob/699e6b478d66e5e1b426cf71c5bd47987d884b8a/http/src/main/java/org/http4s/blaze/http/parser/ParserBase.java#L140-L184
156,686
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/GanttChartView.java
GanttChartView.mapGanttBarHeight
protected int mapGanttBarHeight(int height) { switch (height) { case 0: { height = 6; break; } case 1: { height = 8; break; } case 2: { height = 10; break; } case 3: { height = 12; break; } case 4: { height = 14; break; } case 5: { height = 18; break; } case 6: { height = 24; break; } } return (height); }
java
protected int mapGanttBarHeight(int height) { switch (height) { case 0: { height = 6; break; } case 1: { height = 8; break; } case 2: { height = 10; break; } case 3: { height = 12; break; } case 4: { height = 14; break; } case 5: { height = 18; break; } case 6: { height = 24; break; } } return (height); }
[ "protected", "int", "mapGanttBarHeight", "(", "int", "height", ")", "{", "switch", "(", "height", ")", "{", "case", "0", ":", "{", "height", "=", "6", ";", "break", ";", "}", "case", "1", ":", "{", "height", "=", "8", ";", "break", ";", "}", "case", "2", ":", "{", "height", "=", "10", ";", "break", ";", "}", "case", "3", ":", "{", "height", "=", "12", ";", "break", ";", "}", "case", "4", ":", "{", "height", "=", "14", ";", "break", ";", "}", "case", "5", ":", "{", "height", "=", "18", ";", "break", ";", "}", "case", "6", ":", "{", "height", "=", "24", ";", "break", ";", "}", "}", "return", "(", "height", ")", ";", "}" ]
This method maps the encoded height of a Gantt bar to the height in pixels. @param height encoded height @return height in pixels
[ "This", "method", "maps", "the", "encoded", "height", "of", "a", "Gantt", "bar", "to", "the", "height", "in", "pixels", "." ]
143ea0e195da59cd108f13b3b06328e9542337e8
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/GanttChartView.java#L1077-L1125
156,687
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/GanttChartView.java
GanttChartView.getColumnFontStyle
protected TableFontStyle getColumnFontStyle(byte[] data, int offset, Map<Integer, FontBase> fontBases) { int uniqueID = MPPUtility.getInt(data, offset); FieldType fieldType = MPPTaskField.getInstance(MPPUtility.getShort(data, offset + 4)); Integer index = Integer.valueOf(MPPUtility.getByte(data, offset + 8)); int style = MPPUtility.getByte(data, offset + 9); ColorType color = ColorType.getInstance(MPPUtility.getByte(data, offset + 10)); int change = MPPUtility.getByte(data, offset + 12); FontBase fontBase = fontBases.get(index); boolean bold = ((style & 0x01) != 0); boolean italic = ((style & 0x02) != 0); boolean underline = ((style & 0x04) != 0); boolean boldChanged = ((change & 0x01) != 0); boolean underlineChanged = ((change & 0x02) != 0); boolean italicChanged = ((change & 0x04) != 0); boolean colorChanged = ((change & 0x08) != 0); boolean fontChanged = ((change & 0x10) != 0); boolean backgroundColorChanged = (uniqueID == -1); boolean backgroundPatternChanged = (uniqueID == -1); return (new TableFontStyle(uniqueID, fieldType, fontBase, italic, bold, underline, false, color.getColor(), Color.BLACK, BackgroundPattern.TRANSPARENT, italicChanged, boldChanged, underlineChanged, false, colorChanged, fontChanged, backgroundColorChanged, backgroundPatternChanged)); }
java
protected TableFontStyle getColumnFontStyle(byte[] data, int offset, Map<Integer, FontBase> fontBases) { int uniqueID = MPPUtility.getInt(data, offset); FieldType fieldType = MPPTaskField.getInstance(MPPUtility.getShort(data, offset + 4)); Integer index = Integer.valueOf(MPPUtility.getByte(data, offset + 8)); int style = MPPUtility.getByte(data, offset + 9); ColorType color = ColorType.getInstance(MPPUtility.getByte(data, offset + 10)); int change = MPPUtility.getByte(data, offset + 12); FontBase fontBase = fontBases.get(index); boolean bold = ((style & 0x01) != 0); boolean italic = ((style & 0x02) != 0); boolean underline = ((style & 0x04) != 0); boolean boldChanged = ((change & 0x01) != 0); boolean underlineChanged = ((change & 0x02) != 0); boolean italicChanged = ((change & 0x04) != 0); boolean colorChanged = ((change & 0x08) != 0); boolean fontChanged = ((change & 0x10) != 0); boolean backgroundColorChanged = (uniqueID == -1); boolean backgroundPatternChanged = (uniqueID == -1); return (new TableFontStyle(uniqueID, fieldType, fontBase, italic, bold, underline, false, color.getColor(), Color.BLACK, BackgroundPattern.TRANSPARENT, italicChanged, boldChanged, underlineChanged, false, colorChanged, fontChanged, backgroundColorChanged, backgroundPatternChanged)); }
[ "protected", "TableFontStyle", "getColumnFontStyle", "(", "byte", "[", "]", "data", ",", "int", "offset", ",", "Map", "<", "Integer", ",", "FontBase", ">", "fontBases", ")", "{", "int", "uniqueID", "=", "MPPUtility", ".", "getInt", "(", "data", ",", "offset", ")", ";", "FieldType", "fieldType", "=", "MPPTaskField", ".", "getInstance", "(", "MPPUtility", ".", "getShort", "(", "data", ",", "offset", "+", "4", ")", ")", ";", "Integer", "index", "=", "Integer", ".", "valueOf", "(", "MPPUtility", ".", "getByte", "(", "data", ",", "offset", "+", "8", ")", ")", ";", "int", "style", "=", "MPPUtility", ".", "getByte", "(", "data", ",", "offset", "+", "9", ")", ";", "ColorType", "color", "=", "ColorType", ".", "getInstance", "(", "MPPUtility", ".", "getByte", "(", "data", ",", "offset", "+", "10", ")", ")", ";", "int", "change", "=", "MPPUtility", ".", "getByte", "(", "data", ",", "offset", "+", "12", ")", ";", "FontBase", "fontBase", "=", "fontBases", ".", "get", "(", "index", ")", ";", "boolean", "bold", "=", "(", "(", "style", "&", "0x01", ")", "!=", "0", ")", ";", "boolean", "italic", "=", "(", "(", "style", "&", "0x02", ")", "!=", "0", ")", ";", "boolean", "underline", "=", "(", "(", "style", "&", "0x04", ")", "!=", "0", ")", ";", "boolean", "boldChanged", "=", "(", "(", "change", "&", "0x01", ")", "!=", "0", ")", ";", "boolean", "underlineChanged", "=", "(", "(", "change", "&", "0x02", ")", "!=", "0", ")", ";", "boolean", "italicChanged", "=", "(", "(", "change", "&", "0x04", ")", "!=", "0", ")", ";", "boolean", "colorChanged", "=", "(", "(", "change", "&", "0x08", ")", "!=", "0", ")", ";", "boolean", "fontChanged", "=", "(", "(", "change", "&", "0x10", ")", "!=", "0", ")", ";", "boolean", "backgroundColorChanged", "=", "(", "uniqueID", "==", "-", "1", ")", ";", "boolean", "backgroundPatternChanged", "=", "(", "uniqueID", "==", "-", "1", ")", ";", "return", "(", "new", "TableFontStyle", "(", "uniqueID", ",", "fieldType", ",", "fontBase", ",", "italic", ",", "bold", ",", "underline", ",", "false", ",", "color", ".", "getColor", "(", ")", ",", "Color", ".", "BLACK", ",", "BackgroundPattern", ".", "TRANSPARENT", ",", "italicChanged", ",", "boldChanged", ",", "underlineChanged", ",", "false", ",", "colorChanged", ",", "fontChanged", ",", "backgroundColorChanged", ",", "backgroundPatternChanged", ")", ")", ";", "}" ]
Retrieve column font details from a block of property data. @param data property data @param offset offset into property data @param fontBases map of font bases @return ColumnFontStyle instance
[ "Retrieve", "column", "font", "details", "from", "a", "block", "of", "property", "data", "." ]
143ea0e195da59cd108f13b3b06328e9542337e8
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/GanttChartView.java#L1159-L1183
156,688
joniles/mpxj
src/main/java/net/sf/mpxj/phoenix/PhoenixInputStream.java
PhoenixInputStream.prepareInputStream
private InputStream prepareInputStream(InputStream stream) throws IOException { InputStream result; BufferedInputStream bis = new BufferedInputStream(stream); readHeaderProperties(bis); if (isCompressed()) { result = new InflaterInputStream(bis); } else { result = bis; } return result; }
java
private InputStream prepareInputStream(InputStream stream) throws IOException { InputStream result; BufferedInputStream bis = new BufferedInputStream(stream); readHeaderProperties(bis); if (isCompressed()) { result = new InflaterInputStream(bis); } else { result = bis; } return result; }
[ "private", "InputStream", "prepareInputStream", "(", "InputStream", "stream", ")", "throws", "IOException", "{", "InputStream", "result", ";", "BufferedInputStream", "bis", "=", "new", "BufferedInputStream", "(", "stream", ")", ";", "readHeaderProperties", "(", "bis", ")", ";", "if", "(", "isCompressed", "(", ")", ")", "{", "result", "=", "new", "InflaterInputStream", "(", "bis", ")", ";", "}", "else", "{", "result", "=", "bis", ";", "}", "return", "result", ";", "}" ]
If the file is compressed, handle this so that the stream is ready to read. @param stream input stream @return uncompressed input stream
[ "If", "the", "file", "is", "compressed", "handle", "this", "so", "that", "the", "stream", "is", "ready", "to", "read", "." ]
143ea0e195da59cd108f13b3b06328e9542337e8
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/phoenix/PhoenixInputStream.java#L88-L102
156,689
joniles/mpxj
src/main/java/net/sf/mpxj/phoenix/PhoenixInputStream.java
PhoenixInputStream.readHeaderString
private String readHeaderString(BufferedInputStream stream) throws IOException { int bufferSize = 100; stream.mark(bufferSize); byte[] buffer = new byte[bufferSize]; stream.read(buffer); Charset charset = CharsetHelper.UTF8; String header = new String(buffer, charset); int prefixIndex = header.indexOf("PPX!!!!|"); int suffixIndex = header.indexOf("|!!!!XPP"); if (prefixIndex != 0 || suffixIndex == -1) { throw new IOException("File format not recognised"); } int skip = suffixIndex + 9; stream.reset(); stream.skip(skip); return header.substring(prefixIndex + 8, suffixIndex); }
java
private String readHeaderString(BufferedInputStream stream) throws IOException { int bufferSize = 100; stream.mark(bufferSize); byte[] buffer = new byte[bufferSize]; stream.read(buffer); Charset charset = CharsetHelper.UTF8; String header = new String(buffer, charset); int prefixIndex = header.indexOf("PPX!!!!|"); int suffixIndex = header.indexOf("|!!!!XPP"); if (prefixIndex != 0 || suffixIndex == -1) { throw new IOException("File format not recognised"); } int skip = suffixIndex + 9; stream.reset(); stream.skip(skip); return header.substring(prefixIndex + 8, suffixIndex); }
[ "private", "String", "readHeaderString", "(", "BufferedInputStream", "stream", ")", "throws", "IOException", "{", "int", "bufferSize", "=", "100", ";", "stream", ".", "mark", "(", "bufferSize", ")", ";", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "bufferSize", "]", ";", "stream", ".", "read", "(", "buffer", ")", ";", "Charset", "charset", "=", "CharsetHelper", ".", "UTF8", ";", "String", "header", "=", "new", "String", "(", "buffer", ",", "charset", ")", ";", "int", "prefixIndex", "=", "header", ".", "indexOf", "(", "\"PPX!!!!|\"", ")", ";", "int", "suffixIndex", "=", "header", ".", "indexOf", "(", "\"|!!!!XPP\"", ")", ";", "if", "(", "prefixIndex", "!=", "0", "||", "suffixIndex", "==", "-", "1", ")", "{", "throw", "new", "IOException", "(", "\"File format not recognised\"", ")", ";", "}", "int", "skip", "=", "suffixIndex", "+", "9", ";", "stream", ".", "reset", "(", ")", ";", "stream", ".", "skip", "(", "skip", ")", ";", "return", "header", ".", "substring", "(", "prefixIndex", "+", "8", ",", "suffixIndex", ")", ";", "}" ]
Read the header from the Phoenix file. @param stream input stream @return raw header data
[ "Read", "the", "header", "from", "the", "Phoenix", "file", "." ]
143ea0e195da59cd108f13b3b06328e9542337e8
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/phoenix/PhoenixInputStream.java#L110-L131
156,690
joniles/mpxj
src/main/java/net/sf/mpxj/phoenix/PhoenixInputStream.java
PhoenixInputStream.readHeaderProperties
private void readHeaderProperties(BufferedInputStream stream) throws IOException { String header = readHeaderString(stream); for (String property : header.split("\\|")) { String[] expression = property.split("="); m_properties.put(expression[0], expression[1]); } }
java
private void readHeaderProperties(BufferedInputStream stream) throws IOException { String header = readHeaderString(stream); for (String property : header.split("\\|")) { String[] expression = property.split("="); m_properties.put(expression[0], expression[1]); } }
[ "private", "void", "readHeaderProperties", "(", "BufferedInputStream", "stream", ")", "throws", "IOException", "{", "String", "header", "=", "readHeaderString", "(", "stream", ")", ";", "for", "(", "String", "property", ":", "header", ".", "split", "(", "\"\\\\|\"", ")", ")", "{", "String", "[", "]", "expression", "=", "property", ".", "split", "(", "\"=\"", ")", ";", "m_properties", ".", "put", "(", "expression", "[", "0", "]", ",", "expression", "[", "1", "]", ")", ";", "}", "}" ]
Read properties from the raw header data. @param stream input stream
[ "Read", "properties", "from", "the", "raw", "header", "data", "." ]
143ea0e195da59cd108f13b3b06328e9542337e8
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/phoenix/PhoenixInputStream.java#L138-L146
156,691
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/MPP8Reader.java
MPP8Reader.process
@Override public void process(MPPReader reader, ProjectFile file, DirectoryEntry root) throws MPXJException, IOException { try { populateMemberData(reader, file, root); processProjectProperties(); if (!reader.getReadPropertiesOnly()) { processCalendarData(); processResourceData(); processTaskData(); processConstraintData(); processAssignmentData(); if (reader.getReadPresentationData()) { processViewPropertyData(); processViewData(); processTableData(); } } } finally { clearMemberData(); } }
java
@Override public void process(MPPReader reader, ProjectFile file, DirectoryEntry root) throws MPXJException, IOException { try { populateMemberData(reader, file, root); processProjectProperties(); if (!reader.getReadPropertiesOnly()) { processCalendarData(); processResourceData(); processTaskData(); processConstraintData(); processAssignmentData(); if (reader.getReadPresentationData()) { processViewPropertyData(); processViewData(); processTableData(); } } } finally { clearMemberData(); } }
[ "@", "Override", "public", "void", "process", "(", "MPPReader", "reader", ",", "ProjectFile", "file", ",", "DirectoryEntry", "root", ")", "throws", "MPXJException", ",", "IOException", "{", "try", "{", "populateMemberData", "(", "reader", ",", "file", ",", "root", ")", ";", "processProjectProperties", "(", ")", ";", "if", "(", "!", "reader", ".", "getReadPropertiesOnly", "(", ")", ")", "{", "processCalendarData", "(", ")", ";", "processResourceData", "(", ")", ";", "processTaskData", "(", ")", ";", "processConstraintData", "(", ")", ";", "processAssignmentData", "(", ")", ";", "if", "(", "reader", ".", "getReadPresentationData", "(", ")", ")", "{", "processViewPropertyData", "(", ")", ";", "processViewData", "(", ")", ";", "processTableData", "(", ")", ";", "}", "}", "}", "finally", "{", "clearMemberData", "(", ")", ";", "}", "}" ]
This method is used to process an MPP8 file. This is the file format used by Project 98. @param reader parent file reader @param file Parent MPX file @param root Root of the POI file system. @throws MPXJException @throws IOException
[ "This", "method", "is", "used", "to", "process", "an", "MPP8", "file", ".", "This", "is", "the", "file", "format", "used", "by", "Project", "98", "." ]
143ea0e195da59cd108f13b3b06328e9542337e8
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPP8Reader.java#L88-L116
156,692
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/MPP8Reader.java
MPP8Reader.updateBaseCalendarNames
private void updateBaseCalendarNames(List<Pair<ProjectCalendar, Integer>> baseCalendars) { for (Pair<ProjectCalendar, Integer> pair : baseCalendars) { ProjectCalendar cal = pair.getFirst(); Integer baseCalendarID = pair.getSecond(); ProjectCalendar baseCal = m_calendarMap.get(baseCalendarID); if (baseCal != null) { cal.setParent(baseCal); } } }
java
private void updateBaseCalendarNames(List<Pair<ProjectCalendar, Integer>> baseCalendars) { for (Pair<ProjectCalendar, Integer> pair : baseCalendars) { ProjectCalendar cal = pair.getFirst(); Integer baseCalendarID = pair.getSecond(); ProjectCalendar baseCal = m_calendarMap.get(baseCalendarID); if (baseCal != null) { cal.setParent(baseCal); } } }
[ "private", "void", "updateBaseCalendarNames", "(", "List", "<", "Pair", "<", "ProjectCalendar", ",", "Integer", ">", ">", "baseCalendars", ")", "{", "for", "(", "Pair", "<", "ProjectCalendar", ",", "Integer", ">", "pair", ":", "baseCalendars", ")", "{", "ProjectCalendar", "cal", "=", "pair", ".", "getFirst", "(", ")", ";", "Integer", "baseCalendarID", "=", "pair", ".", "getSecond", "(", ")", ";", "ProjectCalendar", "baseCal", "=", "m_calendarMap", ".", "get", "(", "baseCalendarID", ")", ";", "if", "(", "baseCal", "!=", "null", ")", "{", "cal", ".", "setParent", "(", "baseCal", ")", ";", "}", "}", "}" ]
The way calendars are stored in an MPP8 file means that there can be forward references between the base calendar unique ID for a derived calendar, and the base calendar itself. To get around this, we initially populate the base calendar name attribute with the base calendar unique ID, and now in this method we can convert those ID values into the correct names. @param baseCalendars list of calendars and base calendar IDs
[ "The", "way", "calendars", "are", "stored", "in", "an", "MPP8", "file", "means", "that", "there", "can", "be", "forward", "references", "between", "the", "base", "calendar", "unique", "ID", "for", "a", "derived", "calendar", "and", "the", "base", "calendar", "itself", ".", "To", "get", "around", "this", "we", "initially", "populate", "the", "base", "calendar", "name", "attribute", "with", "the", "base", "calendar", "unique", "ID", "and", "now", "in", "this", "method", "we", "can", "convert", "those", "ID", "values", "into", "the", "correct", "names", "." ]
143ea0e195da59cd108f13b3b06328e9542337e8
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPP8Reader.java#L374-L386
156,693
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/MPP8Reader.java
MPP8Reader.setTaskNotes
private void setTaskNotes(Task task, byte[] data, ExtendedData taskExtData, FixDeferFix taskVarData) { String notes = taskExtData.getString(TASK_NOTES); if (notes == null && data.length == 366) { byte[] offsetData = taskVarData.getByteArray(getOffset(data, 362)); if (offsetData != null && offsetData.length >= 12) { notes = taskVarData.getString(getOffset(offsetData, 8)); // We do pick up some random stuff with this approach, and // we don't know enough about the file format to know when to ignore it // so we'll use a heuristic here to ignore anything that // doesn't look like RTF. if (notes != null && notes.indexOf('{') == -1) { notes = null; } } } if (notes != null) { if (m_reader.getPreserveNoteFormatting() == false) { notes = RtfHelper.strip(notes); } task.setNotes(notes); } }
java
private void setTaskNotes(Task task, byte[] data, ExtendedData taskExtData, FixDeferFix taskVarData) { String notes = taskExtData.getString(TASK_NOTES); if (notes == null && data.length == 366) { byte[] offsetData = taskVarData.getByteArray(getOffset(data, 362)); if (offsetData != null && offsetData.length >= 12) { notes = taskVarData.getString(getOffset(offsetData, 8)); // We do pick up some random stuff with this approach, and // we don't know enough about the file format to know when to ignore it // so we'll use a heuristic here to ignore anything that // doesn't look like RTF. if (notes != null && notes.indexOf('{') == -1) { notes = null; } } } if (notes != null) { if (m_reader.getPreserveNoteFormatting() == false) { notes = RtfHelper.strip(notes); } task.setNotes(notes); } }
[ "private", "void", "setTaskNotes", "(", "Task", "task", ",", "byte", "[", "]", "data", ",", "ExtendedData", "taskExtData", ",", "FixDeferFix", "taskVarData", ")", "{", "String", "notes", "=", "taskExtData", ".", "getString", "(", "TASK_NOTES", ")", ";", "if", "(", "notes", "==", "null", "&&", "data", ".", "length", "==", "366", ")", "{", "byte", "[", "]", "offsetData", "=", "taskVarData", ".", "getByteArray", "(", "getOffset", "(", "data", ",", "362", ")", ")", ";", "if", "(", "offsetData", "!=", "null", "&&", "offsetData", ".", "length", ">=", "12", ")", "{", "notes", "=", "taskVarData", ".", "getString", "(", "getOffset", "(", "offsetData", ",", "8", ")", ")", ";", "// We do pick up some random stuff with this approach, and ", "// we don't know enough about the file format to know when to ignore it", "// so we'll use a heuristic here to ignore anything that", "// doesn't look like RTF.", "if", "(", "notes", "!=", "null", "&&", "notes", ".", "indexOf", "(", "'", "'", ")", "==", "-", "1", ")", "{", "notes", "=", "null", ";", "}", "}", "}", "if", "(", "notes", "!=", "null", ")", "{", "if", "(", "m_reader", ".", "getPreserveNoteFormatting", "(", ")", "==", "false", ")", "{", "notes", "=", "RtfHelper", ".", "strip", "(", "notes", ")", ";", "}", "task", ".", "setNotes", "(", "notes", ")", ";", "}", "}" ]
There appear to be two ways of representing task notes in an MPP8 file. This method tries to determine which has been used. @param task task @param data task data @param taskExtData extended task data @param taskVarData task var data
[ "There", "appear", "to", "be", "two", "ways", "of", "representing", "task", "notes", "in", "an", "MPP8", "file", ".", "This", "method", "tries", "to", "determine", "which", "has", "been", "used", "." ]
143ea0e195da59cd108f13b3b06328e9542337e8
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPP8Reader.java#L742-L772
156,694
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/MPP8Reader.java
MPP8Reader.processHyperlinkData
private void processHyperlinkData(Task task, byte[] data) { if (data != null) { int offset = 12; String hyperlink; String address; String subaddress; offset += 12; hyperlink = MPPUtility.getUnicodeString(data, offset); offset += ((hyperlink.length() + 1) * 2); offset += 12; address = MPPUtility.getUnicodeString(data, offset); offset += ((address.length() + 1) * 2); offset += 12; subaddress = MPPUtility.getUnicodeString(data, offset); task.setHyperlink(hyperlink); task.setHyperlinkAddress(address); task.setHyperlinkSubAddress(subaddress); } }
java
private void processHyperlinkData(Task task, byte[] data) { if (data != null) { int offset = 12; String hyperlink; String address; String subaddress; offset += 12; hyperlink = MPPUtility.getUnicodeString(data, offset); offset += ((hyperlink.length() + 1) * 2); offset += 12; address = MPPUtility.getUnicodeString(data, offset); offset += ((address.length() + 1) * 2); offset += 12; subaddress = MPPUtility.getUnicodeString(data, offset); task.setHyperlink(hyperlink); task.setHyperlinkAddress(address); task.setHyperlinkSubAddress(subaddress); } }
[ "private", "void", "processHyperlinkData", "(", "Task", "task", ",", "byte", "[", "]", "data", ")", "{", "if", "(", "data", "!=", "null", ")", "{", "int", "offset", "=", "12", ";", "String", "hyperlink", ";", "String", "address", ";", "String", "subaddress", ";", "offset", "+=", "12", ";", "hyperlink", "=", "MPPUtility", ".", "getUnicodeString", "(", "data", ",", "offset", ")", ";", "offset", "+=", "(", "(", "hyperlink", ".", "length", "(", ")", "+", "1", ")", "*", "2", ")", ";", "offset", "+=", "12", ";", "address", "=", "MPPUtility", ".", "getUnicodeString", "(", "data", ",", "offset", ")", ";", "offset", "+=", "(", "(", "address", ".", "length", "(", ")", "+", "1", ")", "*", "2", ")", ";", "offset", "+=", "12", ";", "subaddress", "=", "MPPUtility", ".", "getUnicodeString", "(", "data", ",", "offset", ")", ";", "task", ".", "setHyperlink", "(", "hyperlink", ")", ";", "task", ".", "setHyperlinkAddress", "(", "address", ")", ";", "task", ".", "setHyperlinkSubAddress", "(", "subaddress", ")", ";", "}", "}" ]
This method is used to extract the task hyperlink attributes from a block of data and call the appropriate modifier methods to configure the specified task object. @param task task instance @param data hyperlink data block
[ "This", "method", "is", "used", "to", "extract", "the", "task", "hyperlink", "attributes", "from", "a", "block", "of", "data", "and", "call", "the", "appropriate", "modifier", "methods", "to", "configure", "the", "specified", "task", "object", "." ]
143ea0e195da59cd108f13b3b06328e9542337e8
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPP8Reader.java#L782-L806
156,695
joniles/mpxj
src/main/java/net/sf/mpxj/sample/PrimaveraConvert.java
PrimaveraConvert.process
public void process(String driverClass, String connectionString, String projectID, String outputFile) throws Exception { System.out.println("Reading Primavera database started."); Class.forName(driverClass); Properties props = new Properties(); // // This is not a very robust way to detect that we're working with SQLlite... // If you are trying to grab data from // a standalone P6 using SQLite, the SQLite JDBC driver needs this property // in order to correctly parse timestamps. // if (driverClass.equals("org.sqlite.JDBC")) { props.setProperty("date_string_format", "yyyy-MM-dd HH:mm:ss"); } Connection c = DriverManager.getConnection(connectionString, props); PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader(); reader.setConnection(c); processProject(reader, Integer.parseInt(projectID), outputFile); }
java
public void process(String driverClass, String connectionString, String projectID, String outputFile) throws Exception { System.out.println("Reading Primavera database started."); Class.forName(driverClass); Properties props = new Properties(); // // This is not a very robust way to detect that we're working with SQLlite... // If you are trying to grab data from // a standalone P6 using SQLite, the SQLite JDBC driver needs this property // in order to correctly parse timestamps. // if (driverClass.equals("org.sqlite.JDBC")) { props.setProperty("date_string_format", "yyyy-MM-dd HH:mm:ss"); } Connection c = DriverManager.getConnection(connectionString, props); PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader(); reader.setConnection(c); processProject(reader, Integer.parseInt(projectID), outputFile); }
[ "public", "void", "process", "(", "String", "driverClass", ",", "String", "connectionString", ",", "String", "projectID", ",", "String", "outputFile", ")", "throws", "Exception", "{", "System", ".", "out", ".", "println", "(", "\"Reading Primavera database started.\"", ")", ";", "Class", ".", "forName", "(", "driverClass", ")", ";", "Properties", "props", "=", "new", "Properties", "(", ")", ";", "//", "// This is not a very robust way to detect that we're working with SQLlite...", "// If you are trying to grab data from", "// a standalone P6 using SQLite, the SQLite JDBC driver needs this property", "// in order to correctly parse timestamps.", "//", "if", "(", "driverClass", ".", "equals", "(", "\"org.sqlite.JDBC\"", ")", ")", "{", "props", ".", "setProperty", "(", "\"date_string_format\"", ",", "\"yyyy-MM-dd HH:mm:ss\"", ")", ";", "}", "Connection", "c", "=", "DriverManager", ".", "getConnection", "(", "connectionString", ",", "props", ")", ";", "PrimaveraDatabaseReader", "reader", "=", "new", "PrimaveraDatabaseReader", "(", ")", ";", "reader", ".", "setConnection", "(", "c", ")", ";", "processProject", "(", "reader", ",", "Integer", ".", "parseInt", "(", "projectID", ")", ",", "outputFile", ")", ";", "}" ]
Extract Primavera project data and export in another format. @param driverClass JDBC driver class name @param connectionString JDBC connection string @param projectID project ID @param outputFile output file @throws Exception
[ "Extract", "Primavera", "project", "data", "and", "export", "in", "another", "format", "." ]
143ea0e195da59cd108f13b3b06328e9542337e8
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/sample/PrimaveraConvert.java#L82-L105
156,696
joniles/mpxj
src/main/java/net/sf/mpxj/sample/PrimaveraConvert.java
PrimaveraConvert.processProject
private void processProject(PrimaveraDatabaseReader reader, int projectID, String outputFile) throws Exception { long start = System.currentTimeMillis(); reader.setProjectID(projectID); ProjectFile projectFile = reader.read(); long elapsed = System.currentTimeMillis() - start; System.out.println("Reading database completed in " + elapsed + "ms."); System.out.println("Writing output file started."); start = System.currentTimeMillis(); ProjectWriter writer = ProjectWriterUtility.getProjectWriter(outputFile); writer.write(projectFile, outputFile); elapsed = System.currentTimeMillis() - start; System.out.println("Writing output completed in " + elapsed + "ms."); }
java
private void processProject(PrimaveraDatabaseReader reader, int projectID, String outputFile) throws Exception { long start = System.currentTimeMillis(); reader.setProjectID(projectID); ProjectFile projectFile = reader.read(); long elapsed = System.currentTimeMillis() - start; System.out.println("Reading database completed in " + elapsed + "ms."); System.out.println("Writing output file started."); start = System.currentTimeMillis(); ProjectWriter writer = ProjectWriterUtility.getProjectWriter(outputFile); writer.write(projectFile, outputFile); elapsed = System.currentTimeMillis() - start; System.out.println("Writing output completed in " + elapsed + "ms."); }
[ "private", "void", "processProject", "(", "PrimaveraDatabaseReader", "reader", ",", "int", "projectID", ",", "String", "outputFile", ")", "throws", "Exception", "{", "long", "start", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "reader", ".", "setProjectID", "(", "projectID", ")", ";", "ProjectFile", "projectFile", "=", "reader", ".", "read", "(", ")", ";", "long", "elapsed", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "start", ";", "System", ".", "out", ".", "println", "(", "\"Reading database completed in \"", "+", "elapsed", "+", "\"ms.\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"Writing output file started.\"", ")", ";", "start", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "ProjectWriter", "writer", "=", "ProjectWriterUtility", ".", "getProjectWriter", "(", "outputFile", ")", ";", "writer", ".", "write", "(", "projectFile", ",", "outputFile", ")", ";", "elapsed", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "start", ";", "System", ".", "out", ".", "println", "(", "\"Writing output completed in \"", "+", "elapsed", "+", "\"ms.\"", ")", ";", "}" ]
Process a single project. @param reader Primavera reader @param projectID required project ID @param outputFile output file name
[ "Process", "a", "single", "project", "." ]
143ea0e195da59cd108f13b3b06328e9542337e8
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/sample/PrimaveraConvert.java#L114-L128
156,697
joniles/mpxj
src/main/java/net/sf/mpxj/common/MPPResourceField.java
MPPResourceField.getInstance
public static ResourceField getInstance(int value) { ResourceField result = null; if (value >= 0 && value < FIELD_ARRAY.length) { result = FIELD_ARRAY[value]; } else { if ((value & 0x8000) != 0) { int baseValue = ResourceField.ENTERPRISE_CUSTOM_FIELD1.getValue(); int id = baseValue + (value & 0xFFF); result = ResourceField.getInstance(id); } } return (result); }
java
public static ResourceField getInstance(int value) { ResourceField result = null; if (value >= 0 && value < FIELD_ARRAY.length) { result = FIELD_ARRAY[value]; } else { if ((value & 0x8000) != 0) { int baseValue = ResourceField.ENTERPRISE_CUSTOM_FIELD1.getValue(); int id = baseValue + (value & 0xFFF); result = ResourceField.getInstance(id); } } return (result); }
[ "public", "static", "ResourceField", "getInstance", "(", "int", "value", ")", "{", "ResourceField", "result", "=", "null", ";", "if", "(", "value", ">=", "0", "&&", "value", "<", "FIELD_ARRAY", ".", "length", ")", "{", "result", "=", "FIELD_ARRAY", "[", "value", "]", ";", "}", "else", "{", "if", "(", "(", "value", "&", "0x8000", ")", "!=", "0", ")", "{", "int", "baseValue", "=", "ResourceField", ".", "ENTERPRISE_CUSTOM_FIELD1", ".", "getValue", "(", ")", ";", "int", "id", "=", "baseValue", "+", "(", "value", "&", "0xFFF", ")", ";", "result", "=", "ResourceField", ".", "getInstance", "(", "id", ")", ";", "}", "}", "return", "(", "result", ")", ";", "}" ]
Retrieve an instance of the ResourceField class based on the data read from an MS Project file. @param value value from an MS Project file @return ResourceField instance
[ "Retrieve", "an", "instance", "of", "the", "ResourceField", "class", "based", "on", "the", "data", "read", "from", "an", "MS", "Project", "file", "." ]
143ea0e195da59cd108f13b3b06328e9542337e8
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/common/MPPResourceField.java#L44-L63
156,698
joniles/mpxj
src/main/java/net/sf/mpxj/mpx/TaskModel.java
TaskModel.update
public void update(Record record, boolean isText) throws MPXJException { int length = record.getLength(); for (int i = 0; i < length; i++) { if (isText == true) { add(getTaskCode(record.getString(i))); } else { add(record.getInteger(i).intValue()); } } }
java
public void update(Record record, boolean isText) throws MPXJException { int length = record.getLength(); for (int i = 0; i < length; i++) { if (isText == true) { add(getTaskCode(record.getString(i))); } else { add(record.getInteger(i).intValue()); } } }
[ "public", "void", "update", "(", "Record", "record", ",", "boolean", "isText", ")", "throws", "MPXJException", "{", "int", "length", "=", "record", ".", "getLength", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "isText", "==", "true", ")", "{", "add", "(", "getTaskCode", "(", "record", ".", "getString", "(", "i", ")", ")", ")", ";", "}", "else", "{", "add", "(", "record", ".", "getInteger", "(", "i", ")", ".", "intValue", "(", ")", ")", ";", "}", "}", "}" ]
This method populates the task model from data read from an MPX file. @param record data read from an MPX file @param isText flag indicating whether the textual or numeric data is being supplied
[ "This", "method", "populates", "the", "task", "model", "from", "data", "read", "from", "an", "MPX", "file", "." ]
143ea0e195da59cd108f13b3b06328e9542337e8
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/TaskModel.java#L99-L114
156,699
joniles/mpxj
src/main/java/net/sf/mpxj/mpx/TaskModel.java
TaskModel.add
private void add(int field) { if (field < m_flags.length) { if (m_flags[field] == false) { m_flags[field] = true; m_fields[m_count] = field; ++m_count; } } }
java
private void add(int field) { if (field < m_flags.length) { if (m_flags[field] == false) { m_flags[field] = true; m_fields[m_count] = field; ++m_count; } } }
[ "private", "void", "add", "(", "int", "field", ")", "{", "if", "(", "field", "<", "m_flags", ".", "length", ")", "{", "if", "(", "m_flags", "[", "field", "]", "==", "false", ")", "{", "m_flags", "[", "field", "]", "=", "true", ";", "m_fields", "[", "m_count", "]", "=", "field", ";", "++", "m_count", ";", "}", "}", "}" ]
This method is called from the task class each time an attribute is added, ensuring that all of the attributes present in each task record are present in the resource model. @param field field identifier
[ "This", "method", "is", "called", "from", "the", "task", "class", "each", "time", "an", "attribute", "is", "added", "ensuring", "that", "all", "of", "the", "attributes", "present", "in", "each", "task", "record", "are", "present", "in", "the", "resource", "model", "." ]
143ea0e195da59cd108f13b3b06328e9542337e8
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/TaskModel.java#L123-L134