idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
143,100
public boolean nonConsumingMatch ( ParserTokenType rhs ) { ParserToken token = lookAhead ( 0 ) ; return token != null && token . type . isInstance ( rhs ) ; }
Determines if the token at the front of the stream is a match for a given type without consuming the token .
44
24
143,101
public boolean match ( ParserTokenType expected ) { ParserToken next = lookAhead ( 0 ) ; if ( next == null || ! next . type . isInstance ( expected ) ) { return false ; } consume ( ) ; return true ; }
Determines if the next token in the stream is of an expected type and consumes it if it is
53
21
143,102
public static void main ( String [ ] args ) { JFrame frame ; App biorhythm = new App ( ) ; try { frame = new JFrame ( "Biorhythm" ) ; frame . addWindowListener ( new AppCloser ( frame , biorhythm ) ) ; } catch ( java . lang . Throwable ivjExc ) { frame = null ; System . out . println ( ivjExc . getMessage ( ) ) ; ivjExc . printStackTrace ( ) ; } frame . getContentPane ( ) . add ( BorderLayout . CENTER , biorhythm ) ; Dimension size = biorhythm . getSize ( ) ; if ( ( size == null ) || ( ( size . getHeight ( ) < 100 ) | ( size . getWidth ( ) < 100 ) ) ) size = new Dimension ( 640 , 400 ) ; frame . setSize ( size ) ; biorhythm . init ( ) ; // Simulate the applet calls frame . setTitle ( "Sample java application" ) ; biorhythm . start ( ) ; frame . setVisible ( true ) ; }
main entrypoint - starts the applet when it is run as an application
241
15
143,103
public void init ( ) { JPanel view = new JPanel ( ) ; view . setLayout ( new BorderLayout ( ) ) ; label = new JLabel ( INITIAL_TEXT ) ; Font font = new Font ( Font . SANS_SERIF , Font . BOLD , 32 ) ; label . setFont ( font ) ; view . add ( BorderLayout . CENTER , label ) ; this . getContentPane ( ) . add ( BorderLayout . CENTER , view ) ; this . startRollingText ( ) ; }
Initialize this applet .
114
6
143,104
public String replicateTable ( String tableName , boolean toCopyData ) throws SQLException { String tempTableName = MySqlCommunication . getTempTableName ( tableName ) ; LOG . debug ( "Replicate table {} into {}" , tableName , tempTableName ) ; if ( this . tableExists ( tempTableName ) ) { this . truncateTempTable ( tempTableName ) ; } else { this . createTempTable ( tableName ) ; } if ( toCopyData ) { final String sql = "INSERT INTO " + tempTableName + " SELECT * FROM " + tableName + ";" ; this . executeUpdate ( sql ) ; } return tempTableName ; }
Replicates table structure and data from source to temporary table .
149
12
143,105
public void restoreTable ( String tableName , String tempTableName ) throws SQLException { LOG . debug ( "Restore table {} from {}" , tableName , tempTableName ) ; try { this . setForeignKeyCheckEnabled ( false ) ; this . truncateTable ( tableName ) ; final String sql = "INSERT INTO " + tableName + " SELECT * FROM " + tempTableName + ";" ; this . executeUpdate ( sql ) ; } finally { this . setForeignKeyCheckEnabled ( true ) ; } }
Restores table content .
114
5
143,106
public void removeTempTable ( String tempTableName ) throws SQLException { if ( tempTableName == null ) { return ; } if ( ! tempTableName . contains ( TEMP_TABLE_NAME_SUFFIX ) ) { throw new SQLException ( tempTableName + " is not a valid temp table name" ) ; } try ( Connection conn = this . getConn ( ) ; Statement stmt = conn . createStatement ( ) ) { final String sql = "DROP TABLE " + tempTableName + ";" ; LOG . debug ( "{} executing update: {}" , this . dbInfo , sql ) ; int row = stmt . executeUpdate ( sql ) ; } }
Drops a temporary table .
149
6
143,107
public final void addParser ( @ NotNull final ParserConfig parser ) { Contract . requireArgNotNull ( "parser" , parser ) ; if ( list == null ) { list = new ArrayList <> ( ) ; } list . add ( parser ) ; }
Adds a parser to the list . If the list does not exist it s created .
56
17
143,108
private String setXmlPreambleAndDTD ( final String xml , final String dtdFileName , final String entities , final String dtdRootEleName ) { // Check if the XML already has a DOCTYPE. If it does then replace the values and remove entities for processing final Matcher matcher = DOCTYPE_PATTERN . matcher ( xml ) ; if ( matcher . find ( ) ) { String preamble = matcher . group ( "Preamble" ) ; String name = matcher . group ( "Name" ) ; String systemId = matcher . group ( "SystemId" ) ; String declaredEntities = matcher . group ( "Entities" ) ; String doctype = matcher . group ( ) ; String newDoctype = doctype . replace ( name , dtdRootEleName ) ; if ( systemId != null ) { newDoctype = newDoctype . replace ( systemId , dtdFileName ) ; } if ( declaredEntities != null ) { newDoctype = newDoctype . replace ( declaredEntities , " [\n" + entities + "\n]" ) ; } else { newDoctype = newDoctype . substring ( 0 , newDoctype . length ( ) - 1 ) + " [\n" + entities + "\n]>" ; } if ( preamble == null ) { final StringBuilder output = new StringBuilder ( ) ; output . append ( "<?xml version='1.0' encoding='UTF-8' ?>\n" ) ; output . append ( xml . replace ( doctype , newDoctype ) ) ; return output . toString ( ) ; } else { return xml . replace ( doctype , newDoctype ) ; } } else { // The XML doesn't have any doctype so add it final String preamble = XMLUtilities . findPreamble ( xml ) ; if ( preamble != null ) { final StringBuilder doctype = new StringBuilder ( ) ; doctype . append ( preamble ) ; appendDoctype ( doctype , dtdRootEleName , dtdFileName , entities ) ; return xml . replace ( preamble , doctype . toString ( ) ) ; } else { final StringBuilder output = new StringBuilder ( ) ; output . append ( "<?xml version='1.0' encoding='UTF-8' ?>\n" ) ; appendDoctype ( output , dtdRootEleName , dtdFileName , entities ) ; output . append ( xml ) ; return output . toString ( ) ; } } }
Sets the DTD for an xml file . If there are any entities then they are removed . This function will also add the preamble to the XML if it doesn t exist .
569
38
143,109
public int process ( ) { // Calculate the result of the left operation if any if ( leftOperation != null ) { leftOperand = leftOperation . process ( ) ; } // Calculate the result of the right operation if any if ( rightOperation != null ) { rightOperand = rightOperation . process ( ) ; } // Process the operation itself after the composition resolution return calculate ( ) ; }
Process the operation and take care about the composition of the operations
83
12
143,110
public void executeAction ( ShanksSimulation simulation , ShanksAgent agent , List < NetworkElement > arguments ) throws ShanksException { for ( NetworkElement ne : arguments ) { this . addAffectedElement ( ne ) ; } this . launchEvent ( ) ; }
Method called when the action has to be performed .
57
10
143,111
@ Override public synchronized boolean stopFollowing ( final Follower follower ) { if ( ! this . isFollowedBy ( follower ) ) { return false ; } this . stopConsuming ( follower ) ; DefaultLogWatch . LOGGER . info ( "Unregistered {} for {}." , follower , this ) ; return true ; }
Is synchronized since we want to prevent multiple stops of the same follower .
68
14
143,112
public void progress ( ) { count ++ ; if ( count % period == 0 && LOG . isInfoEnabled ( ) ) { final double percent = 100 * ( count / ( double ) totalIterations ) ; final long tock = System . currentTimeMillis ( ) ; final long timeInterval = tock - tick ; final long linesPerSec = ( count - prevCount ) * 1000 / timeInterval ; tick = tock ; prevCount = count ; final int etaSeconds = ( int ) ( ( totalIterations - count ) / linesPerSec ) ; final long hours = SECONDS . toHours ( etaSeconds ) ; final long minutes = SECONDS . toMinutes ( etaSeconds - HOURS . toSeconds ( hours ) ) ; final long seconds = SECONDS . toSeconds ( etaSeconds - MINUTES . toSeconds ( minutes ) ) ; LOG . info ( String . format ( "[%3.0f%%] Completed %d iterations of %d total input. %d iters/s. ETA %02d:%02d:%02d" , percent , count , totalIterations , linesPerSec , hours , minutes , seconds ) ) ; } }
Logs the progress .
265
5
143,113
public void writeEntries ( JarFile jarFile ) throws IOException { Enumeration < JarEntry > entries = jarFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { JarEntry entry = entries . nextElement ( ) ; ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream ( jarFile . getInputStream ( entry ) ) ; try { if ( inputStream . hasZipHeader ( ) && entry . getMethod ( ) != ZipEntry . STORED ) { new CrcAndSize ( inputStream ) . setupStoredEntry ( entry ) ; inputStream . close ( ) ; inputStream = new ZipHeaderPeekInputStream ( jarFile . getInputStream ( entry ) ) ; } EntryWriter entryWriter = new InputStreamEntryWriter ( inputStream , true ) ; writeEntry ( entry , entryWriter ) ; } finally { inputStream . close ( ) ; } } }
Write all entries from the specified jar file .
196
9
143,114
@ Override public void afterProjectsRead ( final MavenSession session ) throws MavenExecutionException { boolean anyProject = false ; for ( MavenProject project : session . getProjects ( ) ) { if ( project . getPlugin ( "ceylon" ) != null || project . getPlugin ( "ceylon-maven-plugin" ) != null || "ceylon" . equals ( project . getArtifact ( ) . getArtifactHandler ( ) . getPackaging ( ) ) || "car" . equals ( project . getArtifact ( ) . getArtifactHandler ( ) . getPackaging ( ) ) || "ceylon-jar" . equals ( project . getArtifact ( ) . getArtifactHandler ( ) . getPackaging ( ) ) || usesCeylonRepo ( project ) ) { anyProject = true ; } } if ( anyProject ) { logger . info ( "At least one project is using the Ceylon plugin. Preparing." ) ; findCeylonRepo ( session ) ; } logger . info ( "Adding Ceylon repositories to build" ) ; session . getRequest ( ) . setWorkspaceReader ( new CeylonWorkspaceReader ( session . getRequest ( ) . getWorkspaceReader ( ) , logger ) ) ; }
Interception after projects are known .
274
7
143,115
private boolean usesCeylonRepo ( final MavenProject project ) { for ( Repository repo : project . getRepositories ( ) ) { if ( "ceylon" . equals ( repo . getLayout ( ) ) ) { return true ; } } for ( Artifact ext : project . getPluginArtifacts ( ) ) { if ( ext . getArtifactId ( ) . startsWith ( "ceylon" ) ) { return true ; } } return false ; }
Checks that a project use the Ceylon Maven plugin .
99
13
143,116
public void stream ( InputStream inputStream , MediaType mediaType ) { try { OutputStream outputStream = exchange . getOutputStream ( ) ; setResponseMediaType ( mediaType ) ; byte [ ] buffer = new byte [ 10240 ] ; int len ; while ( ( len = inputStream . read ( buffer ) ) != - 1 ) { outputStream . write ( buffer , 0 , len ) ; } } catch ( Exception ex ) { throw new RuntimeException ( "Error transferring data" , ex ) ; } }
Transfers blocking the bytes from a given InputStream to this response
108
14
143,117
public ServiceInformation get ( String key ) { ServiceInformation info = null ; long hash = algorithm . hash ( key ) ; //Find the first server with a hash key after this one final SortedMap < Long , ServiceInformation > tailMap = ring . tailMap ( hash ) ; //Wrap around to the beginning of the ring, if we went past the last one hash = tailMap . isEmpty ( ) ? ring . firstKey ( ) : tailMap . firstKey ( ) ; info = ring . get ( hash ) ; return info ; }
Returns the appropriate server for the given key .
114
9
143,118
public void addScenario ( Class < ? extends Scenario > scenarioClass , String scenarioID , String initialState , Properties properties , String gatewayDeviceID , String externalLinkID ) throws ShanksException { // throws NonGatewayDeviceException, TooManyConnectionException, // DuplicatedIDException, AlreadyConnectedScenarioException, // SecurityException, NoSuchMethodException, IllegalArgumentException, // InstantiationException, IllegalAccessException, // InvocationTargetException { Constructor < ? extends Scenario > c ; Scenario scenario ; try { c = scenarioClass . getConstructor ( new Class [ ] { String . class , String . class , Properties . class , Logger . class } ) ; scenario = c . newInstance ( scenarioID , initialState , properties , this . getLogger ( ) ) ; } catch ( SecurityException e ) { throw new ShanksException ( e ) ; } catch ( NoSuchMethodException e ) { throw new ShanksException ( e ) ; } catch ( IllegalArgumentException e ) { throw new ShanksException ( e ) ; } catch ( InstantiationException e ) { throw new ShanksException ( e ) ; } catch ( IllegalAccessException e ) { throw new ShanksException ( e ) ; } catch ( InvocationTargetException e ) { throw new ShanksException ( e ) ; } Device gateway = ( Device ) scenario . getNetworkElement ( gatewayDeviceID ) ; Link externalLink = ( Link ) this . getNetworkElement ( externalLinkID ) ; if ( ! scenario . getCurrentElements ( ) . containsKey ( gatewayDeviceID ) ) { throw new NonGatewayDeviceException ( scenario , gateway , externalLink ) ; } else { gateway . connectToLink ( externalLink ) ; if ( ! this . getCurrentElements ( ) . containsKey ( externalLink . getID ( ) ) ) { this . addNetworkElement ( externalLink ) ; } if ( ! this . scenarios . containsKey ( scenario ) ) { this . scenarios . put ( scenario , new ArrayList < Link > ( ) ) ; } else { List < Link > externalLinks = this . scenarios . get ( scenario ) ; if ( ! externalLinks . contains ( externalLink ) ) { externalLinks . add ( externalLink ) ; } else if ( externalLink . getLinkedDevices ( ) . contains ( gateway ) ) { throw new AlreadyConnectedScenarioException ( scenario , gateway , externalLink ) ; } } } }
Add the scenario to the complex scenario .
517
8
143,119
public void addPossiblesFailuresComplex ( ) { Set < Scenario > scenarios = this . getScenarios ( ) ; for ( Scenario s : scenarios ) { for ( Class < ? extends Failure > c : s . getPossibleFailures ( ) . keySet ( ) ) { if ( ! this . getPossibleFailures ( ) . containsKey ( c ) ) { this . addPossibleFailure ( c , s . getPossibleFailures ( ) . get ( c ) ) ; } else { List < Set < NetworkElement >> elements = this . getPossibleFailures ( ) . get ( c ) ; // elements.addAll(s.getPossibleFailures().get(c)); for ( Set < NetworkElement > sne : s . getPossibleFailures ( ) . get ( c ) ) { if ( ! elements . contains ( sne ) ) elements . add ( sne ) ; } this . addPossibleFailure ( c , elements ) ; } } } }
Idem que con los eventos y los dupes
213
11
143,120
public void addPossiblesEventsComplex ( ) { Set < Scenario > scenarios = this . getScenarios ( ) ; for ( Scenario s : scenarios ) { for ( Class < ? extends Event > c : s . getPossibleEventsOfNE ( ) . keySet ( ) ) { if ( ! this . getPossibleEventsOfNE ( ) . containsKey ( c ) ) { this . addPossibleEventsOfNE ( c , s . getPossibleEventsOfNE ( ) . get ( c ) ) ; } else { List < Set < NetworkElement >> elements = this . getPossibleEventsOfNE ( ) . get ( c ) ; // elements.addAll(s.getPossibleEventsOfNE().get(c)); for ( Set < NetworkElement > sne : s . getPossibleEventsOfNE ( ) . get ( c ) ) { if ( ! elements . contains ( sne ) ) elements . add ( sne ) ; } this . addPossibleEventsOfNE ( c , elements ) ; } } for ( Class < ? extends Event > c : s . getPossibleEventsOfScenario ( ) . keySet ( ) ) { if ( ! this . getPossibleEventsOfScenario ( ) . containsKey ( c ) ) { this . addPossibleEventsOfScenario ( c , s . getPossibleEventsOfScenario ( ) . get ( c ) ) ; } else { List < Set < Scenario >> elements = this . getPossibleEventsOfScenario ( ) . get ( c ) ; // elements.addAll(s.getPossibleEventsOfScenario().get(c)); for ( Set < Scenario > sne : s . getPossibleEventsOfScenario ( ) . get ( c ) ) { if ( ! elements . contains ( sne ) ) elements . add ( sne ) ; } this . addPossibleEventsOfScenario ( c , elements ) ; } } } }
J Anadido eventos de escenario y evitado la adiccion de duplicados
413
21
143,121
@ Api public < T > void setOption ( GestureOption < T > option , T value ) { hammertime . setOption ( option , value ) ; }
Change initial settings of this widget .
35
7
143,122
@ Api public void unregisterHandler ( EventType eventType ) { if ( ! jsHandlersMap . containsKey ( eventType ) ) { return ; } HammerGwt . off ( hammertime , eventType , ( NativeHammmerHandler ) jsHandlersMap . remove ( eventType ) ) ; }
Unregister Hammer Gwt handler .
66
7
143,123
private List < String > getChildrenList ( ) { if ( childrenList != null ) return childrenList ; SharedPreferences prefs = loadSharedPreferences ( "children" ) ; String list = prefs . getString ( getId ( ) , null ) ; childrenList = ( list == null ) ? new ArrayList < String > ( ) : new ArrayList <> ( Arrays . asList ( list . split ( "," ) ) ) ; return childrenList ; }
Get a list of child objects ids .
101
9
143,124
public void addChild ( C child ) { SharedPreferences prefs = loadSharedPreferences ( "children" ) ; List < String > objects = getChildrenList ( ) ; Model toPut = ( Model ) child ; if ( objects . indexOf ( toPut . getId ( ) ) != ArrayUtils . INDEX_NOT_FOUND ) { return ; } objects . add ( toPut . getId ( ) ) ; toPut . save ( ) ; prefs . edit ( ) . putString ( String . valueOf ( getId ( ) ) , StringUtils . join ( objects , "," ) ) . commit ( ) ; }
Adds the object to the child ids list .
138
10
143,125
public boolean removeChild ( String id ) { SharedPreferences prefs = loadSharedPreferences ( "children" ) ; List < String > objects = getChildrenList ( ) ; if ( objects . indexOf ( id ) == ArrayUtils . INDEX_NOT_FOUND ) { return false ; } objects . remove ( id ) ; prefs . edit ( ) . putString ( String . valueOf ( getId ( ) ) , StringUtils . join ( objects , "," ) ) . commit ( ) ; return true ; }
Removes the object from the child ids list .
114
11
143,126
public C findChild ( String id ) { int index = getChildrenList ( ) . indexOf ( id ) ; if ( index == ArrayUtils . INDEX_NOT_FOUND ) { return null ; } C child = null ; try { Model dummy = ( Model ) childClazz . newInstance ( ) ; dummy . setContext ( context ) ; child = ( C ) dummy . find ( id ) ; } catch ( InstantiationException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } return child ; }
Find a specific object from the child list .
128
9
143,127
public List < C > findAllChildren ( ) { List < String > objects = getChildrenList ( ) ; List < C > children = new ArrayList < C > ( ) ; try { Model dummy = ( Model ) childClazz . newInstance ( ) ; dummy . setContext ( context ) ; for ( String id : objects ) { children . add ( ( C ) dummy . find ( id ) ) ; } } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } catch ( InstantiationException e ) { e . printStackTrace ( ) ; } return children ; }
Find all objects from the child list .
128
8
143,128
private Collection < Facet > filter ( Collection < Facet > facets ) { if ( NotStopWordPredicate == null ) { return facets ; } return facets . stream ( ) . filter ( NotStopWordPredicate ) . collect ( Collectors . toList ( ) ) ; }
Filter stop word facets
59
4
143,129
public ConsistentHashRing getRing ( String type ) { ConsistentHashRing ring = rings . get ( type ) ; if ( ring != null ) { return ring ; } if ( type == null ) { //If there's no ring without a type, then any type will do //Use weighted random among the types, based on how many servers are serving each type int selection = rand . nextInt ( ) % totalServers ; for ( ConsistentHashRing candidateRing : rings . values ( ) ) { if ( selection <= 0 ) { return candidateRing ; } else { selection -= candidateRing . size ( ) ; } } //It's possible there are no rings Preconditions . checkState ( totalServers == 0 , "It shouldn't be possible to get here, " + "unless there are no rings" ) ; return null ; } else { //If there's no server for this type, then pick one without a type return rings . get ( null ) ; } }
Get the server ring for a particular type .
204
9
143,130
public void add ( DOCUMENT doc ) { if ( doc != null ) { documents . add ( doc ) ; int id = documents . size ( ) - 1 ; for ( KEY key : documentMapper . apply ( doc ) ) { index . put ( key , id ) ; } } }
Add void .
62
3
143,131
public ScriptEnvironment getEnvironment ( String environmentName ) { Preconditions . checkArgument ( StringUtils . isNotNullOrBlank ( environmentName ) , "Environment name cannot be null or empty" ) ; ScriptEngine engine = engineManager . getEngineByName ( environmentName ) ; Preconditions . checkArgument ( engine != null , environmentName + " is an unknown." ) ; environmentName = engine . getFactory ( ) . getEngineName ( ) ; if ( ! environments . containsKey ( environmentName ) ) { environments . put ( environmentName , new ScriptEnvironment ( engine ) ) ; } return environments . get ( environmentName ) ; }
Gets the scripting environment given the environment name .
138
10
143,132
public static ScriptEnvironment getTemporaryEnvironment ( String environmentName ) { Preconditions . checkArgument ( StringUtils . isNotNullOrBlank ( environmentName ) , "Environment name cannot be null or empty" ) ; ScriptEngine engine = ScriptEnvironmentManager . getInstance ( ) . engineManager . getEngineByName ( environmentName ) ; Preconditions . checkArgument ( engine != null , environmentName + " is an unknown." ) ; return new ScriptEnvironment ( engine ) ; }
Gets a temporary scripting environment given the environment name .
104
11
143,133
public String getEnvironmentNameForExtension ( String extension ) { Preconditions . checkArgument ( StringUtils . isNotNullOrBlank ( extension ) , "Extension name cannot be null or empty" ) ; ScriptEngine engine = engineManager . getEngineByExtension ( extension ) ; Preconditions . checkArgument ( engine != null , extension + " is not a recognized scripting extension." ) ; return engine . getFactory ( ) . getLanguageName ( ) ; }
Gets the scripting environment name given the script extension .
102
11
143,134
public Set < Constructor < ? > > getConstructors ( boolean privileged ) { if ( privileged ) { return Collections . unmodifiableSet ( Sets . union ( constructors , declaredConstructors ) ) ; } else { return Collections . unmodifiableSet ( constructors ) ; } }
Gets constructors .
60
5
143,135
public Set < Field > getFields ( boolean privileged ) { if ( privileged ) { return Collections . unmodifiableSet ( Sets . union ( fields , declaredFields ) ) ; } else { return Collections . unmodifiableSet ( fields ) ; } }
Gets fields .
54
4
143,136
protected T getParentFromConfig ( ) { //TODO: Move this to a converter String parentName = Config . get ( canonicalName ( ) , "parent" ) . asString ( null ) ; if ( parentName != null && DynamicEnum . isDefined ( Cast . as ( getClass ( ) ) , parentName ) ) { return DynamicEnum . valueOf ( Cast . as ( getClass ( ) ) , parentName ) ; } else if ( parentName != null ) { try { parentName = parentName . replaceFirst ( Pattern . quote ( getClass ( ) . getCanonicalName ( ) ) , "" ) ; DynamicEnum . register ( Cast . as ( Reflect . onClass ( getClass ( ) ) . invoke ( "create" , parentName ) . get ( ) ) ) ; } catch ( ReflectionException e ) { return null ; } } return null ; }
Determines the parent via a configuration setting .
192
10
143,137
public static HttpHandler createRootHandler ( List < MappedEndpoint > mappedEndpoints , List < Interceptor > rootInterceptors , List < Interceptor > endpointInterceptors , ExceptionMapper exceptionMapper , String basePath , boolean httpTracer ) { final RoutingHandler routingRestHandler = new HttpRootHandler ( false ) ; final PathTemplateHandler websocketHandler = Handlers . pathTemplate ( false ) ; HttpHandler staticHandler = null ; for ( MappedEndpoint me : mappedEndpoints ) { if ( MappedEndpoint . Type . REST . equals ( me . type ) ) { HttpHandler httpDispatcher = new BlockingHandler ( new HttpDispatcher ( new ConnegHandler ( new InterceptorHandler ( me . handler , endpointInterceptors ) , me . mediaTypes ) , exceptionMapper ) ) ; String endpointPath = HandlerUtil . BASE_PATH . equals ( basePath ) ? me . url : basePath + me . url ; HttpHandler httpHandler = wrapCompressionHandler ( httpDispatcher , me ) ; routingRestHandler . add ( me . method , endpointPath , httpHandler ) ; } if ( MappedEndpoint . Type . MULTIPART . equals ( me . type ) ) { HttpHandler httpDispatcher = new BlockingHandler ( new HttpDispatcher ( new ConnegHandler ( new InterceptorHandler ( me . handler , endpointInterceptors ) , me . mediaTypes ) , exceptionMapper ) ) ; String endpointPath = HandlerUtil . BASE_PATH . equals ( basePath ) ? me . url : basePath + me . url ; HttpHandler httpHandler = wrapCompressionHandler ( httpDispatcher , me ) ; routingRestHandler . add ( me . method , endpointPath , httpHandler ) ; } if ( MappedEndpoint . Type . SSE . equals ( me . type ) ) { InterceptorHandler interceptorHandler = new InterceptorHandler ( me . handler , endpointInterceptors ) ; HttpHandler httpHandler = wrapCompressionHandler ( interceptorHandler , me ) ; String endpointPath = HandlerUtil . BASE_PATH . equals ( basePath ) ? me . url : basePath + me . url ; routingRestHandler . add ( me . method , endpointPath , httpHandler ) ; } if ( MappedEndpoint . Type . WS . equals ( me . type ) ) { InterceptorHandler interceptorHandler = new InterceptorHandler ( me . handler , endpointInterceptors ) ; HttpHandler httpHandler = wrapCompressionHandler ( interceptorHandler , me ) ; websocketHandler . add ( me . url , httpHandler ) ; } if ( MappedEndpoint . Type . STATIC . equals ( me . type ) ) { staticHandler = wrapCompressionHandler ( me . handler , me ) ; } } HttpHandler resolved = resolveHandlers ( routingRestHandler , websocketHandler , staticHandler , mappedEndpoints ) ; HttpHandler root = wrapRootInterceptorHandler ( resolved , rootInterceptors ) ; HttpHandler handler = wrapRequestDump ( root , httpTracer ) ; // handler = wrapServerName(handler); return Handlers . gracefulShutdown ( handler ) ; }
chain of responsibility
689
3
143,138
private void increaseLevel ( boolean list ) { level ++ ; if ( hasData . length == level ) { // Grow lists when needed hasData = Arrays . copyOf ( hasData , hasData . length * 2 ) ; lists = Arrays . copyOf ( lists , hasData . length * 2 ) ; } hasData [ level ] = false ; lists [ level ] = list ; }
Increase the level by one .
82
6
143,139
private void writeName ( String name ) throws IOException { if ( shouldOutputName ( ) ) { out . write ( TAG_KEY ) ; writeStringNoTag ( name ) ; } }
Write the name if needed .
40
6
143,140
private void writeIntegerNoTag ( int value ) throws IOException { while ( true ) { if ( ( value & ~ 0x7F ) == 0 ) { out . write ( value ) ; break ; } else { out . write ( ( value & 0x7f ) | 0x80 ) ; value >>>= 7 ; } } }
Write an integer to the output stream without tagging it .
72
11
143,141
private void writeInteger ( int value ) throws IOException { if ( value < 0 ) { out . write ( TAG_NEGATIVE_INT ) ; writeIntegerNoTag ( - value ) ; } else { out . write ( TAG_POSITIVE_INT ) ; writeIntegerNoTag ( value ) ; } }
Write an integer to the output stream .
67
8
143,142
public static boolean check ( String passwd , String hashed ) { try { String [ ] parts = hashed . split ( "\\$" ) ; if ( parts . length != 5 || ! parts [ 1 ] . equals ( "s0" ) ) { throw new IllegalArgumentException ( "Invalid hashed value" ) ; } long params = Long . parseLong ( parts [ 2 ] , 16 ) ; byte [ ] salt = decode ( parts [ 3 ] . toCharArray ( ) ) ; byte [ ] derived0 = decode ( parts [ 4 ] . toCharArray ( ) ) ; int N = ( int ) Math . pow ( 2 , params >> 16 & 0xffff ) ; int r = ( int ) params >> 8 & 0xff ; int p = ( int ) params & 0xff ; byte [ ] derived1 = SCrypt . scrypt ( passwd . getBytes ( "UTF-8" ) , salt , N , r , p , 32 ) ; if ( derived0 . length != derived1 . length ) return false ; int result = 0 ; for ( int i = 0 ; i < derived0 . length ; i ++ ) { result |= derived0 [ i ] ^ derived1 [ i ] ; } return result == 0 ; } catch ( UnsupportedEncodingException e ) { throw new IllegalStateException ( "JVM doesn't support UTF-8?" ) ; } catch ( GeneralSecurityException e ) { throw new IllegalStateException ( "JVM doesn't support SHA1PRNG or HMAC_SHA256?" ) ; } }
Compare the supplied plaintext password to a hashed password .
331
12
143,143
public static Platform detect ( ) throws UnsupportedPlatformException { String osArch = getProperty ( "os.arch" ) ; String osName = getProperty ( "os.name" ) ; for ( Arch arch : Arch . values ( ) ) { if ( arch . pattern . matcher ( osArch ) . matches ( ) ) { for ( OS os : OS . values ( ) ) { if ( os . pattern . matcher ( osName ) . matches ( ) ) { return new Platform ( arch , os ) ; } } } } String msg = String . format ( "Unsupported platform %s %s" , osArch , osName ) ; throw new UnsupportedPlatformException ( msg ) ; }
Attempt to detect the current platform .
148
7
143,144
public < T > T getNodeMetaData ( Object key ) { if ( metaDataMap == null ) { return ( T ) null ; } return ( T ) metaDataMap . get ( key ) ; }
Gets the node meta data .
44
7
143,145
public void copyNodeMetaData ( ASTNode other ) { if ( other . metaDataMap == null ) { return ; } if ( metaDataMap == null ) { metaDataMap = new ListHashMap ( ) ; } metaDataMap . putAll ( other . metaDataMap ) ; }
Copies all node meta data from the other node to this one
62
13
143,146
public void setNodeMetaData ( Object key , Object value ) { if ( key == null ) throw new GroovyBugError ( "Tried to set meta data with null key on " + this + "." ) ; if ( metaDataMap == null ) { metaDataMap = new ListHashMap ( ) ; } Object old = metaDataMap . put ( key , value ) ; if ( old != null ) throw new GroovyBugError ( "Tried to overwrite existing meta data " + this + "." ) ; }
Sets the node meta data .
111
7
143,147
public Object putNodeMetaData ( Object key , Object value ) { if ( key == null ) throw new GroovyBugError ( "Tried to set meta data with null key on " + this + "." ) ; if ( metaDataMap == null ) { metaDataMap = new ListHashMap ( ) ; } return metaDataMap . put ( key , value ) ; }
Sets the node meta data but allows overwriting values .
80
13
143,148
public void removeNodeMetaData ( Object key ) { if ( key == null ) throw new GroovyBugError ( "Tried to remove meta data with null key " + this + "." ) ; if ( metaDataMap == null ) { return ; } metaDataMap . remove ( key ) ; }
Removes a node meta data entry .
64
8
143,149
public RangeInfo subListBorders ( int size ) { if ( inclusive == null ) throw new IllegalStateException ( "Should not call subListBorders on a non-inclusive aware IntRange" ) ; int tempFrom = from ; if ( tempFrom < 0 ) { tempFrom += size ; } int tempTo = to ; if ( tempTo < 0 ) { tempTo += size ; } if ( tempFrom > tempTo ) { return new RangeInfo ( inclusive ? tempTo : tempTo + 1 , tempFrom + 1 , true ) ; } return new RangeInfo ( tempFrom , inclusive ? tempTo + 1 : tempTo , false ) ; }
A method for determining from and to information when using this IntRange to index an aggregate object of the specified size . Normally only used internally within Groovy but useful if adding range indexing support for your own aggregates .
139
44
143,150
protected void createSetterMethod ( ClassNode declaringClass , PropertyNode propertyNode , String setterName , Statement setterBlock ) { MethodNode setter = new MethodNode ( setterName , propertyNode . getModifiers ( ) , ClassHelper . VOID_TYPE , params ( param ( propertyNode . getType ( ) , "value" ) ) , ClassNode . EMPTY_ARRAY , setterBlock ) ; setter . setSynthetic ( true ) ; // add it to the class declaringClass . addMethod ( setter ) ; }
Creates a setter method with the given body .
118
11
143,151
public void applyToPrimaryClassNodes ( PrimaryClassNodeOperation body ) throws CompilationFailedException { Iterator classNodes = getPrimaryClassNodes ( body . needSortedInput ( ) ) . iterator ( ) ; while ( classNodes . hasNext ( ) ) { SourceUnit context = null ; try { ClassNode classNode = ( ClassNode ) classNodes . next ( ) ; context = classNode . getModule ( ) . getContext ( ) ; if ( context == null || context . phase < phase || ( context . phase == phase && ! context . phaseComplete ) ) { int offset = 1 ; Iterator < InnerClassNode > iterator = classNode . getInnerClasses ( ) ; while ( iterator . hasNext ( ) ) { iterator . next ( ) ; offset ++ ; } body . call ( context , new GeneratorContext ( this . ast , offset ) , classNode ) ; } } catch ( CompilationFailedException e ) { // fall through, getErrorReporter().failIfErrors() will trigger } catch ( NullPointerException npe ) { GroovyBugError gbe = new GroovyBugError ( "unexpected NullpointerException" , npe ) ; changeBugText ( gbe , context ) ; throw gbe ; } catch ( GroovyBugError e ) { changeBugText ( e , context ) ; throw e ; } catch ( NoClassDefFoundError e ) { // effort to get more logging in case a dependency of a class is loaded // although it shouldn't have convertUncaughtExceptionToCompilationError ( e ) ; } catch ( Exception e ) { convertUncaughtExceptionToCompilationError ( e ) ; } } getErrorCollector ( ) . failIfErrors ( ) ; }
A loop driver for applying operations to all primary ClassNodes in our AST . Automatically skips units that have already been processed through the current phase .
375
31
143,152
public static < T > T withStreams ( Socket socket , @ ClosureParams ( value = SimpleType . class , options = { "java.io.InputStream" , "java.io.OutputStream" } ) Closure < T > closure ) throws IOException { InputStream input = socket . getInputStream ( ) ; OutputStream output = socket . getOutputStream ( ) ; try { T result = closure . call ( new Object [ ] { input , output } ) ; InputStream temp1 = input ; input = null ; temp1 . close ( ) ; OutputStream temp2 = output ; output = null ; temp2 . close ( ) ; return result ; } finally { closeWithWarning ( input ) ; closeWithWarning ( output ) ; } }
Passes the Socket s InputStream and OutputStream to the closure . The streams will be closed after the closure returns even if an exception is thrown .
161
30
143,153
public static < T > T withObjectStreams ( Socket socket , @ ClosureParams ( value = SimpleType . class , options = { "java.io.ObjectInputStream" , "java.io.ObjectOutputStream" } ) Closure < T > closure ) throws IOException { InputStream input = socket . getInputStream ( ) ; OutputStream output = socket . getOutputStream ( ) ; ObjectOutputStream oos = new ObjectOutputStream ( output ) ; ObjectInputStream ois = new ObjectInputStream ( input ) ; try { T result = closure . call ( new Object [ ] { ois , oos } ) ; InputStream temp1 = ois ; ois = null ; temp1 . close ( ) ; temp1 = input ; input = null ; temp1 . close ( ) ; OutputStream temp2 = oos ; oos = null ; temp2 . close ( ) ; temp2 = output ; output = null ; temp2 . close ( ) ; return result ; } finally { closeWithWarning ( ois ) ; closeWithWarning ( input ) ; closeWithWarning ( oos ) ; closeWithWarning ( output ) ; } }
Creates an InputObjectStream and an OutputObjectStream from a Socket and passes them to the closure . The streams will be closed after the closure returns even if an exception is thrown .
246
37
143,154
public MethodKey createCopy ( ) { int size = getParameterCount ( ) ; Class [ ] paramTypes = new Class [ size ] ; for ( int i = 0 ; i < size ; i ++ ) { paramTypes [ i ] = getParameterType ( i ) ; } return new DefaultMethodKey ( sender , name , paramTypes , isCallToSuper ) ; }
Creates an immutable copy that we can cache .
78
10
143,155
public static void doExtendTraits ( final ClassNode cNode , final SourceUnit unit , final CompilationUnit cu ) { if ( cNode . isInterface ( ) ) return ; boolean isItselfTrait = Traits . isTrait ( cNode ) ; SuperCallTraitTransformer superCallTransformer = new SuperCallTraitTransformer ( unit ) ; if ( isItselfTrait ) { checkTraitAllowed ( cNode , unit ) ; return ; } if ( ! cNode . getNameWithoutPackage ( ) . endsWith ( Traits . TRAIT_HELPER ) ) { List < ClassNode > traits = findTraits ( cNode ) ; for ( ClassNode trait : traits ) { TraitHelpersTuple helpers = Traits . findHelpers ( trait ) ; applyTrait ( trait , cNode , helpers ) ; superCallTransformer . visitClass ( cNode ) ; if ( unit != null ) { ASTTransformationCollectorCodeVisitor collector = new ASTTransformationCollectorCodeVisitor ( unit , cu . getTransformLoader ( ) ) ; collector . visitClass ( cNode ) ; } } } }
Given a class node if this class node implements a trait then generate all the appropriate code which delegates calls to the trait . It is safe to call this method on a class node which does not implement a trait .
248
42
143,156
public SyntaxException getSyntaxError ( int index ) { SyntaxException exception = null ; Message message = getError ( index ) ; if ( message != null && message instanceof SyntaxErrorMessage ) { exception = ( ( SyntaxErrorMessage ) message ) . getCause ( ) ; } return exception ; }
Convenience routine to return the specified error s underlying SyntaxException or null if it isn t one .
66
22
143,157
private void gobble ( Iterator iter ) { if ( eatTheRest ) { while ( iter . hasNext ( ) ) { tokens . add ( iter . next ( ) ) ; } } }
Adds the remaining tokens to the processed tokens list .
41
10
143,158
public static int allParametersAndArgumentsMatch ( Parameter [ ] params , ClassNode [ ] args ) { if ( params == null ) { params = Parameter . EMPTY_ARRAY ; } int dist = 0 ; if ( args . length < params . length ) return - 1 ; // we already know the lengths are equal for ( int i = 0 ; i < params . length ; i ++ ) { ClassNode paramType = params [ i ] . getType ( ) ; ClassNode argType = args [ i ] ; if ( ! isAssignableTo ( argType , paramType ) ) return - 1 ; else { if ( ! paramType . equals ( argType ) ) dist += getDistance ( argType , paramType ) ; } } return dist ; }
Checks that arguments and parameter types match .
163
9
143,159
static int excessArgumentsMatchesVargsParameter ( Parameter [ ] params , ClassNode [ ] args ) { // we already know parameter length is bigger zero and last is a vargs // the excess arguments are all put in an array for the vargs call // so check against the component type int dist = 0 ; ClassNode vargsBase = params [ params . length - 1 ] . getType ( ) . getComponentType ( ) ; for ( int i = params . length ; i < args . length ; i ++ ) { if ( ! isAssignableTo ( args [ i ] , vargsBase ) ) return - 1 ; else if ( ! args [ i ] . equals ( vargsBase ) ) dist += getDistance ( args [ i ] , vargsBase ) ; } return dist ; }
Checks that excess arguments match the vararg signature parameter .
170
12
143,160
static int lastArgMatchesVarg ( Parameter [ ] params , ClassNode ... args ) { if ( ! isVargs ( params ) ) return - 1 ; // case length ==0 handled already // we have now two cases, // the argument is wrapped in the vargs array or // the argument is an array that can be used for the vargs part directly // we test only the wrapping part, since the non wrapping is done already ClassNode lastParamType = params [ params . length - 1 ] . getType ( ) ; ClassNode ptype = lastParamType . getComponentType ( ) ; ClassNode arg = args [ args . length - 1 ] ; if ( isNumberType ( ptype ) && isNumberType ( arg ) && ! ptype . equals ( arg ) ) return - 1 ; return isAssignableTo ( arg , ptype ) ? Math . min ( getDistance ( arg , lastParamType ) , getDistance ( arg , ptype ) ) : - 1 ; }
Checks if the last argument matches the vararg type .
210
12
143,161
private static Parameter buildParameter ( final Map < String , GenericsType > genericFromReceiver , final Map < String , GenericsType > placeholdersFromContext , final Parameter methodParameter , final ClassNode paramType ) { if ( genericFromReceiver . isEmpty ( ) && ( placeholdersFromContext == null || placeholdersFromContext . isEmpty ( ) ) ) { return methodParameter ; } if ( paramType . isArray ( ) ) { ClassNode componentType = paramType . getComponentType ( ) ; Parameter subMethodParameter = new Parameter ( componentType , methodParameter . getName ( ) ) ; Parameter component = buildParameter ( genericFromReceiver , placeholdersFromContext , subMethodParameter , componentType ) ; return new Parameter ( component . getType ( ) . makeArray ( ) , component . getName ( ) ) ; } ClassNode resolved = resolveClassNodeGenerics ( genericFromReceiver , placeholdersFromContext , paramType ) ; return new Parameter ( resolved , methodParameter . getName ( ) ) ; }
Given a parameter builds a new parameter for which the known generics placeholders are resolved .
224
18
143,162
public static boolean isClassClassNodeWrappingConcreteType ( ClassNode classNode ) { GenericsType [ ] genericsTypes = classNode . getGenericsTypes ( ) ; return ClassHelper . CLASS_Type . equals ( classNode ) && classNode . isUsingGenerics ( ) && genericsTypes != null && ! genericsTypes [ 0 ] . isPlaceholder ( ) && ! genericsTypes [ 0 ] . isWildcard ( ) ; }
Returns true if the class node represents a the class node for the Class class and if the parametrized type is a neither a placeholder or a wildcard . For example the class node Class&lt ; Foo&gt ; where Foo is a class would return true but the class node for Class&lt ; ?&gt ; would return false .
97
71
143,163
public static < T > T splitEachLine ( InputStream stream , String regex , String charset , @ ClosureParams ( value = FromString . class , options = "List<String>" ) Closure < T > closure ) throws IOException { return splitEachLine ( new BufferedReader ( new InputStreamReader ( stream , charset ) ) , regex , closure ) ; }
Iterates through the given InputStream line by line using the specified encoding splitting each line using the given separator . The list of tokens for each line is then passed to the given closure . Finally the stream is closed .
81
44
143,164
public static void transformChar ( Reader self , Writer writer , @ ClosureParams ( value = SimpleType . class , options = "java.lang.String" ) Closure closure ) throws IOException { int c ; try { char [ ] chars = new char [ 1 ] ; while ( ( c = self . read ( ) ) != - 1 ) { chars [ 0 ] = ( char ) c ; writer . write ( ( String ) closure . call ( new String ( chars ) ) ) ; } writer . flush ( ) ; Writer temp2 = writer ; writer = null ; temp2 . close ( ) ; Reader temp1 = self ; self = null ; temp1 . close ( ) ; } finally { closeWithWarning ( self ) ; closeWithWarning ( writer ) ; } }
Transforms each character from this reader by passing it to the given closure . The Closure should return each transformed character which will be passed to the Writer . The reader and writer will be both be closed before this method returns .
164
45
143,165
public static < T , U extends Closeable > T withCloseable ( U self , @ ClosureParams ( value = FirstParam . class ) Closure < T > action ) throws IOException { try { T result = action . call ( self ) ; Closeable temp = self ; self = null ; temp . close ( ) ; return result ; } finally { DefaultGroovyMethodsSupport . closeWithWarning ( self ) ; } }
Allows this closeable to be used within the closure ensuring that it is closed once the closure has been executed and before this method returns .
91
27
143,166
public Object getProperty ( Object object ) { return java . lang . reflect . Array . getLength ( object ) ; }
Get this property from the given object .
25
8
143,167
protected MethodVisitor makeDelegateCall ( final String name , final String desc , final String signature , final String [ ] exceptions , final int accessFlags ) { MethodVisitor mv = super . visitMethod ( accessFlags , name , desc , signature , exceptions ) ; mv . visitVarInsn ( ALOAD , 0 ) ; // load this mv . visitFieldInsn ( GETFIELD , proxyName , DELEGATE_OBJECT_FIELD , BytecodeHelper . getTypeDescription ( delegateClass ) ) ; // load delegate // using InvokerHelper to allow potential intercepted calls int size ; mv . visitLdcInsn ( name ) ; // method name Type [ ] args = Type . getArgumentTypes ( desc ) ; BytecodeHelper . pushConstant ( mv , args . length ) ; mv . visitTypeInsn ( ANEWARRAY , "java/lang/Object" ) ; size = 6 ; int idx = 1 ; for ( int i = 0 ; i < args . length ; i ++ ) { Type arg = args [ i ] ; mv . visitInsn ( DUP ) ; BytecodeHelper . pushConstant ( mv , i ) ; // primitive types must be boxed if ( isPrimitive ( arg ) ) { mv . visitIntInsn ( getLoadInsn ( arg ) , idx ) ; String wrappedType = getWrappedClassDescriptor ( arg ) ; mv . visitMethodInsn ( INVOKESTATIC , wrappedType , "valueOf" , "(" + arg . getDescriptor ( ) + ")L" + wrappedType + ";" , false ) ; } else { mv . visitVarInsn ( ALOAD , idx ) ; // load argument i } size = Math . max ( size , 5 + registerLen ( arg ) ) ; idx += registerLen ( arg ) ; mv . visitInsn ( AASTORE ) ; // store value into array } mv . visitMethodInsn ( INVOKESTATIC , "org/codehaus/groovy/runtime/InvokerHelper" , "invokeMethod" , "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;" , false ) ; unwrapResult ( mv , desc ) ; mv . visitMaxs ( size , registerLen ( args ) + 1 ) ; return mv ; }
Generate a call to the delegate object .
521
9
143,168
public static Method getSAMMethod ( Class < ? > c ) { // SAM = single public abstract method // if the class is not abstract there is no abstract method if ( ! Modifier . isAbstract ( c . getModifiers ( ) ) ) return null ; if ( c . isInterface ( ) ) { Method [ ] methods = c . getMethods ( ) ; // res stores the first found abstract method Method res = null ; for ( Method mi : methods ) { // ignore methods, that are not abstract and from Object if ( ! Modifier . isAbstract ( mi . getModifiers ( ) ) ) continue ; // ignore trait methods which have a default implementation if ( mi . getAnnotation ( Traits . Implemented . class ) != null ) continue ; try { Object . class . getMethod ( mi . getName ( ) , mi . getParameterTypes ( ) ) ; continue ; } catch ( NoSuchMethodException e ) { /*ignore*/ } // we have two methods, so no SAM if ( res != null ) return null ; res = mi ; } return res ; } else { LinkedList < Method > methods = new LinkedList ( ) ; getAbstractMethods ( c , methods ) ; if ( methods . isEmpty ( ) ) return null ; ListIterator < Method > it = methods . listIterator ( ) ; while ( it . hasNext ( ) ) { Method m = it . next ( ) ; if ( hasUsableImplementation ( c , m ) ) it . remove ( ) ; } return getSingleNonDuplicateMethod ( methods ) ; } }
returns the abstract method from a SAM type if it is a SAM type .
332
16
143,169
protected void generateMopCalls ( LinkedList < MethodNode > mopCalls , boolean useThis ) { for ( MethodNode method : mopCalls ) { String name = getMopMethodName ( method , useThis ) ; Parameter [ ] parameters = method . getParameters ( ) ; String methodDescriptor = BytecodeHelper . getMethodDescriptor ( method . getReturnType ( ) , method . getParameters ( ) ) ; MethodVisitor mv = controller . getClassVisitor ( ) . visitMethod ( ACC_PUBLIC | ACC_SYNTHETIC , name , methodDescriptor , null , null ) ; controller . setMethodVisitor ( mv ) ; mv . visitVarInsn ( ALOAD , 0 ) ; int newRegister = 1 ; OperandStack operandStack = controller . getOperandStack ( ) ; for ( Parameter parameter : parameters ) { ClassNode type = parameter . getType ( ) ; operandStack . load ( parameter . getType ( ) , newRegister ) ; // increment to next register, double/long are using two places newRegister ++ ; if ( type == ClassHelper . double_TYPE || type == ClassHelper . long_TYPE ) newRegister ++ ; } operandStack . remove ( parameters . length ) ; ClassNode declaringClass = method . getDeclaringClass ( ) ; // JDK 8 support for default methods in interfaces // this should probably be strenghtened when we support the A.super.foo() syntax int opcode = declaringClass . isInterface ( ) ? INVOKEINTERFACE : INVOKESPECIAL ; mv . visitMethodInsn ( opcode , BytecodeHelper . getClassInternalName ( declaringClass ) , method . getName ( ) , methodDescriptor , opcode == INVOKEINTERFACE ) ; BytecodeHelper . doReturn ( mv , method . getReturnType ( ) ) ; mv . visitMaxs ( 0 , 0 ) ; mv . visitEnd ( ) ; controller . getClassNode ( ) . addMethod ( name , ACC_PUBLIC | ACC_SYNTHETIC , method . getReturnType ( ) , parameters , null , null ) ; } }
generates a Meta Object Protocol method that is used to call a non public method or to make a call to super .
474
24
143,170
public static ClassNode getWrapper ( ClassNode cn ) { cn = cn . redirect ( ) ; if ( ! isPrimitiveType ( cn ) ) return cn ; if ( cn == boolean_TYPE ) { return Boolean_TYPE ; } else if ( cn == byte_TYPE ) { return Byte_TYPE ; } else if ( cn == char_TYPE ) { return Character_TYPE ; } else if ( cn == short_TYPE ) { return Short_TYPE ; } else if ( cn == int_TYPE ) { return Integer_TYPE ; } else if ( cn == long_TYPE ) { return Long_TYPE ; } else if ( cn == float_TYPE ) { return Float_TYPE ; } else if ( cn == double_TYPE ) { return Double_TYPE ; } else if ( cn == VOID_TYPE ) { return void_WRAPPER_TYPE ; } else { return cn ; } }
Creates a ClassNode containing the wrapper of a ClassNode of primitive type . Any ClassNode representing a primitive type should be created using the predefined types used in class . The method will check the parameter for known references of ClassNode representing a primitive type . If Reference is found then a ClassNode will be contained that represents the wrapper class . For example for boolean the wrapper class is java . lang . Boolean .
205
83
143,171
public static MethodNode findSAM ( ClassNode type ) { if ( ! Modifier . isAbstract ( type . getModifiers ( ) ) ) return null ; if ( type . isInterface ( ) ) { List < MethodNode > methods = type . getMethods ( ) ; MethodNode found = null ; for ( MethodNode mi : methods ) { // ignore methods, that are not abstract and from Object if ( ! Modifier . isAbstract ( mi . getModifiers ( ) ) ) continue ; // ignore trait methods which have a default implementation if ( Traits . hasDefaultImplementation ( mi ) ) continue ; if ( mi . getDeclaringClass ( ) . equals ( OBJECT_TYPE ) ) continue ; if ( OBJECT_TYPE . getDeclaredMethod ( mi . getName ( ) , mi . getParameters ( ) ) != null ) continue ; // we have two methods, so no SAM if ( found != null ) return null ; found = mi ; } return found ; } else { List < MethodNode > methods = type . getAbstractMethods ( ) ; MethodNode found = null ; if ( methods != null ) { for ( MethodNode mi : methods ) { if ( ! hasUsableImplementation ( type , mi ) ) { if ( found != null ) return null ; found = mi ; } } } return found ; } }
Returns the single abstract method of a class node if it is a SAM type or null otherwise .
281
19
143,172
public static int getPrecedence ( int type , boolean throwIfInvalid ) { switch ( type ) { case LEFT_PARENTHESIS : return 0 ; case EQUAL : case PLUS_EQUAL : case MINUS_EQUAL : case MULTIPLY_EQUAL : case DIVIDE_EQUAL : case INTDIV_EQUAL : case MOD_EQUAL : case POWER_EQUAL : case LOGICAL_OR_EQUAL : case LOGICAL_AND_EQUAL : case LEFT_SHIFT_EQUAL : case RIGHT_SHIFT_EQUAL : case RIGHT_SHIFT_UNSIGNED_EQUAL : case BITWISE_OR_EQUAL : case BITWISE_AND_EQUAL : case BITWISE_XOR_EQUAL : return 5 ; case QUESTION : return 10 ; case LOGICAL_OR : return 15 ; case LOGICAL_AND : return 20 ; case BITWISE_OR : case BITWISE_AND : case BITWISE_XOR : return 22 ; case COMPARE_IDENTICAL : case COMPARE_NOT_IDENTICAL : return 24 ; case COMPARE_NOT_EQUAL : case COMPARE_EQUAL : case COMPARE_LESS_THAN : case COMPARE_LESS_THAN_EQUAL : case COMPARE_GREATER_THAN : case COMPARE_GREATER_THAN_EQUAL : case COMPARE_TO : case FIND_REGEX : case MATCH_REGEX : case KEYWORD_INSTANCEOF : return 25 ; case DOT_DOT : case DOT_DOT_DOT : return 30 ; case LEFT_SHIFT : case RIGHT_SHIFT : case RIGHT_SHIFT_UNSIGNED : return 35 ; case PLUS : case MINUS : return 40 ; case MULTIPLY : case DIVIDE : case INTDIV : case MOD : return 45 ; case NOT : case REGEX_PATTERN : return 50 ; case SYNTH_CAST : return 55 ; case PLUS_PLUS : case MINUS_MINUS : case PREFIX_PLUS_PLUS : case PREFIX_MINUS_MINUS : case POSTFIX_PLUS_PLUS : case POSTFIX_MINUS_MINUS : return 65 ; case PREFIX_PLUS : case PREFIX_MINUS : return 70 ; case POWER : return 72 ; case SYNTH_METHOD : case LEFT_SQUARE_BRACKET : return 75 ; case DOT : case NAVIGATE : return 80 ; case KEYWORD_NEW : return 85 ; } if ( throwIfInvalid ) { throw new GroovyBugError ( "precedence requested for non-operator" ) ; } return - 1 ; }
Returns the precedence of the specified operator . Non - operator s will receive - 1 or a GroovyBugError depending on your preference .
607
27
143,173
public < T > T with ( Closure < T > closure ) { return DefaultGroovyMethods . with ( null , closure ) ; }
Allows the closure to be called for NullObject
29
9
143,174
private static boolean implementsMethod ( ClassNode classNode , String methodName , Class [ ] argTypes ) { List methods = classNode . getMethods ( ) ; if ( argTypes == null || argTypes . length == 0 ) { for ( Iterator i = methods . iterator ( ) ; i . hasNext ( ) ; ) { MethodNode mn = ( MethodNode ) i . next ( ) ; boolean methodMatch = mn . getName ( ) . equals ( methodName ) ; if ( methodMatch ) return true ; // TODO Implement further parameter analysis } } return false ; }
Tests whether the ClassNode implements the specified method name
123
11
143,175
public String getTypeDescriptor ( ) { if ( typeDescriptor == null ) { StringBuilder buf = new StringBuilder ( name . length ( ) + parameters . length * 10 ) ; buf . append ( returnType . getName ( ) ) ; buf . append ( ' ' ) ; buf . append ( name ) ; buf . append ( ' ' ) ; for ( int i = 0 ; i < parameters . length ; i ++ ) { if ( i > 0 ) { buf . append ( ", " ) ; } Parameter param = parameters [ i ] ; buf . append ( formatTypeName ( param . getType ( ) ) ) ; } buf . append ( ' ' ) ; typeDescriptor = buf . toString ( ) ; } return typeDescriptor ; }
The type descriptor for a method node is a string containing the name of the method its return type and its parameter types in a canonical form . For simplicity I m using the format of a Java declaration without parameter names .
165
43
143,176
@ Override public String getText ( ) { String retType = AstToTextHelper . getClassText ( returnType ) ; String exceptionTypes = AstToTextHelper . getThrowsClauseText ( exceptions ) ; String parms = AstToTextHelper . getParametersText ( parameters ) ; return AstToTextHelper . getModifiersText ( modifiers ) + " " + retType + " " + name + "(" + parms + ") " + exceptionTypes + " { ... }" ; }
Provides a nicely formatted string of the method definition . For simplicity generic types on some of the elements are not displayed .
107
24
143,177
public GroovyConstructorDoc [ ] constructors ( ) { Collections . sort ( constructors ) ; return constructors . toArray ( new GroovyConstructorDoc [ constructors . size ( ) ] ) ; }
returns a sorted array of constructors
45
8
143,178
public GroovyClassDoc [ ] innerClasses ( ) { Collections . sort ( nested ) ; return nested . toArray ( new GroovyClassDoc [ nested . size ( ) ] ) ; }
returns a sorted array of nested classes and interfaces
41
10
143,179
public GroovyFieldDoc [ ] fields ( ) { Collections . sort ( fields ) ; return fields . toArray ( new GroovyFieldDoc [ fields . size ( ) ] ) ; }
returns a sorted array of fields
39
7
143,180
public GroovyFieldDoc [ ] properties ( ) { Collections . sort ( properties ) ; return properties . toArray ( new GroovyFieldDoc [ properties . size ( ) ] ) ; }
returns a sorted array of properties
39
7
143,181
public GroovyFieldDoc [ ] enumConstants ( ) { Collections . sort ( enumConstants ) ; return enumConstants . toArray ( new GroovyFieldDoc [ enumConstants . size ( ) ] ) ; }
returns a sorted array of enum constants
47
8
143,182
public GroovyMethodDoc [ ] methods ( ) { Collections . sort ( methods ) ; return methods . toArray ( new GroovyMethodDoc [ methods . size ( ) ] ) ; }
returns a sorted array of methods
39
7
143,183
public void add ( Map < String , Object > map ) throws SQLException { if ( withinDataSetBatch ) { if ( batchData . size ( ) == 0 ) { batchKeys = map . keySet ( ) ; } else { if ( ! map . keySet ( ) . equals ( batchKeys ) ) { throw new IllegalArgumentException ( "Inconsistent keys found for batch add!" ) ; } } batchData . add ( map ) ; return ; } int answer = executeUpdate ( buildListQuery ( map ) , new ArrayList < Object > ( map . values ( ) ) ) ; if ( answer != 1 ) { LOG . warning ( "Should have updated 1 row not " + answer + " when trying to add: " + map ) ; } }
Adds the provided map of key - value pairs as a new row in the table represented by this DataSet .
164
22
143,184
public void each ( int offset , int maxRows , Closure closure ) throws SQLException { eachRow ( getSql ( ) , getParameters ( ) , offset , maxRows , closure ) ; }
Calls the provided closure for a page of rows from the table represented by this DataSet . A page is defined as starting at a 1 - based offset and containing a maximum number of rows .
46
39
143,185
private void wrapSetterMethod ( ClassNode classNode , boolean bindable , String propertyName ) { String getterName = "get" + MetaClassHelper . capitalize ( propertyName ) ; MethodNode setter = classNode . getSetterMethod ( "set" + MetaClassHelper . capitalize ( propertyName ) ) ; if ( setter != null ) { // Get the existing code block Statement code = setter . getCode ( ) ; Expression oldValue = varX ( "$oldValue" ) ; Expression newValue = varX ( "$newValue" ) ; Expression proposedValue = varX ( setter . getParameters ( ) [ 0 ] . getName ( ) ) ; BlockStatement block = new BlockStatement ( ) ; // create a local variable to hold the old value from the getter block . addStatement ( declS ( oldValue , callThisX ( getterName ) ) ) ; // add the fireVetoableChange method call block . addStatement ( stmt ( callThisX ( "fireVetoableChange" , args ( constX ( propertyName ) , oldValue , proposedValue ) ) ) ) ; // call the existing block, which will presumably set the value properly block . addStatement ( code ) ; if ( bindable ) { // get the new value to emit in the event block . addStatement ( declS ( newValue , callThisX ( getterName ) ) ) ; // add the firePropertyChange method call block . addStatement ( stmt ( callThisX ( "firePropertyChange" , args ( constX ( propertyName ) , oldValue , newValue ) ) ) ) ; } // replace the existing code block with our new one setter . setCode ( block ) ; } }
Wrap an existing setter .
364
7
143,186
public static long directorySize ( File self ) throws IOException , IllegalArgumentException { final long [ ] size = { 0L } ; eachFileRecurse ( self , FileType . FILES , new Closure < Void > ( null ) { public void doCall ( Object [ ] args ) { size [ 0 ] += ( ( File ) args [ 0 ] ) . length ( ) ; } } ) ; return size [ 0 ] ; }
Calculates directory size as total size of all its files recursively .
93
16
143,187
public static < T > T splitEachLine ( File self , String regex , @ ClosureParams ( value = SimpleType . class , options = "java.lang.String[]" ) Closure < T > closure ) throws IOException { return IOGroovyMethods . splitEachLine ( newReader ( self ) , regex , closure ) ; }
Iterates through this file line by line splitting each line using the given regex separator . For each line the given closure is called with a single parameter being the list of strings computed by splitting the line around matches of the given regular expression . Finally the resources used for processing the file are closed .
74
59
143,188
public static void write ( File file , String text , String charset ) throws IOException { Writer writer = null ; try { FileOutputStream out = new FileOutputStream ( file ) ; writeUTF16BomIfRequired ( charset , out ) ; writer = new OutputStreamWriter ( out , charset ) ; writer . write ( text ) ; writer . flush ( ) ; Writer temp = writer ; writer = null ; temp . close ( ) ; } finally { closeWithWarning ( writer ) ; } }
Write the text to the File using the specified encoding .
106
11
143,189
public static void append ( File file , Object text ) throws IOException { Writer writer = null ; try { writer = new FileWriter ( file , true ) ; InvokerHelper . write ( writer , text ) ; writer . flush ( ) ; Writer temp = writer ; writer = null ; temp . close ( ) ; } finally { closeWithWarning ( writer ) ; } }
Append the text at the end of the File .
77
11
143,190
public static void append ( File file , Object text , String charset ) throws IOException { Writer writer = null ; try { FileOutputStream out = new FileOutputStream ( file , true ) ; if ( ! file . exists ( ) ) { writeUTF16BomIfRequired ( charset , out ) ; } writer = new OutputStreamWriter ( out , charset ) ; InvokerHelper . write ( writer , text ) ; writer . flush ( ) ; Writer temp = writer ; writer = null ; temp . close ( ) ; } finally { closeWithWarning ( writer ) ; } }
Append the text at the end of the File using a specified encoding .
123
15
143,191
public static void append ( File file , Writer writer , String charset ) throws IOException { appendBuffered ( file , writer , charset ) ; }
Append the text supplied by the Writer at the end of the File using a specified encoding .
32
19
143,192
private static void writeUtf16Bom ( OutputStream stream , boolean bigEndian ) throws IOException { if ( bigEndian ) { stream . write ( - 2 ) ; stream . write ( - 1 ) ; } else { stream . write ( - 1 ) ; stream . write ( - 2 ) ; } }
Write a Byte Order Mark at the beginning of the file
67
11
143,193
protected Class getClassCacheEntry ( String name ) { if ( name == null ) return null ; synchronized ( classCache ) { return classCache . get ( name ) ; } }
gets a class from the class cache . This cache contains only classes loaded through this class loader or an InnerLoader instance . If no class is stored for a specific name then the method should return null .
37
40
143,194
public MetaClassRegistryChangeEventListener [ ] getMetaClassRegistryChangeEventListeners ( ) { synchronized ( changeListenerList ) { ArrayList < MetaClassRegistryChangeEventListener > ret = new ArrayList < MetaClassRegistryChangeEventListener > ( changeListenerList . size ( ) + nonRemoveableChangeListenerList . size ( ) ) ; ret . addAll ( nonRemoveableChangeListenerList ) ; ret . addAll ( changeListenerList ) ; return ret . toArray ( new MetaClassRegistryChangeEventListener [ ret . size ( ) ] ) ; } }
Gets an array of of all registered ConstantMetaClassListener instances .
123
14
143,195
public static MetaClassRegistry getInstance ( int includeExtension ) { if ( includeExtension != DONT_LOAD_DEFAULT ) { if ( instanceInclude == null ) { instanceInclude = new MetaClassRegistryImpl ( ) ; } return instanceInclude ; } else { if ( instanceExclude == null ) { instanceExclude = new MetaClassRegistryImpl ( DONT_LOAD_DEFAULT ) ; } return instanceExclude ; } }
Singleton of MetaClassRegistry .
98
8
143,196
public CSTNode get ( int index ) { CSTNode element = null ; if ( index < size ( ) ) { element = ( CSTNode ) elements . get ( index ) ; } return element ; }
Returns the specified element or null .
42
7
143,197
public CSTNode set ( int index , CSTNode element ) { if ( elements == null ) { throw new GroovyBugError ( "attempt to set() on a EMPTY Reduction" ) ; } if ( index == 0 && ! ( element instanceof Token ) ) { // // It's not the greatest of design that the interface allows this, but it // is a tradeoff with convenience, and the convenience is more important. throw new GroovyBugError ( "attempt to set() a non-Token as root of a Reduction" ) ; } // // Fill slots with nulls, if necessary. int count = elements . size ( ) ; if ( index >= count ) { for ( int i = count ; i <= index ; i ++ ) { elements . add ( null ) ; } } // // Then set in the element. elements . set ( index , element ) ; return element ; }
Sets an element in at the specified index .
187
10
143,198
public void add ( T value ) { Element < T > element = new Element < T > ( bundle , value ) ; element . previous = tail ; if ( tail != null ) tail . next = element ; tail = element ; if ( head == null ) head = element ; }
adds a value to the list
58
7
143,199
public T [ ] toArray ( T [ ] tArray ) { List < T > array = new ArrayList < T > ( 100 ) ; for ( Iterator < T > it = iterator ( ) ; it . hasNext ( ) ; ) { T val = it . next ( ) ; if ( val != null ) array . add ( val ) ; } return array . toArray ( tArray ) ; }
Returns an array of non null elements from the source array .
86
12