idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
19,800 | public static List < Number > findIndexValues ( Object self , Number startIndex , Closure closure ) { List < Number > result = new ArrayList < Number > ( ) ; long count = 0 ; long startCount = startIndex . longValue ( ) ; BooleanClosureWrapper bcw = new BooleanClosureWrapper ( closure ) ; for ( Iterator iter = InvokerHelper . asIterator ( self ) ; iter . hasNext ( ) ; count ++ ) { Object value = iter . next ( ) ; if ( count < startCount ) { continue ; } if ( bcw . call ( value ) ) { result . add ( count ) ; } } return result ; } | Iterates over the elements of an iterable collection of items starting from a specified startIndex and returns the index values of the items that match the condition specified in the closure . |
19,801 | public Object getProperty ( String property ) { if ( ExpandoMetaClass . isValidExpandoProperty ( property ) ) { if ( property . equals ( ExpandoMetaClass . STATIC_QUALIFIER ) || property . equals ( ExpandoMetaClass . CONSTRUCTOR ) || myMetaClass . hasProperty ( this , property ) == null ) { return replaceDelegate ( ) . getProperty ( property ) ; } } return myMetaClass . getProperty ( this , property ) ; } | this method mimics EMC behavior |
19,802 | public static Message create ( String text , Object data , ProcessingUnit owner ) { return new SimpleMessage ( text , data , owner ) ; } | Creates a new Message from the specified text . |
19,803 | public Object invokeMethod ( String name , Object args ) { Object val = null ; if ( args != null && Object [ ] . class . isAssignableFrom ( args . getClass ( ) ) ) { Object [ ] arr = ( Object [ ] ) args ; if ( arr . length == 1 ) { val = arr [ 0 ] ; } else if ( arr . length == 2 && arr [ 0 ] instanceof Collection && arr [ 1 ] instanceof Closure ) { Closure < ? > closure = ( Closure < ? > ) arr [ 1 ] ; Iterator < ? > iterator = ( ( Collection ) arr [ 0 ] ) . iterator ( ) ; List < Object > list = new ArrayList < Object > ( ) ; while ( iterator . hasNext ( ) ) { list . add ( curryDelegateAndGetContent ( closure , iterator . next ( ) ) ) ; } val = list ; } else { val = Arrays . asList ( arr ) ; } } content . put ( name , val ) ; return val ; } | Intercepts calls for setting a key and value for a JSON object |
19,804 | public void setVariable ( String name , Object value ) { if ( variables == null ) variables = new LinkedHashMap ( ) ; variables . put ( name , value ) ; } | Sets the value of the given variable |
19,805 | public Object getProperty ( Object object ) { MetaMethod getter = getGetter ( ) ; if ( getter == null ) { if ( field != null ) return field . getProperty ( object ) ; throw new GroovyRuntimeException ( "Cannot read write-only property: " + name ) ; } return getter . invoke ( object , MetaClassHelper . EMPTY_ARRAY ) ; } | Get the property of the given object . |
19,806 | public void setProperty ( Object object , Object newValue ) { MetaMethod setter = getSetter ( ) ; if ( setter == null ) { if ( field != null && ! Modifier . isFinal ( field . getModifiers ( ) ) ) { field . setProperty ( object , newValue ) ; return ; } throw new GroovyRuntimeException ( "Cannot set read-only property: " + name ) ; } newValue = DefaultTypeTransformation . castToType ( newValue , getType ( ) ) ; setter . invoke ( object , new Object [ ] { newValue } ) ; } | Set the property on the given object to the new value . |
19,807 | public int getModifiers ( ) { MetaMethod getter = getGetter ( ) ; MetaMethod setter = getSetter ( ) ; if ( setter != null && getter == null ) return setter . getModifiers ( ) ; if ( getter != null && setter == null ) return getter . getModifiers ( ) ; int modifiers = getter . getModifiers ( ) | setter . getModifiers ( ) ; int visibility = 0 ; if ( Modifier . isPublic ( modifiers ) ) visibility = Modifier . PUBLIC ; if ( Modifier . isProtected ( modifiers ) ) visibility = Modifier . PROTECTED ; if ( Modifier . isPrivate ( modifiers ) ) visibility = Modifier . PRIVATE ; int states = getter . getModifiers ( ) & setter . getModifiers ( ) ; states &= ~ ( Modifier . PUBLIC | Modifier . PROTECTED | Modifier . PRIVATE ) ; states |= visibility ; return states ; } | Gets the visibility modifiers for the property as defined by the getter and setter methods . |
19,808 | public static boolean isTrait ( final ClassNode cNode ) { return cNode != null && ( ( cNode . isInterface ( ) && ! cNode . getAnnotations ( TRAIT_CLASSNODE ) . isEmpty ( ) ) || isAnnotatedWithTrait ( cNode ) ) ; } | Returns true if the specified class node is a trait . |
19,809 | public static Method getBridgeMethodTarget ( Method someMethod ) { TraitBridge annotation = someMethod . getAnnotation ( TraitBridge . class ) ; if ( annotation == null ) { return null ; } Class aClass = annotation . traitClass ( ) ; String desc = annotation . desc ( ) ; for ( Method method : aClass . getDeclaredMethods ( ) ) { String methodDescriptor = BytecodeHelper . getMethodDescriptor ( method . getReturnType ( ) , method . getParameterTypes ( ) ) ; if ( desc . equals ( methodDescriptor ) ) { return method ; } } return null ; } | Reflection API to find the method corresponding to the default implementation of a trait given a bridge method . |
19,810 | private static int findNext ( boolean reverse , int pos ) { boolean backwards = IS_BACKWARDS_CHECKBOX . isSelected ( ) ; backwards = backwards ? ! reverse : reverse ; String pattern = ( String ) FIND_FIELD . getSelectedItem ( ) ; if ( pattern != null && pattern . length ( ) > 0 ) { try { Document doc = textComponent . getDocument ( ) ; doc . getText ( 0 , doc . getLength ( ) , SEGMENT ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } pos += textComponent . getSelectedText ( ) == null ? ( backwards ? - 1 : 1 ) : 0 ; char first = backwards ? pattern . charAt ( pattern . length ( ) - 1 ) : pattern . charAt ( 0 ) ; char oppFirst = Character . isUpperCase ( first ) ? Character . toLowerCase ( first ) : Character . toUpperCase ( first ) ; int start = pos ; boolean wrapped = WRAP_SEARCH_CHECKBOX . isSelected ( ) ; int end = backwards ? 0 : SEGMENT . getEndIndex ( ) ; pos += backwards ? - 1 : 1 ; int length = textComponent . getDocument ( ) . getLength ( ) ; if ( pos > length ) { pos = wrapped ? 0 : length ; } boolean found = false ; while ( ! found && ( backwards ? pos > end : pos < end ) ) { found = ! MATCH_CASE_CHECKBOX . isSelected ( ) && SEGMENT . array [ pos ] == oppFirst ; found = found ? found : SEGMENT . array [ pos ] == first ; if ( found ) { pos += backwards ? - ( pattern . length ( ) - 1 ) : 0 ; for ( int i = 0 ; found && i < pattern . length ( ) ; i ++ ) { char c = pattern . charAt ( i ) ; found = SEGMENT . array [ pos + i ] == c ; if ( ! MATCH_CASE_CHECKBOX . isSelected ( ) && ! found ) { c = Character . isUpperCase ( c ) ? Character . toLowerCase ( c ) : Character . toUpperCase ( c ) ; found = SEGMENT . array [ pos + i ] == c ; } } } if ( ! found ) { pos += backwards ? - 1 : 1 ; if ( pos == end && wrapped ) { pos = backwards ? SEGMENT . getEndIndex ( ) : 0 ; end = start ; wrapped = false ; } } } pos = found ? pos : - 1 ; } return pos ; } | Find and select the next searchable matching text . |
19,811 | protected static void invalidateSwitchPoints ( ) { if ( LOG_ENABLED ) { LOG . info ( "invalidating switch point" ) ; } SwitchPoint old = switchPoint ; switchPoint = new SwitchPoint ( ) ; synchronized ( IndyInterface . class ) { SwitchPoint . invalidateAll ( new SwitchPoint [ ] { old } ) ; } } | Callback for constant meta class update change |
19,812 | public static CallSite bootstrapCurrent ( Lookup caller , String name , MethodType type ) { return realBootstrap ( caller , name , CALL_TYPES . METHOD . ordinal ( ) , type , false , true , false ) ; } | bootstrap method for method calls with this as receiver |
19,813 | private static CallSite realBootstrap ( Lookup caller , String name , int callID , MethodType type , boolean safe , boolean thisCall , boolean spreadCall ) { MutableCallSite mc = new MutableCallSite ( type ) ; MethodHandle mh = makeFallBack ( mc , caller . lookupClass ( ) , name , callID , type , safe , thisCall , spreadCall ) ; mc . setTarget ( mh ) ; return mc ; } | backing bootstrap method with all parameters |
19,814 | public void addCell ( TableLayoutCell cell ) { GridBagConstraints constraints = cell . getConstraints ( ) ; constraints . insets = new Insets ( cellpadding , cellpadding , cellpadding , cellpadding ) ; add ( cell . getComponent ( ) , constraints ) ; } | Adds a new cell to the current grid |
19,815 | public void addClass ( ClassNode node ) { node = node . redirect ( ) ; String name = node . getName ( ) ; ClassNode stored = classes . get ( name ) ; if ( stored != null && stored != node ) { SourceUnit nodeSource = node . getModule ( ) . getContext ( ) ; SourceUnit storedSource = stored . getModule ( ) . getContext ( ) ; String txt = "Invalid duplicate class definition of class " + node . getName ( ) + " : " ; if ( nodeSource == storedSource ) { txt += "The source " + nodeSource . getName ( ) + " contains at least two definitions of the class " + node . getName ( ) + ".\n" ; if ( node . isScriptBody ( ) || stored . isScriptBody ( ) ) { txt += "One of the classes is an explicit generated class using the class statement, the other is a class generated from" + " the script body based on the file name. Solutions are to change the file name or to change the class name.\n" ; } } else { txt += "The sources " + nodeSource . getName ( ) + " and " + storedSource . getName ( ) + " each contain a class with the name " + node . getName ( ) + ".\n" ; } nodeSource . getErrorCollector ( ) . addErrorAndContinue ( new SyntaxErrorMessage ( new SyntaxException ( txt , node . getLineNumber ( ) , node . getColumnNumber ( ) , node . getLastLineNumber ( ) , node . getLastColumnNumber ( ) ) , nodeSource ) ) ; } classes . put ( name , node ) ; if ( classesToCompile . containsKey ( name ) ) { ClassNode cn = classesToCompile . get ( name ) ; cn . setRedirect ( node ) ; classesToCompile . remove ( name ) ; } } | Adds a class to the unit . |
19,816 | private String getSlashyPath ( final String path ) { String changedPath = path ; if ( File . separatorChar != '/' ) changedPath = changedPath . replace ( File . separatorChar , '/' ) ; return changedPath ; } | This solution is based on an absolute path |
19,817 | public static void write ( Path self , String text , String charset ) throws IOException { Writer writer = null ; try { writer = new OutputStreamWriter ( Files . newOutputStream ( self , CREATE , APPEND ) , Charset . forName ( charset ) ) ; writer . write ( text ) ; writer . flush ( ) ; Writer temp = writer ; writer = null ; temp . close ( ) ; } finally { closeWithWarning ( writer ) ; } } | Write the text to the Path using the specified encoding . |
19,818 | public static void append ( Path self , Object text ) throws IOException { Writer writer = null ; try { writer = new OutputStreamWriter ( Files . newOutputStream ( self , CREATE , APPEND ) , Charset . defaultCharset ( ) ) ; InvokerHelper . write ( writer , text ) ; writer . flush ( ) ; Writer temp = writer ; writer = null ; temp . close ( ) ; } finally { closeWithWarning ( writer ) ; } } | Append the text at the end of the Path . |
19,819 | public static int count ( CharSequence self , CharSequence text ) { int answer = 0 ; for ( int idx = 0 ; true ; idx ++ ) { idx = self . toString ( ) . indexOf ( text . toString ( ) , idx ) ; if ( idx < answer ) break ; ++ answer ; } return answer ; } | Count the number of occurrences of a sub CharSequence . |
19,820 | public static < T extends CharSequence > T eachMatch ( T self , CharSequence regex , @ ClosureParams ( value = FromString . class , options = { "List<String>" , "String[]" } ) Closure closure ) { eachMatch ( self . toString ( ) , regex . toString ( ) , closure ) ; return self ; } | Process each regex group matched substring of the given CharSequence . If the closure parameter takes one argument an array with all match groups is passed to it . If the closure takes as many arguments as there are match groups then each parameter will be one match group . |
19,821 | public static String eachMatch ( String self , String regex , @ ClosureParams ( value = FromString . class , options = { "List<String>" , "String[]" } ) Closure closure ) { return eachMatch ( self , Pattern . compile ( regex ) , closure ) ; } | Process each regex group matched substring of the given string . If the closure parameter takes one argument an array with all match groups is passed to it . If the closure takes as many arguments as there are match groups then each parameter will be one match group . |
19,822 | public static String expandLine ( CharSequence self , int tabStop ) { String s = self . toString ( ) ; int index ; while ( ( index = s . indexOf ( '\t' ) ) != - 1 ) { StringBuilder builder = new StringBuilder ( s ) ; int count = tabStop - index % tabStop ; builder . deleteCharAt ( index ) ; for ( int i = 0 ; i < count ; i ++ ) builder . insert ( index , " " ) ; s = builder . toString ( ) ; } return s ; } | Expands all tabs into spaces . Assumes the CharSequence represents a single line of text . |
19,823 | public static String find ( CharSequence self , CharSequence regex , @ ClosureParams ( value = SimpleType . class , options = "java.lang.String[]" ) Closure closure ) { return find ( self . toString ( ) , Pattern . compile ( regex . toString ( ) ) , closure ) ; } | Returns the result of calling a closure with the first occurrence of a regular expression found within a CharSequence . If the regex doesn t match the closure will not be called and find will return null . |
19,824 | public static String getAt ( CharSequence self , Collection indices ) { StringBuilder answer = new StringBuilder ( ) ; for ( Object value : indices ) { if ( value instanceof Range ) { answer . append ( getAt ( self , ( Range ) value ) ) ; } else if ( value instanceof Collection ) { answer . append ( getAt ( self , ( Collection ) value ) ) ; } else { int idx = DefaultTypeTransformation . intUnbox ( value ) ; answer . append ( getAt ( self , idx ) ) ; } } return answer . toString ( ) ; } | Select a List of characters from a CharSequence using a Collection to identify the indices to be selected . |
19,825 | public static CharSequence getAt ( CharSequence text , int index ) { index = normaliseIndex ( index , text . length ( ) ) ; return text . subSequence ( index , index + 1 ) ; } | Support the subscript operator for CharSequence . |
19,826 | public static String getAt ( GString text , int index ) { return ( String ) getAt ( text . toString ( ) , index ) ; } | Support the subscript operator for GString . |
19,827 | public static CharSequence getAt ( CharSequence text , IntRange range ) { return getAt ( text , ( Range ) range ) ; } | Support the range subscript operator for CharSequence with IntRange |
19,828 | public static CharSequence getAt ( CharSequence text , Range range ) { RangeInfo info = subListBorders ( text . length ( ) , range ) ; CharSequence sequence = text . subSequence ( info . from , info . to ) ; return info . reverse ? reverse ( sequence ) : sequence ; } | Support the range subscript operator for CharSequence |
19,829 | public static String getAt ( GString text , Range range ) { return getAt ( text . toString ( ) , range ) ; } | Support the range subscript operator for GString |
19,830 | public static List getAt ( Matcher self , Collection indices ) { List result = new ArrayList ( ) ; for ( Object value : indices ) { if ( value instanceof Range ) { result . addAll ( getAt ( self , ( Range ) value ) ) ; } else { int idx = DefaultTypeTransformation . intUnbox ( value ) ; result . add ( getAt ( self , idx ) ) ; } } return result ; } | Select a List of values from a Matcher using a Collection to identify the indices to be selected . |
19,831 | public static String getAt ( String text , int index ) { index = normaliseIndex ( index , text . length ( ) ) ; return text . substring ( index , index + 1 ) ; } | Support the subscript operator for String . |
19,832 | public static String getAt ( String text , IntRange range ) { return getAt ( text , ( Range ) range ) ; } | Support the range subscript operator for String with IntRange |
19,833 | public static String getAt ( String text , Range range ) { RangeInfo info = subListBorders ( text . length ( ) , range ) ; String answer = text . substring ( info . from , info . to ) ; if ( info . reverse ) { answer = reverse ( answer ) ; } return answer ; } | Support the range subscript operator for String |
19,834 | public static int getCount ( Matcher matcher ) { int counter = 0 ; matcher . reset ( ) ; while ( matcher . find ( ) ) { counter ++ ; } return counter ; } | Find the number of Strings matched to the given Matcher . |
19,835 | public static boolean isAllWhitespace ( CharSequence self ) { String s = self . toString ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( ! Character . isWhitespace ( s . charAt ( i ) ) ) return false ; } return true ; } | True if a CharSequence only contains whitespace characters . |
19,836 | public static boolean isBigDecimal ( CharSequence self ) { try { new BigDecimal ( self . toString ( ) . trim ( ) ) ; return true ; } catch ( NumberFormatException nfe ) { return false ; } } | Determine if a CharSequence can be parsed as a BigDecimal . |
19,837 | public static boolean isBigInteger ( CharSequence self ) { try { new BigInteger ( self . toString ( ) . trim ( ) ) ; return true ; } catch ( NumberFormatException nfe ) { return false ; } } | Determine if a CharSequence can be parsed as a BigInteger . |
19,838 | public static boolean isDouble ( CharSequence self ) { try { Double . valueOf ( self . toString ( ) . trim ( ) ) ; return true ; } catch ( NumberFormatException nfe ) { return false ; } } | Determine if a CharSequence can be parsed as a Double . |
19,839 | public static boolean isFloat ( CharSequence self ) { try { Float . valueOf ( self . toString ( ) . trim ( ) ) ; return true ; } catch ( NumberFormatException nfe ) { return false ; } } | Determine if a CharSequence can be parsed as a Float . |
19,840 | public static boolean isInteger ( CharSequence self ) { try { Integer . valueOf ( self . toString ( ) . trim ( ) ) ; return true ; } catch ( NumberFormatException nfe ) { return false ; } } | Determine if a CharSequence can be parsed as an Integer . |
19,841 | public static boolean isLong ( CharSequence self ) { try { Long . valueOf ( self . toString ( ) . trim ( ) ) ; return true ; } catch ( NumberFormatException nfe ) { return false ; } } | Determine if a CharSequence can be parsed as a Long . |
19,842 | public static StringBuffer leftShift ( String self , Object value ) { return new StringBuffer ( self ) . append ( value ) ; } | Overloads the left shift operator to provide an easy way to append multiple objects as string representations to a String . |
19,843 | public static StringBuilder leftShift ( StringBuilder self , Object value ) { self . append ( value ) ; return self ; } | Overloads the left shift operator to provide syntactic sugar for appending to a StringBuilder . |
19,844 | public static String minus ( CharSequence self , Object target ) { String s = self . toString ( ) ; String text = DefaultGroovyMethods . toString ( target ) ; int index = s . indexOf ( text ) ; if ( index == - 1 ) return s ; int end = index + text . length ( ) ; if ( s . length ( ) > end ) { return s . substring ( 0 , index ) + s . substring ( end ) ; } return s . substring ( 0 , index ) ; } | Remove a part of a CharSequence by replacing the first occurrence of target within self with and returns the result . |
19,845 | public static String minus ( CharSequence self , Pattern pattern ) { return pattern . matcher ( self ) . replaceFirst ( "" ) ; } | Remove a part of a CharSequence . This replaces the first occurrence of the pattern within self with and returns the result . |
19,846 | public static String multiply ( CharSequence self , Number factor ) { String s = self . toString ( ) ; int size = factor . intValue ( ) ; if ( size == 0 ) return "" ; else if ( size < 0 ) { throw new IllegalArgumentException ( "multiply() should be called with a number of 0 or greater not: " + size ) ; } StringBuilder answer = new StringBuilder ( s ) ; for ( int i = 1 ; i < size ; i ++ ) { answer . append ( s ) ; } return answer . toString ( ) ; } | Repeat a CharSequence a certain number of times . |
19,847 | public static String next ( CharSequence self ) { StringBuilder buffer = new StringBuilder ( self ) ; if ( buffer . length ( ) == 0 ) { buffer . append ( Character . MIN_VALUE ) ; } else { char last = buffer . charAt ( buffer . length ( ) - 1 ) ; if ( last == Character . MAX_VALUE ) { buffer . append ( Character . MIN_VALUE ) ; } else { char next = last ; next ++ ; buffer . setCharAt ( buffer . length ( ) - 1 , next ) ; } } return buffer . toString ( ) ; } | This method is called by the ++ operator for the class CharSequence . It increments the last character in the given CharSequence . If the last character in the CharSequence is Character . MAX_VALUE a Character . MIN_VALUE will be appended . The empty CharSequence is incremented to a string consisting of the character Character . MIN_VALUE . |
19,848 | public static String normalize ( final CharSequence self ) { final String s = self . toString ( ) ; int nx = s . indexOf ( '\r' ) ; if ( nx < 0 ) { return s ; } final int len = s . length ( ) ; final StringBuilder sb = new StringBuilder ( len ) ; int i = 0 ; do { sb . append ( s , i , nx ) ; sb . append ( '\n' ) ; if ( ( i = nx + 1 ) >= len ) break ; if ( s . charAt ( i ) == '\n' ) { if ( ++ i >= len ) break ; } nx = s . indexOf ( '\r' , i ) ; } while ( nx > 0 ) ; sb . append ( s , i , len ) ; return sb . toString ( ) ; } | Return a String with linefeeds and carriage returns normalized to linefeeds . |
19,849 | public static String plus ( CharSequence left , Object value ) { return left + DefaultGroovyMethods . toString ( value ) ; } | Appends the String representation of the given operand to this CharSequence . |
19,850 | public static String plus ( Number value , String right ) { return DefaultGroovyMethods . toString ( value ) + right ; } | Appends a String to the string representation of this number . |
19,851 | public static List < String > readLines ( CharSequence self ) throws IOException { return IOGroovyMethods . readLines ( new StringReader ( self . toString ( ) ) ) ; } | Return the lines of a CharSequence as a List of String . |
19,852 | public static String replaceAll ( final CharSequence self , final CharSequence regex , final CharSequence replacement ) { return self . toString ( ) . replaceAll ( regex . toString ( ) , replacement . toString ( ) ) ; } | Replaces each substring of this CharSequence that matches the given regular expression with the given replacement . |
19,853 | public static String replaceFirst ( final CharSequence self , final CharSequence regex , final CharSequence replacement ) { return self . toString ( ) . replaceFirst ( regex . toString ( ) , replacement . toString ( ) ) ; } | Replaces the first substring of this CharSequence that matches the given regular expression with the given replacement . |
19,854 | public static void setIndex ( Matcher matcher , int idx ) { int count = getCount ( matcher ) ; if ( idx < - count || idx >= count ) { throw new IndexOutOfBoundsException ( "index is out of range " + ( - count ) + ".." + ( count - 1 ) + " (index = " + idx + ")" ) ; } if ( idx == 0 ) { matcher . reset ( ) ; } else if ( idx > 0 ) { matcher . reset ( ) ; for ( int i = 0 ; i < idx ; i ++ ) { matcher . find ( ) ; } } else if ( idx < 0 ) { matcher . reset ( ) ; idx += getCount ( matcher ) ; for ( int i = 0 ; i < idx ; i ++ ) { matcher . find ( ) ; } } } | Set the position of the given Matcher to the given index . |
19,855 | public static < T > T splitEachLine ( CharSequence self , CharSequence regex , @ ClosureParams ( value = FromString . class , options = "List<String>" ) Closure < T > closure ) throws IOException { return splitEachLine ( self , Pattern . compile ( regex . toString ( ) ) , closure ) ; } | Iterates through the given CharSequence line by line splitting each line using the given regex delimiter . The list of tokens for each line is then passed to the given closure . |
19,856 | public static < T > T splitEachLine ( CharSequence self , Pattern pattern , @ ClosureParams ( value = FromString . class , options = "List<String>" ) Closure < T > closure ) throws IOException { final List < String > list = readLines ( self ) ; T result = null ; for ( String line : list ) { List vals = Arrays . asList ( pattern . split ( line ) ) ; result = closure . call ( vals ) ; } return result ; } | Iterates through the given CharSequence line by line splitting each line using the given separator Pattern . The list of tokens for each line is then passed to the given closure . |
19,857 | public static String takeWhile ( GString self , @ ClosureParams ( value = SimpleType . class , options = "char" ) Closure condition ) { return ( String ) takeWhile ( self . toString ( ) , condition ) ; } | A GString variant of the equivalent GString method . |
19,858 | public static List < String > toList ( CharSequence self ) { String s = self . toString ( ) ; int size = s . length ( ) ; List < String > answer = new ArrayList < String > ( size ) ; for ( int i = 0 ; i < size ; i ++ ) { answer . add ( s . substring ( i , i + 1 ) ) ; } return answer ; } | Converts the given CharSequence into a List of Strings of one character . |
19,859 | 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" ) ; } if ( ! s . endsWith ( "\n" ) ) { builder . deleteCharAt ( builder . length ( ) - 1 ) ; } return builder . toString ( ) ; } catch ( IOException e ) { } return s ; } | Replaces sequences of whitespaces with tabs . |
19,860 | public static String unexpandLine ( CharSequence self , int tabStop ) { StringBuilder builder = new StringBuilder ( self . toString ( ) ) ; int index = 0 ; while ( index + tabStop < builder . length ( ) ) { String piece = builder . substring ( index , index + tabStop ) ; int count = 0 ; while ( ( count < tabStop ) && ( Character . isWhitespace ( piece . charAt ( tabStop - ( count + 1 ) ) ) ) ) count ++ ; 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 ( ) ; } | Replaces sequences of whitespaces with tabs within a line . |
19,861 | public boolean hasPossibleMethod ( String name , Expression arguments ) { int count = 0 ; if ( arguments instanceof TupleExpression ) { TupleExpression tuple = ( TupleExpression ) arguments ; 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 . |
19,862 | 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 . |
19,863 | 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 . |
19,864 | private boolean ensureValidSetter ( final Expression expression , final Expression leftExpression , final Expression rightExpression , final SetterInfo setterInfo ) { 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 ) { 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 . |
19,865 | 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 |
19,866 | private ClassNode getGenericsResolvedTypeOfFieldOrProperty ( AnnotatedNode an , ClassNode type ) { if ( ! type . isUsingGenerics ( ) ) return type ; Map < String , GenericsType > connections = new HashMap ( ) ; 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 |
19,867 | 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" ) ; 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 ) { throw new RuntimeException ( "bad character in base64 value" ) ; } 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" ) ; } } | Decode the String from Base64 into a byte array . |
19,868 | 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" ) ; } } if ( ! txt . toString ( ) . equals ( "" ) ) { execGroovy ( txt . toString ( ) , out ) ; } } | Read in lines and execute them . |
19,869 | 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 . |
19,870 | 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 . |
19,871 | 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 { buffer . addString ( value . toString ( ) ) ; } } | Serializes Number value and writes it into specified buffer . |
19,872 | 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 . |
19,873 | 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 |
19,874 | public void setTargetBytecode ( String version ) { if ( CompilerConfiguration . PRE_JDK5 . equals ( version ) || CompilerConfiguration . POST_JDK5 . equals ( version ) ) { this . targetBytecode = version ; } } | Sets the bytecode compatibility mode |
19,875 | 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 . |
19,876 | 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 |
19,877 | 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 . |
19,878 | 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 |
19,879 | 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 . |
19,880 | 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 . |
19,881 | public void put ( final K key , V value ) { ManagedReference < V > ref = new ManagedReference < V > ( bundle , value ) { 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 . |
19,882 | 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 . |
19,883 | 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 . |
19,884 | 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 . |
19,885 | 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 .. |
19,886 | 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 . |
19,887 | @ 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 ) { 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 . |
19,888 | 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 . |
19,889 | public void setTargetDirectory ( String directory ) { if ( directory != null && directory . length ( ) > 0 ) { this . targetDirectory = new File ( directory ) ; } else { this . targetDirectory = null ; } } | Sets the target directory . |
19,890 | 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 ) { } if ( c == null ) c = super . loadClass ( name , resolve ) ; if ( resolve ) resolveClass ( c ) ; return c ; } | loads a class using the name of the class |
19,891 | 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 . |
19,892 | 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 . |
19,893 | 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 |
19,894 | private List < TokenStream > collectTokenStreams ( TokenStream stream ) { 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 ( " " ) ; if ( currentGroup == null ) { if ( currentTokenType != DateLexer . WHITE_SPACE && DateParser . FOLLOW_empty_in_parse186 . member ( currentTokenType ) ) { currentGroup = new ArrayList < Token > ( ) ; currentGroup . add ( currentToken ) ; } } else { if ( currentTokenType == DateLexer . WHITE_SPACE ) { currentGroup . add ( currentToken ) ; } else { if ( currentTokenType == DateLexer . UNKNOWN ) { addGroup ( currentGroup , groups ) ; currentGroup = null ; } 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 |
19,895 | private void addGroup ( List < Token > group , List < List < Token > > groups ) { if ( group . isEmpty ( ) ) return ; while ( ! group . isEmpty ( ) && IGNORED_TRAILING_TOKENS . contains ( group . get ( group . size ( ) - 1 ) . getType ( ) ) ) { group . remove ( group . size ( ) - 1 ) ; } if ( ! group . isEmpty ( ) ) { groups . add ( group ) ; } } | Cleans up the given group and adds it to the list of groups if still valid |
19,896 | 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 ) ) { _calendar . set ( Calendar . DAY_OF_WEEK , dayOfWeekInt ) ; _calendar . add ( Calendar . DAY_OF_YEAR , seekAmountInt * 7 * sign ) ; } else if ( seekType . equals ( SEEK_BY_DAY ) ) { do { _calendar . add ( Calendar . DAY_OF_YEAR , sign ) ; } while ( _calendar . get ( Calendar . DAY_OF_WEEK ) != dayOfWeekInt ) ; 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 . |
19,897 | 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 |
19,898 | 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 |
19,899 | 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 ( ) ; _calendar . set ( Calendar . DAY_OF_MONTH , 1 ) ; 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 ) ) ; } _calendar . set ( Calendar . MONTH , monthInt - 1 ) ; } | seeks to a particular month |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.