idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
6,900
protected synchronized Class loadClass ( String name , boolean resolve ) throws ClassNotFoundException { if ( inDefine ) { if ( name . equals ( REFLECTOR ) ) return Reflector . class ; } return super . loadClass ( name , resolve ) ; }
Loads a class per name . Unlike a normal loadClass this version behaves different during a class definition . In that case it checks if the class we want to load is Reflector and returns class if the check is successful . If it is not during a class definition it just calls the super class version of loadClass .
6,901
public synchronized Class defineClass ( String name , byte [ ] bytecode , ProtectionDomain domain ) { inDefine = true ; Class c = defineClass ( name , bytecode , 0 , bytecode . length , domain ) ; loadedClasses . put ( name , c ) ; resolveClass ( c ) ; inDefine = false ; return c ; }
helper method to define Reflector classes .
6,902
public static boolean isBridgeMethod ( Method someMethod ) { TraitBridge annotation = someMethod . getAnnotation ( TraitBridge . class ) ; return annotation != null ; }
Reflection API to indicate whether some method is a bridge method to the default implementation of a trait .
6,903
public static String [ ] decomposeSuperCallName ( String origName ) { if ( origName . contains ( SUPER_TRAIT_METHOD_PREFIX ) ) { int endIndex = origName . indexOf ( SUPER_TRAIT_METHOD_PREFIX ) ; String tName = origName . substring ( 0 , endIndex ) . replace ( '_' , '.' ) . replace ( ".." , "_" ) ; String fName = origName . substring ( endIndex + SUPER_TRAIT_METHOD_PREFIX . length ( ) ) ; return new String [ ] { tName , fName } ; } return null ; }
Returns the name of a method without the super trait specific prefix . If the method name doesn t correspond to a super trait method call the result will be null .
6,904
public static LinkedHashSet < ClassNode > collectSelfTypes ( ClassNode receiver , LinkedHashSet < ClassNode > selfTypes ) { return collectSelfTypes ( receiver , selfTypes , true , true ) ; }
Collects all the self types that a type should extend or implement given the traits is implements . Collects from interfaces and superclasses too .
6,905
public static LinkedHashSet < ClassNode > collectSelfTypes ( ClassNode receiver , LinkedHashSet < ClassNode > selfTypes , boolean checkInterfaces , boolean checkSuper ) { if ( Traits . isTrait ( receiver ) ) { List < AnnotationNode > annotations = receiver . getAnnotations ( SELFTYPE_CLASSNODE ) ; for ( AnnotationNode annotation : annotations ) { Expression value = annotation . getMember ( "value" ) ; if ( value instanceof ClassExpression ) { selfTypes . add ( value . getType ( ) ) ; } else if ( value instanceof ListExpression ) { List < Expression > expressions = ( ( ListExpression ) value ) . getExpressions ( ) ; for ( Expression expression : expressions ) { if ( expression instanceof ClassExpression ) { selfTypes . add ( expression . getType ( ) ) ; } } } } } if ( checkInterfaces ) { ClassNode [ ] interfaces = receiver . getInterfaces ( ) ; for ( ClassNode anInterface : interfaces ) { collectSelfTypes ( anInterface , selfTypes , true , checkSuper ) ; } } if ( checkSuper ) { ClassNode superClass = receiver . getSuperClass ( ) ; if ( superClass != null ) { collectSelfTypes ( superClass , selfTypes , checkInterfaces , true ) ; } } return selfTypes ; }
Collects all the self types that a type should extend or implement given the traits is implements .
6,906
public void write ( PrintWriter output , Janitor janitor ) { String name = source . getName ( ) ; int line = getCause ( ) . getStartLine ( ) ; int column = getCause ( ) . getStartColumn ( ) ; String sample = source . getSample ( line , column , janitor ) ; output . print ( name + ": " + line + ": " + getCause ( ) . getMessage ( ) ) ; if ( sample != null ) { output . println ( ) ; output . print ( sample ) ; output . println ( ) ; } }
Writes out a nicely formatted summary of the syntax error .
6,907
public static boolean chooseMathMethod ( Selector info , MetaMethod metaMethod ) { Map < MethodType , MethodHandle > xmap = methods . get ( info . name ) ; if ( xmap == null ) return false ; MethodType type = replaceWithMoreSpecificType ( info . args , info . targetType ) ; type = widenOperators ( type ) ; MethodHandle handle = xmap . get ( type ) ; if ( handle == null ) return false ; info . handle = handle ; return true ; }
Choose a method to replace the originally chosen metaMethod to have a more efficient call path .
6,908
private static MethodType widenOperators ( MethodType mt ) { if ( mt . parameterCount ( ) == 2 ) { Class leftType = mt . parameterType ( 0 ) ; Class rightType = mt . parameterType ( 1 ) ; if ( isIntCategory ( leftType ) && isIntCategory ( rightType ) ) return IIV ; if ( isLongCategory ( leftType ) && isLongCategory ( rightType ) ) return LLV ; if ( isBigDecCategory ( leftType ) && isBigDecCategory ( rightType ) ) return GGV ; if ( isDoubleCategory ( leftType ) && isDoubleCategory ( rightType ) ) return DDV ; return OOV ; } else if ( mt . parameterCount ( ) == 1 ) { Class leftType = mt . parameterType ( 0 ) ; if ( isIntCategory ( leftType ) ) return IV ; if ( isLongCategory ( leftType ) ) return LV ; if ( isBigDecCategory ( leftType ) ) return GV ; if ( isDoubleCategory ( leftType ) ) return DV ; } return mt ; }
Widens the operators . For math operations like a + b we generally execute them using a conversion to certain types . If a for example is an int and b a byte we do the operation using integer math . This method gives a simplified MethodType that contains the two operators with this widening according to Groovy rules applied . That means both parameters in the MethodType will have the same type .
6,909
public void checkParameters ( Class [ ] arguments ) { if ( ! isValidMethod ( arguments ) ) { throw new IllegalArgumentException ( "Parameters to method: " + getName ( ) + " do not match types: " + InvokerHelper . toString ( getParameterTypes ( ) ) + " for arguments: " + InvokerHelper . toString ( arguments ) ) ; } }
Checks that the given parameters are valid to call this method
6,910
public boolean isMethod ( MetaMethod method ) { return getName ( ) . equals ( method . getName ( ) ) && getModifiers ( ) == method . getModifiers ( ) && getReturnType ( ) . equals ( method . getReturnType ( ) ) && equal ( getParameterTypes ( ) , method . getParameterTypes ( ) ) ; }
Returns true if this this metamethod represents the same method as the argument .
6,911
private static boolean compatibleModifiers ( int modifiersA , int modifiersB ) { int mask = Modifier . PRIVATE | Modifier . PROTECTED | Modifier . PUBLIC | Modifier . STATIC ; return ( modifiersA & mask ) == ( modifiersB & mask ) ; }
Checks the compatibility between two modifier masks . Checks that they are equal with regards to access and static modifier .
6,912
public synchronized String getSignature ( ) { if ( signature == null ) { CachedClass [ ] parameters = getParameterTypes ( ) ; final String name = getName ( ) ; StringBuilder buf = new StringBuilder ( name . length ( ) + parameters . length * 10 ) ; buf . append ( getReturnType ( ) . getName ( ) ) ; buf . append ( ' ' ) ; buf . append ( name ) ; buf . append ( '(' ) ; for ( int i = 0 ; i < parameters . length ; i ++ ) { if ( i > 0 ) { buf . append ( ", " ) ; } buf . append ( parameters [ i ] . getName ( ) ) ; } buf . append ( ')' ) ; signature = buf . toString ( ) ; } return signature ; }
Returns the signature of this method
6,913
public final RuntimeException processDoMethodInvokeException ( Exception e , Object object , Object [ ] argumentArray ) { if ( e instanceof RuntimeException ) return ( RuntimeException ) e ; return MetaClassHelper . createExceptionText ( "failed to invoke method: " , this , object , argumentArray , e , true ) ; }
This method is called when an exception occurs while invoking this method .
6,914
public Object doMethodInvoke ( Object object , Object [ ] argumentArray ) { argumentArray = coerceArgumentsToClasses ( argumentArray ) ; try { return invoke ( object , argumentArray ) ; } catch ( Exception e ) { throw processDoMethodInvokeException ( e , object , argumentArray ) ; } }
Invokes the method this object represents . This method is not final but it should be overloaded very carefully and only by generated methods there is no guarantee that it will be called
6,915
private void checkForConstructorWithCSButClassWithout ( MethodNode node ) { if ( ! ( node instanceof ConstructorNode ) ) return ; Object meta = node . getNodeMetaData ( STATIC_COMPILE_NODE ) ; if ( ! Boolean . TRUE . equals ( meta ) ) return ; ClassNode clz = typeCheckingContext . getEnclosingClassNode ( ) ; meta = clz . getNodeMetaData ( STATIC_COMPILE_NODE ) ; if ( Boolean . TRUE . equals ( meta ) ) return ; if ( clz . getObjectInitializerStatements ( ) . isEmpty ( ) && clz . getFields ( ) . isEmpty ( ) && clz . getProperties ( ) . isEmpty ( ) ) { return ; } addStaticTypeError ( "Cannot statically compile constructor implicitly including non static elements from object initializers, properties or fields." , node ) ; }
If we are in a constructor that is static compiled but in a class that is not it may happen that init code from object initializers fields or properties is added into the constructor code . The backend assumes a purely static constructor so it may fail if it encounters dynamic code here . Thus we make this kind of code fail
6,916
public static boolean isEnumSubclass ( Object value ) { if ( value instanceof Class ) { Class superclass = ( ( Class ) value ) . getSuperclass ( ) ; while ( superclass != null ) { if ( superclass . getName ( ) . equals ( "java.lang.Enum" ) ) { return true ; } superclass = superclass . getSuperclass ( ) ; } } return false ; }
Determines whether the value object is a Class object representing a subclass of java . lang . Enum . Uses class name check to avoid breaking on pre - Java 5 JREs .
6,917
public static List primitiveArrayToList ( Object array ) { int size = Array . getLength ( array ) ; List list = new ArrayList ( size ) ; for ( int i = 0 ; i < size ; i ++ ) { Object item = Array . get ( array , i ) ; if ( item != null && item . getClass ( ) . isArray ( ) && item . getClass ( ) . getComponentType ( ) . isPrimitive ( ) ) { item = primitiveArrayToList ( item ) ; } list . add ( item ) ; } return list ; }
Allows conversion of arrays into a mutable List
6,918
public void println ( String text ) { try { if ( autoIndent ) printIndent ( ) ; out . write ( text ) ; println ( ) ; } catch ( IOException ioe ) { throw new GroovyRuntimeException ( ioe ) ; } }
Prints a string followed by an end of line character .
6,919
public void printIndent ( ) { for ( int i = 0 ; i < indentLevel ; i ++ ) { try { out . write ( indent ) ; } catch ( IOException ioe ) { throw new GroovyRuntimeException ( ioe ) ; } } }
Prints the current indent level .
6,920
public static Map < String , MethodNode > getDeclaredMethodsFromSuper ( ClassNode cNode ) { ClassNode parent = cNode . getSuperClass ( ) ; if ( parent == null ) { return new HashMap < String , MethodNode > ( ) ; } return parent . getDeclaredMethodsMap ( ) ; }
Add methods from the super class .
6,921
public static void addDeclaredMethodsFromInterfaces ( ClassNode cNode , Map < String , MethodNode > methodsMap ) { for ( ClassNode iface : cNode . getInterfaces ( ) ) { Map < String , MethodNode > ifaceMethodsMap = iface . getDeclaredMethodsMap ( ) ; for ( Map . Entry < String , MethodNode > entry : ifaceMethodsMap . entrySet ( ) ) { String methSig = entry . getKey ( ) ; if ( ! methodsMap . containsKey ( methSig ) ) { methodsMap . put ( methSig , entry . getValue ( ) ) ; } } } }
Add in methods from all interfaces . Existing entries in the methods map take precedence . Methods from interfaces visited early take precedence over later ones .
6,922
public static Map < String , MethodNode > getDeclaredMethodsFromInterfaces ( ClassNode cNode ) { Map < String , MethodNode > result = new HashMap < String , MethodNode > ( ) ; ClassNode [ ] interfaces = cNode . getInterfaces ( ) ; for ( ClassNode iface : interfaces ) { result . putAll ( iface . getDeclaredMethodsMap ( ) ) ; } return result ; }
Get methods from all interfaces . Methods from interfaces visited early will be overwritten by later ones .
6,923
public static void addDeclaredMethodsFromAllInterfaces ( ClassNode cNode , Map < String , MethodNode > methodsMap ) { List cnInterfaces = Arrays . asList ( cNode . getInterfaces ( ) ) ; ClassNode parent = cNode . getSuperClass ( ) ; while ( parent != null && ! parent . equals ( ClassHelper . OBJECT_TYPE ) ) { ClassNode [ ] interfaces = parent . getInterfaces ( ) ; for ( ClassNode iface : interfaces ) { if ( ! cnInterfaces . contains ( iface ) ) { methodsMap . putAll ( iface . getDeclaredMethodsMap ( ) ) ; } } parent = parent . getSuperClass ( ) ; } }
Adds methods from interfaces and parent interfaces . Existing entries in the methods map take precedence . Methods from interfaces visited early take precedence over later ones .
6,924
public static boolean hasPossibleStaticMethod ( ClassNode cNode , String name , Expression arguments , boolean trySpread ) { int count = 0 ; boolean foundSpread = false ; if ( arguments instanceof TupleExpression ) { TupleExpression tuple = ( TupleExpression ) arguments ; for ( Expression arg : tuple . getExpressions ( ) ) { if ( arg instanceof SpreadExpression ) { foundSpread = true ; } else { count ++ ; } } } else if ( arguments instanceof MapExpression ) { count = 1 ; } for ( MethodNode method : cNode . getMethods ( name ) ) { if ( method . isStatic ( ) ) { Parameter [ ] parameters = method . getParameters ( ) ; if ( trySpread && foundSpread && parameters . length >= count ) return true ; if ( parameters . length == count ) return true ; if ( parameters . length > 0 && parameters [ parameters . length - 1 ] . getType ( ) . isArray ( ) ) { if ( count >= parameters . length - 1 ) return true ; if ( trySpread && foundSpread ) return true ; } int nonDefaultParameters = 0 ; for ( Parameter parameter : parameters ) { if ( ! parameter . hasInitialExpression ( ) ) { nonDefaultParameters ++ ; } } if ( count < parameters . length && nonDefaultParameters <= count ) { return true ; } } } return false ; }
Returns true if the given method has a possibly matching static method with the given name and arguments . Handles default arguments and optionally spread expressions .
6,925
public static boolean hasPossibleStaticProperty ( ClassNode cNode , String methodName ) { if ( ! methodName . startsWith ( "get" ) && ! methodName . startsWith ( "is" ) ) { return false ; } String propName = getPropNameForAccessor ( methodName ) ; PropertyNode pNode = getStaticProperty ( cNode , propName ) ; return pNode != null && ( methodName . startsWith ( "get" ) || boolean_TYPE . equals ( pNode . getType ( ) ) ) ; }
Return true if we have a static accessor
6,926
public static boolean isValidAccessorName ( String accessorName ) { if ( accessorName . startsWith ( "get" ) || accessorName . startsWith ( "is" ) || accessorName . startsWith ( "set" ) ) { int prefixLength = accessorName . startsWith ( "is" ) ? 2 : 3 ; return accessorName . length ( ) > prefixLength ; } ; return false ; }
Detect whether the given accessor name starts with get set or is followed by at least one character .
6,927
public static PropertyNode getStaticProperty ( ClassNode cNode , String propName ) { ClassNode classNode = cNode ; while ( classNode != null ) { for ( PropertyNode pn : classNode . getProperties ( ) ) { if ( pn . getName ( ) . equals ( propName ) && pn . isStatic ( ) ) return pn ; } classNode = classNode . getSuperClass ( ) ; } return null ; }
Detect whether a static property with the given name is within the class or a super class .
6,928
public static boolean samePackageName ( ClassNode first , ClassNode second ) { return Objects . equals ( first . getPackageName ( ) , second . getPackageName ( ) ) ; }
Determine if the given ClassNode values have the same package name .
6,929
private String computeScriptName ( ) { if ( srcFile != null ) { return srcFile . getAbsolutePath ( ) ; } else { String name = PREFIX ; if ( getLocation ( ) . getFileName ( ) . length ( ) > 0 ) name += getLocation ( ) . getFileName ( ) . replaceAll ( "[^\\w_\\.]" , "_" ) . replaceAll ( "[\\.]" , "_dot_" ) ; else name += SUFFIX ; return name ; } }
Try to build a script name for the script of the groovy task to have an helpful value in stack traces in case of exception
6,930
protected void printResults ( PrintStream out ) { log . debug ( "printResults()" ) ; StringBuilder line = new StringBuilder ( ) ; out . println ( line ) ; out . println ( ) ; }
print any results in the statement .
6,931
public void swapTwoChildren ( GroovySourceAST t ) { GroovySourceAST a = ( GroovySourceAST ) t . getFirstChild ( ) ; GroovySourceAST b = ( GroovySourceAST ) a . getNextSibling ( ) ; t . setFirstChild ( b ) ; a . setNextSibling ( null ) ; b . setNextSibling ( a ) ; }
To swap two children of node t ...
6,932
public static Throwable extractRootCause ( Throwable t ) { Throwable result = t ; while ( result . getCause ( ) != null ) { result = result . getCause ( ) ; } return result ; }
Extracts the root cause of the exception no matter how nested it is
6,933
public String getMethodAsString ( ) { if ( ! ( method instanceof ConstantExpression ) ) return null ; ConstantExpression constant = ( ConstantExpression ) method ; return constant . getText ( ) ; }
This method returns the method name as String if it is no dynamic calculated method name but a constant .
6,934
public void write ( int b ) throws IOException { Boolean result = ( Boolean ) callback . call ( consoleId . get ( ) , String . valueOf ( ( char ) b ) ) ; if ( result ) { out . write ( b ) ; } }
Intercepts output - single characters
6,935
public void pushEnclosingMethodCall ( Expression call ) { if ( call instanceof MethodCallExpression || call instanceof StaticMethodCallExpression ) { enclosingMethodCalls . addFirst ( call ) ; } else { throw new IllegalArgumentException ( "Expression must be a method call or a static method call" ) ; } }
Pushes a method call into the method call stack .
6,936
public static BinaryExpression cmpX ( Expression lhv , Expression rhv ) { return new BinaryExpression ( lhv , CMP , rhv ) ; }
Build a binary expression that compares two values
6,937
public static String convertASTToSource ( ReaderSource readerSource , ASTNode expression ) throws Exception { if ( expression == null ) throw new IllegalArgumentException ( "Null: expression" ) ; StringBuilder result = new StringBuilder ( ) ; for ( int x = expression . getLineNumber ( ) ; x <= expression . getLastLineNumber ( ) ; x ++ ) { String line = readerSource . getLine ( x , null ) ; if ( line == null ) { throw new Exception ( "Error calculating source code for expression. Trying to read line " + x + " from " + readerSource . getClass ( ) ) ; } if ( x == expression . getLastLineNumber ( ) ) { line = line . substring ( 0 , expression . getLastColumnNumber ( ) - 1 ) ; } if ( x == expression . getLineNumber ( ) ) { line = line . substring ( expression . getColumnNumber ( ) - 1 ) ; } result . append ( line ) . append ( '\n' ) ; } String source = result . toString ( ) . trim ( ) ; return source ; }
Converts an expression into the String source . Only some specific expressions like closure expression support this .
6,938
public Object getProperty ( Class aClass , Object object , String property , boolean b , boolean b1 ) { if ( null == interceptor ) { return super . getProperty ( aClass , object , property , b , b1 ) ; } if ( interceptor instanceof PropertyAccessInterceptor ) { PropertyAccessInterceptor pae = ( PropertyAccessInterceptor ) interceptor ; Object result = pae . beforeGet ( object , property ) ; if ( interceptor . doInvoke ( ) ) { result = super . getProperty ( aClass , object , property , b , b1 ) ; } return result ; } return super . getProperty ( aClass , object , property , b , b1 ) ; }
Interceptors the call to getProperty if a PropertyAccessInterceptor is available
6,939
public void setProperty ( Class aClass , Object object , String property , Object newValue , boolean b , boolean b1 ) { if ( null == interceptor ) { super . setProperty ( aClass , object , property , newValue , b , b1 ) ; } if ( interceptor instanceof PropertyAccessInterceptor ) { PropertyAccessInterceptor pae = ( PropertyAccessInterceptor ) interceptor ; pae . beforeSet ( object , property , newValue ) ; if ( interceptor . doInvoke ( ) ) { super . setProperty ( aClass , object , property , newValue , b , b1 ) ; } } else { super . setProperty ( aClass , object , property , newValue , b , b1 ) ; } }
Interceptors the call to a property setter if a PropertyAccessInterceptor is available
6,940
public void includeGroovy ( String templatePath ) throws IOException , ClassNotFoundException { URL resource = engine . resolveTemplate ( templatePath ) ; engine . createTypeCheckedModelTemplate ( resource , modelTypes ) . make ( model ) . writeTo ( out ) ; }
Includes another template inside this template .
6,941
public void includeEscaped ( String templatePath ) throws IOException { URL resource = engine . resolveTemplate ( templatePath ) ; yield ( ResourceGroovyMethods . getText ( resource , engine . getCompilerConfiguration ( ) . getSourceEncoding ( ) ) ) ; }
Includes contents of another file not as a template but as escaped text .
6,942
public void includeUnescaped ( String templatePath ) throws IOException { URL resource = engine . resolveTemplate ( templatePath ) ; yieldUnescaped ( ResourceGroovyMethods . getText ( resource , engine . getCompilerConfiguration ( ) . getSourceEncoding ( ) ) ) ; }
Includes contents of another file not as a template but as unescaped text .
6,943
public Object layout ( Map model , String templateName , boolean inheritModel ) throws IOException , ClassNotFoundException { Map submodel = inheritModel ? forkModel ( model ) : model ; URL resource = engine . resolveTemplate ( templateName ) ; engine . createTypeCheckedModelTemplate ( resource , modelTypes ) . make ( submodel ) . writeTo ( out ) ; return this ; }
Imports a template and renders it using the specified model allowing fine grained composition of templates and layouting . This works similarily to a template include but allows a distinct model to be used . If the layout inherits from the parent model a new model is created with the values from the parent model eventually overridden with those provided specifically for this layout .
6,944
public Closure contents ( final Closure cl ) { return new Closure ( cl . getOwner ( ) , cl . getThisObject ( ) ) { private static final long serialVersionUID = - 5733727697043906478L ; public Object call ( ) { cl . call ( ) ; return "" ; } public Object call ( final Object ... args ) { cl . call ( args ) ; return "" ; } public Object call ( final Object arguments ) { cl . call ( arguments ) ; return "" ; } } ; }
Wraps a closure so that it can be used as a prototype for inclusion in layouts . This is useful when you want to use a closure in a model but that you don t want to render the result of the closure but instead call it as if it was a specification of a template fragment .
6,945
public Writer writeTo ( final Writer out ) throws IOException { if ( this . out != null ) { return NullWriter . DEFAULT ; } try { this . out = createWriter ( out ) ; run ( ) ; return out ; } finally { if ( this . out != null ) { this . out . flush ( ) ; } this . out = null ; } }
Main method used to render a template .
6,946
protected static Variable findTargetVariable ( VariableExpression ve ) { final Variable accessedVariable = ve . getAccessedVariable ( ) != null ? ve . getAccessedVariable ( ) : ve ; if ( accessedVariable != ve ) { if ( accessedVariable instanceof VariableExpression ) return findTargetVariable ( ( VariableExpression ) accessedVariable ) ; } return accessedVariable ; }
Given a variable expression returns the ultimately accessed variable .
6,947
static int allParametersAndArgumentsMatchWithDefaultParams ( Parameter [ ] params , ClassNode [ ] args ) { int dist = 0 ; ClassNode ptype = null ; for ( int i = 0 , j = 0 ; i < params . length ; i ++ ) { Parameter param = params [ i ] ; ClassNode paramType = param . getType ( ) ; ClassNode arg = j >= args . length ? null : args [ j ] ; if ( arg == null || ! isAssignableTo ( arg , paramType ) ) { if ( ! param . hasInitialExpression ( ) && ( ptype == null || ! ptype . equals ( paramType ) ) ) { return - 1 ; } ptype = null ; } else { j ++ ; if ( ! paramType . equals ( arg ) ) dist += getDistance ( arg , paramType ) ; if ( param . hasInitialExpression ( ) ) { ptype = arg ; } else { ptype = null ; } } } return dist ; }
Checks that arguments and parameter types match expecting that the number of parameters is strictly greater than the number of arguments allowing possible inclusion of default parameters .
6,948
public static boolean isWildcardLeftHandSide ( final ClassNode node ) { if ( OBJECT_TYPE . equals ( node ) || STRING_TYPE . equals ( node ) || boolean_TYPE . equals ( node ) || Boolean_TYPE . equals ( node ) || CLASS_Type . equals ( node ) ) { return true ; } return false ; }
Tells if a class is one of the accept all classes as the left hand side of an assignment .
6,949
public static Parameter [ ] parameterizeArguments ( final ClassNode receiver , final MethodNode m ) { Map < GenericsTypeName , GenericsType > genericFromReceiver = GenericsUtils . extractPlaceholders ( receiver ) ; Map < GenericsTypeName , GenericsType > contextPlaceholders = extractGenericsParameterMapOfThis ( m ) ; Parameter [ ] methodParameters = m . getParameters ( ) ; Parameter [ ] params = new Parameter [ methodParameters . length ] ; for ( int i = 0 ; i < methodParameters . length ; i ++ ) { Parameter methodParameter = methodParameters [ i ] ; ClassNode paramType = methodParameter . getType ( ) ; params [ i ] = buildParameter ( genericFromReceiver , contextPlaceholders , methodParameter , paramType ) ; } return params ; }
Given a receiver and a method node parameterize the method arguments using available generic type information .
6,950
public static boolean isUsingGenericsOrIsArrayUsingGenerics ( ClassNode cn ) { if ( cn . isArray ( ) ) { return isUsingGenericsOrIsArrayUsingGenerics ( cn . getComponentType ( ) ) ; } return ( cn . isUsingGenerics ( ) && cn . getGenericsTypes ( ) != null ) ; }
Returns true if a class node makes use of generic types . If the class node represents an array type then checks if the component type is using generics .
6,951
protected static GenericsType fullyResolve ( GenericsType gt , Map < GenericsTypeName , GenericsType > placeholders ) { GenericsType fromMap = placeholders . get ( new GenericsTypeName ( gt . getName ( ) ) ) ; if ( gt . isPlaceholder ( ) && fromMap != null ) { gt = fromMap ; } ClassNode type = fullyResolveType ( gt . getType ( ) , placeholders ) ; ClassNode lowerBound = gt . getLowerBound ( ) ; if ( lowerBound != null ) lowerBound = fullyResolveType ( lowerBound , placeholders ) ; ClassNode [ ] upperBounds = gt . getUpperBounds ( ) ; if ( upperBounds != null ) { ClassNode [ ] copy = new ClassNode [ upperBounds . length ] ; for ( int i = 0 , upperBoundsLength = upperBounds . length ; i < upperBoundsLength ; i ++ ) { final ClassNode upperBound = upperBounds [ i ] ; copy [ i ] = fullyResolveType ( upperBound , placeholders ) ; } upperBounds = copy ; } GenericsType genericsType = new GenericsType ( type , upperBounds , lowerBound ) ; genericsType . setWildcard ( gt . isWildcard ( ) ) ; return genericsType ; }
Given a generics type representing SomeClass&lt ; T V&gt ; and a resolved placeholder map returns a new generics type for which placeholders are resolved recursively .
6,952
protected static boolean typeCheckMethodArgumentWithGenerics ( ClassNode parameterType , ClassNode argumentType , boolean lastArg ) { if ( UNKNOWN_PARAMETER_TYPE == argumentType ) { return ! isPrimitiveType ( parameterType ) ; } if ( ! isAssignableTo ( argumentType , parameterType ) && ! lastArg ) { return false ; } if ( ! isAssignableTo ( argumentType , parameterType ) && lastArg ) { if ( parameterType . isArray ( ) ) { if ( ! isAssignableTo ( argumentType , parameterType . getComponentType ( ) ) ) { return false ; } } else { return false ; } } if ( parameterType . isUsingGenerics ( ) && argumentType . isUsingGenerics ( ) ) { GenericsType gt = GenericsUtils . buildWildcardType ( parameterType ) ; if ( ! gt . isCompatibleWith ( argumentType ) ) { boolean samCoercion = isSAMType ( parameterType ) && argumentType . equals ( CLOSURE_TYPE ) ; if ( ! samCoercion ) return false ; } } else if ( parameterType . isArray ( ) && argumentType . isArray ( ) ) { return typeCheckMethodArgumentWithGenerics ( parameterType . getComponentType ( ) , argumentType . getComponentType ( ) , lastArg ) ; } else if ( lastArg && parameterType . isArray ( ) ) { return typeCheckMethodArgumentWithGenerics ( parameterType . getComponentType ( ) , argumentType , lastArg ) ; } return true ; }
Checks that the parameterized generics of an argument are compatible with the generics of the parameter .
6,953
static ClassNode boundUnboundedWildcards ( ClassNode type ) { if ( type . isArray ( ) ) { return boundUnboundedWildcards ( type . getComponentType ( ) ) . makeArray ( ) ; } ClassNode target = type . redirect ( ) ; if ( target == null || type == target || ! isUsingGenericsOrIsArrayUsingGenerics ( target ) ) return type ; ClassNode newType = type . getPlainNodeReference ( ) ; newType . setGenericsPlaceHolder ( type . isGenericsPlaceHolder ( ) ) ; newType . setGenericsTypes ( boundUnboundedWildcards ( type . getGenericsTypes ( ) , target . getGenericsTypes ( ) ) ) ; return newType ; }
Apply the bounds from the declared type when the using type simply declares a parameter as an unbounded wildcard .
6,954
public static List < MethodNode > filterMethodsByVisibility ( List < MethodNode > methodNodeList , ClassNode enclosingClassNode ) { if ( ! asBoolean ( methodNodeList ) ) { return StaticTypeCheckingVisitor . EMPTY_METHODNODE_LIST ; } List < MethodNode > result = new LinkedList < > ( ) ; boolean isEnclosingInnerClass = enclosingClassNode instanceof InnerClassNode ; List < ClassNode > outerClasses = enclosingClassNode . getOuterClasses ( ) ; outer : for ( MethodNode methodNode : methodNodeList ) { if ( methodNode instanceof ExtensionMethodNode ) { result . add ( methodNode ) ; continue ; } ClassNode declaringClass = methodNode . getDeclaringClass ( ) ; if ( isEnclosingInnerClass ) { for ( ClassNode outerClass : outerClasses ) { if ( outerClass . isDerivedFrom ( declaringClass ) ) { if ( outerClass . equals ( declaringClass ) ) { result . add ( methodNode ) ; continue outer ; } else { if ( methodNode . isPublic ( ) || methodNode . isProtected ( ) ) { result . add ( methodNode ) ; continue outer ; } } } } } if ( declaringClass instanceof InnerClassNode ) { if ( declaringClass . getOuterClasses ( ) . contains ( enclosingClassNode ) ) { result . add ( methodNode ) ; continue ; } } if ( methodNode . isPrivate ( ) && ! enclosingClassNode . equals ( declaringClass ) ) { continue ; } if ( methodNode . isProtected ( ) && ! enclosingClassNode . isDerivedFrom ( declaringClass ) && ! samePackageName ( enclosingClassNode , declaringClass ) ) { continue ; } if ( methodNode . isPackageScope ( ) && ! samePackageName ( enclosingClassNode , declaringClass ) ) { continue ; } result . add ( methodNode ) ; } return result ; }
Filter methods according to visibility
6,955
public void setUp ( GroovySourceAST t ) { super . setUp ( t ) ; unvisitedNodes = new ArrayList < GroovySourceAST > ( ) ; traverse ( t ) ; Collections . sort ( unvisitedNodes ) ; }
gather sort and process all unvisited nodes
6,956
public V getSilent ( K key ) { V value = cache . get ( key ) ; if ( value != null ) { cache . remove ( key ) ; cache . put ( key , value ) ; } return value ; }
For testing only
6,957
public Object getValue ( Object row , int rowIndex , int columnIndex ) { if ( valueModel instanceof NestedValueModel ) { NestedValueModel nestedModel = ( NestedValueModel ) valueModel ; nestedModel . getSourceModel ( ) . setValue ( row ) ; } return valueModel . getValue ( ) ; }
Evaluates the value of a cell
6,958
public void init ( ServletConfig config ) throws ServletException { super . init ( config ) ; gse = createGroovyScriptEngine ( ) ; servletContext . log ( "Groovy servlet initialized on " + gse + "." ) ; }
Initialize the GroovyServlet .
6,959
public void service ( HttpServletRequest request , HttpServletResponse response ) throws IOException { final String scriptUri = getScriptUri ( request ) ; response . setContentType ( "text/html; charset=" + encoding ) ; final ServletBinding binding = new ServletBinding ( request , response , servletContext ) ; setVariables ( binding ) ; try { Closure closure = new Closure ( gse ) { public Object call ( ) { try { return ( ( GroovyScriptEngine ) getDelegate ( ) ) . run ( scriptUri , binding ) ; } catch ( ResourceException | ScriptException e ) { throw new RuntimeException ( e ) ; } } } ; GroovyCategorySupport . use ( ServletCategory . class , closure ) ; } catch ( RuntimeException runtimeException ) { StringBuilder error = new StringBuilder ( "GroovyServlet Error: " ) ; error . append ( " script: '" ) ; error . append ( scriptUri ) ; error . append ( "': " ) ; Throwable e = runtimeException . getCause ( ) ; if ( e == null ) { error . append ( " Script processing failed.\n" ) ; error . append ( runtimeException . getMessage ( ) ) ; if ( runtimeException . getStackTrace ( ) . length > 0 ) error . append ( runtimeException . getStackTrace ( ) [ 0 ] . toString ( ) ) ; servletContext . log ( error . toString ( ) ) ; System . err . println ( error . toString ( ) ) ; runtimeException . printStackTrace ( System . err ) ; response . sendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , error . toString ( ) ) ; return ; } if ( e instanceof ResourceException ) { error . append ( " Script not found, sending 404." ) ; servletContext . log ( error . toString ( ) ) ; System . err . println ( error . toString ( ) ) ; response . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; return ; } servletContext . log ( "An error occurred processing the request" , runtimeException ) ; error . append ( e . getMessage ( ) ) ; if ( e . getStackTrace ( ) . length > 0 ) error . append ( e . getStackTrace ( ) [ 0 ] . toString ( ) ) ; servletContext . log ( e . toString ( ) ) ; System . err . println ( e . toString ( ) ) ; runtimeException . printStackTrace ( System . err ) ; response . sendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , e . toString ( ) ) ; } }
Handle web requests to the GroovyServlet
6,960
private static void renameMethod ( ClassNode buildee , MethodNode mNode , String newName ) { buildee . addMethod ( newName , mNode . getModifiers ( ) , mNode . getReturnType ( ) , mNode . getParameters ( ) , mNode . getExceptions ( ) , mNode . getCode ( ) ) ; buildee . removeMethod ( mNode ) ; }
no rename so delete and add
6,961
public static < V > Closure < V > buildMemoizeFunction ( final MemoizeCache < Object , Object > cache , final Closure < V > closure ) { return new MemoizeFunction < V > ( cache , closure ) ; }
Creates a new closure delegating to the supplied one and memoizing all return values by the arguments .
6,962
public static < V > Closure < V > buildSoftReferenceMemoizeFunction ( final int protectedCacheSize , final MemoizeCache < Object , SoftReference < Object > > cache , final Closure < V > closure ) { final ProtectionStorage lruProtectionStorage = protectedCacheSize > 0 ? new LRUProtectionStorage ( protectedCacheSize ) : new NullProtectionStorage ( ) ; final ReferenceQueue queue = new ReferenceQueue ( ) ; return new SoftReferenceMemoizeFunction < V > ( cache , closure , lruProtectionStorage , queue ) ; }
Creates a new closure delegating to the supplied one and memoizing all return values by the arguments . The memoizing closure will use SoftReferences to remember the return values allowing the garbage collector to reclaim the memory if needed .
6,963
private static Object generateKey ( final Object [ ] args ) { if ( args == null ) return Collections . emptyList ( ) ; Object [ ] copyOfArgs = copyOf ( args , args . length ) ; return asList ( copyOfArgs ) ; }
Creates a key to use in the memoize cache
6,964
private static AccessibleObject [ ] makeAccessible ( final AccessibleObject [ ] aoa ) { try { AccessibleObject . setAccessible ( aoa , true ) ; return aoa ; } catch ( Throwable outer ) { final ArrayList < AccessibleObject > ret = new ArrayList < > ( aoa . length ) ; for ( final AccessibleObject ao : aoa ) { try { ao . setAccessible ( true ) ; ret . add ( ao ) ; } catch ( Throwable inner ) { } } return ret . toArray ( ( AccessibleObject [ ] ) Array . newInstance ( aoa . getClass ( ) . getComponentType ( ) , ret . size ( ) ) ) ; } }
to be run in PrivilegedAction!
6,965
public void registerModifiedMetaClass ( ExpandoMetaClass emc ) { final Class klazz = emc . getJavaClass ( ) ; GroovySystem . getMetaClassRegistry ( ) . setMetaClass ( klazz , emc ) ; }
Registers a modified ExpandoMetaClass with the creation handle
6,966
public static Writer leftShift ( Writer self , Object value ) throws IOException { InvokerHelper . write ( self , value ) ; return self ; }
Overloads the leftShift operator for Writer to allow an object to be written using Groovy s default representation for the object .
6,967
public static Appendable leftShift ( Appendable self , Object value ) throws IOException { InvokerHelper . append ( self , value ) ; return self ; }
Overloads the leftShift operator for Appendable to allow an object to be appended using Groovy s default representation for the object .
6,968
public static Appendable withFormatter ( Appendable self , @ ClosureParams ( value = SimpleType . class , options = "java.util.Formatter" ) Closure closure ) { Formatter formatter = new Formatter ( self ) ; callWithFormatter ( closure , formatter ) ; return self ; }
Invokes a Closure that uses a Formatter taking care of resource handling . A Formatter is created and passed to the Closure as its argument . After the Closure executes the Formatter is flushed and closed releasing any associated resources .
6,969
public static Writer leftShift ( OutputStream self , Object value ) throws IOException { OutputStreamWriter writer = new FlushingStreamWriter ( self ) ; leftShift ( writer , value ) ; return writer ; }
Overloads the leftShift operator to provide an append mechanism to add values to a stream .
6,970
public static OutputStream leftShift ( OutputStream self , byte [ ] value ) throws IOException { self . write ( value ) ; self . flush ( ) ; return self ; }
Overloads the leftShift operator to provide an append mechanism to add bytes to a stream .
6,971
public static < T > T withObjectOutputStream ( OutputStream outputStream , @ ClosureParams ( value = SimpleType . class , options = "java.io.ObjectOutputStream" ) Closure < T > closure ) throws IOException { return withStream ( newObjectOutputStream ( outputStream ) , closure ) ; }
Create a new ObjectOutputStream for this output stream and then pass it to the closure . This method ensures the stream is closed after the closure returns .
6,972
public static ObjectInputStream newObjectInputStream ( InputStream inputStream , final ClassLoader classLoader ) throws IOException { return new ObjectInputStream ( inputStream ) { protected Class < ? > resolveClass ( ObjectStreamClass desc ) throws IOException , ClassNotFoundException { return Class . forName ( desc . getName ( ) , true , classLoader ) ; } } ; }
Create an object input stream for this input stream using the given class loader .
6,973
public static void eachObject ( ObjectInputStream ois , Closure closure ) throws IOException , ClassNotFoundException { try { while ( true ) { try { Object obj = ois . readObject ( ) ; closure . call ( obj ) ; } catch ( EOFException e ) { break ; } } InputStream temp = ois ; ois = null ; temp . close ( ) ; } finally { closeWithWarning ( ois ) ; } }
Iterates through the given object stream object by object . The ObjectInputStream is closed afterwards .
6,974
public static < T > T eachLine ( InputStream stream , String charset , int firstLine , @ ClosureParams ( value = FromString . class , options = { "String" , "String,Integer" } ) Closure < T > closure ) throws IOException { return eachLine ( new InputStreamReader ( stream , charset ) , firstLine , closure ) ; }
Iterates through this stream reading with the provided charset passing each line to the given 1 or 2 arg closure . The stream is closed after this method returns .
6,975
public static < T > T eachLine ( Reader self , int firstLine , @ ClosureParams ( value = FromString . class , options = { "String" , "String,Integer" } ) Closure < T > closure ) throws IOException { BufferedReader br ; int count = firstLine ; T result = null ; if ( self instanceof BufferedReader ) br = ( BufferedReader ) self ; else br = new BufferedReader ( self ) ; try { while ( true ) { String line = br . readLine ( ) ; if ( line == null ) { break ; } else { result = callClosureForLine ( closure , line , count ) ; count ++ ; } } Reader temp = self ; self = null ; temp . close ( ) ; return result ; } finally { closeWithWarning ( self ) ; closeWithWarning ( br ) ; } }
Iterates through the given reader line by line . Each line is passed to the given 1 or 2 arg closure . If the closure has two arguments the line count is passed as the second argument . The Reader is closed before this method returns .
6,976
public static List < String > readLines ( InputStream stream , String charset ) throws IOException { return readLines ( newReader ( stream , charset ) ) ; }
Reads the stream into a list with one element for each line .
6,977
public static List < String > readLines ( Reader reader ) throws IOException { IteratorClosureAdapter < String > closure = new IteratorClosureAdapter < String > ( reader ) ; eachLine ( reader , closure ) ; return closure . asList ( ) ; }
Reads the reader into a list of Strings with one entry for each line . The reader is closed before this method returns .
6,978
public static String getText ( InputStream is ) throws IOException { BufferedReader reader = new BufferedReader ( new InputStreamReader ( is ) ) ; return getText ( reader ) ; }
Read the content of this InputStream and return it as a String . The stream is closed before this method returns .
6,979
public static String getText ( Reader reader ) throws IOException { BufferedReader bufferedReader = new BufferedReader ( reader ) ; return getText ( bufferedReader ) ; }
Read the content of the Reader and return it as a String . The reader is closed before this method returns .
6,980
public static String getText ( BufferedReader reader ) throws IOException { StringBuilder answer = new StringBuilder ( ) ; char [ ] charBuffer = new char [ 8192 ] ; int nbCharRead ; try { while ( ( nbCharRead = reader . read ( charBuffer ) ) != - 1 ) { answer . append ( charBuffer , 0 , nbCharRead ) ; } Reader temp = reader ; reader = null ; temp . close ( ) ; } finally { closeWithWarning ( reader ) ; } return answer . toString ( ) ; }
Read the content of the BufferedReader and return it as a String . The BufferedReader is closed afterwards .
6,981
public static Iterator < String > iterator ( Reader self ) { final BufferedReader bufferedReader ; if ( self instanceof BufferedReader ) bufferedReader = ( BufferedReader ) self ; else bufferedReader = new BufferedReader ( self ) ; return new Iterator < String > ( ) { String nextVal ; boolean nextMustRead = true ; boolean hasNext = true ; public boolean hasNext ( ) { if ( nextMustRead && hasNext ) { try { nextVal = readNext ( ) ; nextMustRead = false ; } catch ( IOException e ) { hasNext = false ; } } return hasNext ; } public String next ( ) { String retval = null ; if ( nextMustRead ) { try { retval = readNext ( ) ; } catch ( IOException e ) { hasNext = false ; } } else retval = nextVal ; nextMustRead = true ; return retval ; } private String readNext ( ) throws IOException { String nv = bufferedReader . readLine ( ) ; if ( nv == null ) hasNext = false ; return nv ; } public void remove ( ) { throw new UnsupportedOperationException ( "Cannot remove() from a Reader Iterator" ) ; } } ; }
Creates an iterator which will traverse through the reader a line at a time .
6,982
public static Iterator < Byte > iterator ( final DataInputStream self ) { return new Iterator < Byte > ( ) { Byte nextVal ; boolean nextMustRead = true ; boolean hasNext = true ; public boolean hasNext ( ) { if ( nextMustRead && hasNext ) { try { nextVal = self . readByte ( ) ; nextMustRead = false ; } catch ( IOException e ) { hasNext = false ; } } return hasNext ; } public Byte next ( ) { Byte retval = null ; if ( nextMustRead ) { try { retval = self . readByte ( ) ; } catch ( IOException e ) { hasNext = false ; } } else retval = nextVal ; nextMustRead = true ; return retval ; } public void remove ( ) { throw new UnsupportedOperationException ( "Cannot remove() from a DataInputStream Iterator" ) ; } } ; }
Standard iterator for a data input stream which iterates through the stream content a Byte at a time .
6,983
public static BufferedReader newReader ( InputStream self , String charset ) throws UnsupportedEncodingException { return new BufferedReader ( new InputStreamReader ( self , charset ) ) ; }
Creates a reader for this input stream using the specified charset as the encoding .
6,984
public static < T > T withPrintWriter ( Writer writer , @ ClosureParams ( value = SimpleType . class , options = "java.io.PrintWriter" ) Closure < T > closure ) throws IOException { return withWriter ( newPrintWriter ( writer ) , closure ) ; }
Create a new PrintWriter for this Writer . The writer is passed to the closure and will be closed before this method returns .
6,985
public static < T > T withPrintWriter ( OutputStream stream , @ ClosureParams ( value = SimpleType . class , options = "java.io.PrintWriter" ) Closure < T > closure ) throws IOException { return withWriter ( newPrintWriter ( stream ) , closure ) ; }
Create a new PrintWriter for this OutputStream . The writer is passed to the closure and will be closed before this method returns .
6,986
public static < T > T withWriter ( Writer writer , @ ClosureParams ( FirstParam . class ) Closure < T > closure ) throws IOException { try { T result = closure . call ( writer ) ; try { writer . flush ( ) ; } catch ( IOException e ) { } Writer temp = writer ; writer = null ; temp . close ( ) ; return result ; } finally { closeWithWarning ( writer ) ; } }
Allows this writer to be used within the closure ensuring that it is flushed and closed before this method returns .
6,987
public static < T , U extends InputStream > T withStream ( U stream , @ ClosureParams ( value = FirstParam . class ) Closure < T > closure ) throws IOException { try { T result = closure . call ( stream ) ; InputStream temp = stream ; stream = null ; temp . close ( ) ; return result ; } finally { closeWithWarning ( stream ) ; } }
Allows this input stream to be used within the closure ensuring that it is flushed and closed before this method returns .
6,988
public static < T > T withWriter ( OutputStream stream , @ ClosureParams ( value = SimpleType . class , options = "java.io.Writer" ) Closure < T > closure ) throws IOException { return withWriter ( new OutputStreamWriter ( stream ) , closure ) ; }
Creates a writer from this stream passing it to the given closure . This method ensures the stream is closed after the closure returns .
6,989
public static Writer newWriter ( OutputStream stream , String charset ) throws UnsupportedEncodingException { return new OutputStreamWriter ( stream , charset ) ; }
Creates a writer for this stream using the given charset .
6,990
public static < T , U extends OutputStream > T withStream ( U os , @ ClosureParams ( value = FirstParam . class ) Closure < T > closure ) throws IOException { try { T result = closure . call ( os ) ; os . flush ( ) ; OutputStream temp = os ; os = null ; temp . close ( ) ; return result ; } finally { closeWithWarning ( os ) ; } }
Passes this OutputStream to the closure ensuring that the stream is closed after the closure returns regardless of errors .
6,991
public static void eachByte ( InputStream is , @ ClosureParams ( value = SimpleType . class , options = "byte" ) Closure closure ) throws IOException { try { while ( true ) { int b = is . read ( ) ; if ( b == - 1 ) { break ; } else { closure . call ( ( byte ) b ) ; } } InputStream temp = is ; is = null ; temp . close ( ) ; } finally { closeWithWarning ( is ) ; } }
Traverse through each byte of the specified stream . The stream is closed after the closure returns .
6,992
public static void eachByte ( InputStream is , int bufferLen , @ ClosureParams ( value = FromString . class , options = "byte[],Integer" ) Closure closure ) throws IOException { byte [ ] buffer = new byte [ bufferLen ] ; int bytesRead ; try { while ( ( bytesRead = is . read ( buffer , 0 , bufferLen ) ) > 0 ) { closure . call ( buffer , bytesRead ) ; } InputStream temp = is ; is = null ; temp . close ( ) ; } finally { closeWithWarning ( is ) ; } }
Traverse through each the specified stream reading bytes into a buffer and calling the 2 parameter closure with this buffer and the number of bytes .
6,993
public static void transformLine ( Reader reader , Writer writer , @ ClosureParams ( value = SimpleType . class , options = "java.lang.String" ) Closure closure ) throws IOException { BufferedReader br = new BufferedReader ( reader ) ; BufferedWriter bw = new BufferedWriter ( writer ) ; String line ; try { while ( ( line = br . readLine ( ) ) != null ) { Object o = closure . call ( line ) ; if ( o != null ) { bw . write ( o . toString ( ) ) ; bw . newLine ( ) ; } } bw . flush ( ) ; Writer temp2 = writer ; writer = null ; temp2 . close ( ) ; Reader temp1 = reader ; reader = null ; temp1 . close ( ) ; } finally { closeWithWarning ( br ) ; closeWithWarning ( reader ) ; closeWithWarning ( bw ) ; closeWithWarning ( writer ) ; } }
Transforms the lines from a reader with a Closure and write them to a writer . Both Reader and Writer are closed after the operation .
6,994
public static void filterLine ( Reader reader , Writer writer , @ ClosureParams ( value = SimpleType . class , options = "java.lang.String" ) Closure closure ) throws IOException { BufferedReader br = new BufferedReader ( reader ) ; BufferedWriter bw = new BufferedWriter ( writer ) ; String line ; try { BooleanClosureWrapper bcw = new BooleanClosureWrapper ( closure ) ; while ( ( line = br . readLine ( ) ) != null ) { if ( bcw . call ( line ) ) { bw . write ( line ) ; bw . newLine ( ) ; } } bw . flush ( ) ; Writer temp2 = writer ; writer = null ; temp2 . close ( ) ; Reader temp1 = reader ; reader = null ; temp1 . close ( ) ; } finally { closeWithWarning ( br ) ; closeWithWarning ( reader ) ; closeWithWarning ( bw ) ; closeWithWarning ( writer ) ; } }
Filter the lines from a reader and write them on the writer according to a closure which returns true if the line should be included . Both Reader and Writer are closed after the operation .
6,995
public static void putAt ( Date self , int field , int value ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( self ) ; putAt ( cal , field , value ) ; self . setTime ( cal . getTimeInMillis ( ) ) ; }
Support the subscript operator for mutating a Date .
6,996
public static Timestamp plus ( Timestamp self , int days ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( self ) ; calendar . add ( Calendar . DATE , days ) ; Timestamp ts = new Timestamp ( calendar . getTime ( ) . getTime ( ) ) ; ts . setNanos ( self . getNanos ( ) ) ; return ts ; }
Add number of days to this Timestamp and returns the new Timestamp object .
6,997
public static java . sql . Date minus ( java . sql . Date self , int days ) { return new java . sql . Date ( minus ( ( Date ) self , days ) . getTime ( ) ) ; }
Subtract a number of days from this date and returns the new date .
6,998
public static void upto ( Date self , Date to , Closure closure ) { if ( self . compareTo ( to ) <= 0 ) { for ( Date i = ( Date ) self . clone ( ) ; i . compareTo ( to ) <= 0 ; i = next ( i ) ) { closure . call ( i ) ; } } else throw new GroovyRuntimeException ( "The argument (" + to + ") to upto() cannot be earlier than the value (" + self + ") it's called on." ) ; }
Iterates from this date up to the given date inclusive incrementing by one day each time .
6,999
protected boolean isSkippedInnerClass ( AnnotatedNode node ) { if ( ! ( node instanceof InnerClassNode ) ) return false ; MethodNode enclosingMethod = ( ( InnerClassNode ) node ) . getEnclosingMethod ( ) ; return enclosingMethod != null && isSkipMode ( enclosingMethod ) ; }
Test if a node is an inner class node and if it is then checks if the enclosing method is skipped .