idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
26,400
protected static CallableStatement memorize ( final CallableStatement target , final ConnectionHandle connectionHandle ) { return ( CallableStatement ) Proxy . newProxyInstance ( CallableStatementProxy . class . getClassLoader ( ) , new Class [ ] { CallableStatementProxy . class } , new MemorizeTransactionProxy ( target , connectionHandle ) ) ; }
Wrap CallableStatement with a proxy .
26,401
private Object runWithPossibleProxySwap ( Method method , Object target , Object [ ] args ) throws IllegalAccessException , InvocationTargetException { Object result ; if ( method . getName ( ) . equals ( "createStatement" ) ) { result = memorize ( ( Statement ) method . invoke ( target , args ) , this . connectionHandle . get ( ) ) ; } else if ( method . getName ( ) . equals ( "prepareStatement" ) ) { result = memorize ( ( PreparedStatement ) method . invoke ( target , args ) , this . connectionHandle . get ( ) ) ; } else if ( method . getName ( ) . equals ( "prepareCall" ) ) { result = memorize ( ( CallableStatement ) method . invoke ( target , args ) , this . connectionHandle . get ( ) ) ; } else result = method . invoke ( target , args ) ; return result ; }
Runs the given method with the specified arguments substituting with proxies where necessary
26,402
private void fillConnections ( int connectionsToCreate ) throws InterruptedException { try { for ( int i = 0 ; i < connectionsToCreate ; i ++ ) { if ( this . pool . poolShuttingDown ) { break ; } this . partition . addFreeConnection ( new ConnectionHandle ( null , this . partition , this . pool , false ) ) ; } } catch ( Exception e ) { logger . error ( "Error in trying to obtain a connection. Retrying in " + this . acquireRetryDelayInMs + "ms" , e ) ; Thread . sleep ( this . acquireRetryDelayInMs ) ; } }
Adds new connections to the partition .
26,403
public String calculateCacheKey ( String sql , int resultSetType , int resultSetConcurrency , int resultSetHoldability ) { StringBuilder tmp = calculateCacheKeyInternal ( sql , resultSetType , resultSetConcurrency ) ; tmp . append ( ", H:" ) ; tmp . append ( resultSetHoldability ) ; return tmp . toString ( ) ; }
Simply appends the given parameters and returns it to obtain a cache key
26,404
private StringBuilder calculateCacheKeyInternal ( String sql , int resultSetType , int resultSetConcurrency ) { StringBuilder tmp = new StringBuilder ( sql . length ( ) + 20 ) ; tmp . append ( sql ) ; tmp . append ( ", T" ) ; tmp . append ( resultSetType ) ; tmp . append ( ", C" ) ; tmp . append ( resultSetConcurrency ) ; return tmp ; }
Cache key calculation .
26,405
public String calculateCacheKey ( String sql , int autoGeneratedKeys ) { StringBuilder tmp = new StringBuilder ( sql . length ( ) + 4 ) ; tmp . append ( sql ) ; tmp . append ( autoGeneratedKeys ) ; return tmp . toString ( ) ; }
Alternate version of autoGeneratedKeys .
26,406
public String calculateCacheKey ( String sql , int [ ] columnIndexes ) { StringBuilder tmp = new StringBuilder ( sql . length ( ) + 4 ) ; tmp . append ( sql ) ; for ( int i = 0 ; i < columnIndexes . length ; i ++ ) { tmp . append ( columnIndexes [ i ] ) ; tmp . append ( "CI," ) ; } return tmp . toString ( ) ; }
Calculate a cache key .
26,407
public void run ( ) { ConnectionHandle connection = null ; long tmp ; long nextCheckInMs = this . maxAgeInMs ; int partitionSize = this . partition . getAvailableConnections ( ) ; long currentTime = System . currentTimeMillis ( ) ; for ( int i = 0 ; i < partitionSize ; i ++ ) { try { connection = this . partition . getFreeConnections ( ) . poll ( ) ; if ( connection != null ) { connection . setOriginatingPartition ( this . partition ) ; tmp = this . maxAgeInMs - ( currentTime - connection . getConnectionCreationTimeInMs ( ) ) ; if ( tmp < nextCheckInMs ) { nextCheckInMs = tmp ; } if ( connection . isExpired ( currentTime ) ) { closeConnection ( connection ) ; continue ; } if ( this . lifoMode ) { if ( ! ( connection . getOriginatingPartition ( ) . getFreeConnections ( ) . offer ( connection ) ) ) { connection . internalClose ( ) ; } } else { this . pool . putConnectionBackInPartition ( connection ) ; } Thread . sleep ( 20L ) ; } } catch ( Throwable e ) { logger . error ( "Connection max age thread exception." , e ) ; } } }
Invoked periodically .
26,408
protected void closeConnection ( ConnectionHandle connection ) { if ( connection != null ) { try { connection . internalClose ( ) ; } catch ( Throwable t ) { logger . error ( "Destroy connection exception" , t ) ; } finally { this . pool . postDestroyConnection ( connection ) ; } } }
Closes off this connection
26,409
public void setIdleMaxAge ( long idleMaxAge , TimeUnit timeUnit ) { this . idleMaxAgeInSeconds = TimeUnit . SECONDS . convert ( idleMaxAge , checkNotNull ( timeUnit ) ) ; }
Sets Idle max age .
26,410
public void setAcquireRetryDelay ( long acquireRetryDelay , TimeUnit timeUnit ) { this . acquireRetryDelayInMs = TimeUnit . MILLISECONDS . convert ( acquireRetryDelay , timeUnit ) ; }
Sets the number of ms to wait before attempting to obtain a connection again after a failure .
26,411
public void setQueryExecuteTimeLimit ( long queryExecuteTimeLimit , TimeUnit timeUnit ) { this . queryExecuteTimeLimitInMs = TimeUnit . MILLISECONDS . convert ( queryExecuteTimeLimit , timeUnit ) ; }
Queries taking longer than this limit to execute are logged .
26,412
public void setConnectionTimeout ( long connectionTimeout , TimeUnit timeUnit ) { this . connectionTimeoutInMs = TimeUnit . MILLISECONDS . convert ( connectionTimeout , timeUnit ) ; }
Sets the maximum time to wait before a call to getConnection is timed out .
26,413
public void setCloseConnectionWatchTimeout ( long closeConnectionWatchTimeout , TimeUnit timeUnit ) { this . closeConnectionWatchTimeoutInMs = TimeUnit . MILLISECONDS . convert ( closeConnectionWatchTimeout , timeUnit ) ; }
Sets the time to wait when close connection watch threads are enabled . 0 = wait forever .
26,414
public void setMaxConnectionAge ( long maxConnectionAge , TimeUnit timeUnit ) { this . maxConnectionAgeInSeconds = TimeUnit . SECONDS . convert ( maxConnectionAge , timeUnit ) ; }
Sets the maxConnectionAge . Any connections older than this setting will be closed off whether it is idle or not . Connections currently in use will not be affected until they are returned to the pool .
26,415
private Properties parseXML ( Document doc , String sectionName ) { int found = - 1 ; Properties results = new Properties ( ) ; NodeList config = null ; if ( sectionName == null ) { config = doc . getElementsByTagName ( "default-config" ) ; found = 0 ; } else { config = doc . getElementsByTagName ( "named-config" ) ; if ( config != null && config . getLength ( ) > 0 ) { for ( int i = 0 ; i < config . getLength ( ) ; i ++ ) { Node node = config . item ( i ) ; if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { NamedNodeMap attributes = node . getAttributes ( ) ; if ( attributes != null && attributes . getLength ( ) > 0 ) { Node name = attributes . getNamedItem ( "name" ) ; if ( name . getNodeValue ( ) . equalsIgnoreCase ( sectionName ) ) { found = i ; break ; } } } } } if ( found == - 1 ) { config = null ; logger . warn ( "Did not find " + sectionName + " section in config file. Reverting to defaults." ) ; } } if ( config != null && config . getLength ( ) > 0 ) { Node node = config . item ( found ) ; if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { Element elementEntry = ( Element ) node ; NodeList childNodeList = elementEntry . getChildNodes ( ) ; for ( int j = 0 ; j < childNodeList . getLength ( ) ; j ++ ) { Node node_j = childNodeList . item ( j ) ; if ( node_j . getNodeType ( ) == Node . ELEMENT_NODE ) { Element piece = ( Element ) node_j ; NamedNodeMap attributes = piece . getAttributes ( ) ; if ( attributes != null && attributes . getLength ( ) > 0 ) { results . put ( attributes . item ( 0 ) . getNodeValue ( ) , piece . getTextContent ( ) ) ; } } } } } return results ; }
Parses the given XML doc to extract the properties and return them into a java . util . Properties .
26,416
protected Class < ? > loadClass ( String clazz ) throws ClassNotFoundException { if ( this . classLoader == null ) { return Class . forName ( clazz ) ; } return Class . forName ( clazz , true , this . classLoader ) ; }
Loads the given class respecting the given classloader .
26,417
public boolean hasSameConfiguration ( BoneCPConfig that ) { if ( that != null && Objects . equal ( this . acquireIncrement , that . getAcquireIncrement ( ) ) && Objects . equal ( this . acquireRetryDelayInMs , that . getAcquireRetryDelayInMs ( ) ) && Objects . equal ( this . closeConnectionWatch , that . isCloseConnectionWatch ( ) ) && Objects . equal ( this . logStatementsEnabled , that . isLogStatementsEnabled ( ) ) && Objects . equal ( this . connectionHook , that . getConnectionHook ( ) ) && Objects . equal ( this . connectionTestStatement , that . getConnectionTestStatement ( ) ) && Objects . equal ( this . idleConnectionTestPeriodInSeconds , that . getIdleConnectionTestPeriod ( TimeUnit . SECONDS ) ) && Objects . equal ( this . idleMaxAgeInSeconds , that . getIdleMaxAge ( TimeUnit . SECONDS ) ) && Objects . equal ( this . initSQL , that . getInitSQL ( ) ) && Objects . equal ( this . jdbcUrl , that . getJdbcUrl ( ) ) && Objects . equal ( this . maxConnectionsPerPartition , that . getMaxConnectionsPerPartition ( ) ) && Objects . equal ( this . minConnectionsPerPartition , that . getMinConnectionsPerPartition ( ) ) && Objects . equal ( this . partitionCount , that . getPartitionCount ( ) ) && Objects . equal ( this . releaseHelperThreads , that . getReleaseHelperThreads ( ) ) && Objects . equal ( this . statementsCacheSize , that . getStatementsCacheSize ( ) ) && Objects . equal ( this . username , that . getUsername ( ) ) && Objects . equal ( this . password , that . getPassword ( ) ) && Objects . equal ( this . lazyInit , that . isLazyInit ( ) ) && Objects . equal ( this . transactionRecoveryEnabled , that . isTransactionRecoveryEnabled ( ) ) && Objects . equal ( this . acquireRetryAttempts , that . getAcquireRetryAttempts ( ) ) && Objects . equal ( this . statementReleaseHelperThreads , that . getStatementReleaseHelperThreads ( ) ) && Objects . equal ( this . closeConnectionWatchTimeoutInMs , that . getCloseConnectionWatchTimeout ( ) ) && Objects . equal ( this . connectionTimeoutInMs , that . getConnectionTimeoutInMs ( ) ) && Objects . equal ( this . datasourceBean , that . getDatasourceBean ( ) ) && Objects . equal ( this . getQueryExecuteTimeLimitInMs ( ) , that . getQueryExecuteTimeLimitInMs ( ) ) && Objects . equal ( this . poolAvailabilityThreshold , that . getPoolAvailabilityThreshold ( ) ) && Objects . equal ( this . poolName , that . getPoolName ( ) ) && Objects . equal ( this . disableConnectionTracking , that . isDisableConnectionTracking ( ) ) ) { return true ; } return false ; }
Returns true if this instance has the same config as a given config .
26,418
protected long preConnection ( ) throws SQLException { long statsObtainTime = 0 ; if ( this . pool . poolShuttingDown ) { throw new SQLException ( this . pool . shutdownStackTrace ) ; } if ( this . pool . statisticsEnabled ) { statsObtainTime = System . nanoTime ( ) ; this . pool . statistics . incrementConnectionsRequested ( ) ; } return statsObtainTime ; }
Prep for a new connection
26,419
protected void postConnection ( ConnectionHandle handle , long statsObtainTime ) { handle . renewConnection ( ) ; if ( handle . getConnectionHook ( ) != null ) { handle . getConnectionHook ( ) . onCheckOut ( handle ) ; } if ( this . pool . closeConnectionWatch ) { this . pool . watchConnection ( handle ) ; } if ( this . pool . statisticsEnabled ) { this . pool . statistics . addCumulativeConnectionWaitTime ( System . nanoTime ( ) - statsObtainTime ) ; } }
After obtaining a connection perform additional tasks .
26,420
public BoneCP getPool ( ) { FinalWrapper < BoneCP > wrapper = this . pool ; return wrapper == null ? null : wrapper . value ; }
Returns a handle to the pool . Useful to obtain a handle to the statistics for example .
26,421
public void configure ( Properties props ) throws HibernateException { try { this . config = new BoneCPConfig ( props ) ; String url = props . getProperty ( CONFIG_CONNECTION_URL ) ; String username = props . getProperty ( CONFIG_CONNECTION_USERNAME ) ; String password = props . getProperty ( CONFIG_CONNECTION_PASSWORD ) ; String driver = props . getProperty ( CONFIG_CONNECTION_DRIVER_CLASS ) ; if ( url == null ) { url = props . getProperty ( CONFIG_CONNECTION_URL_ALTERNATE ) ; } if ( username == null ) { username = props . getProperty ( CONFIG_CONNECTION_USERNAME_ALTERNATE ) ; } if ( password == null ) { password = props . getProperty ( CONFIG_CONNECTION_PASSWORD_ALTERNATE ) ; } if ( driver == null ) { driver = props . getProperty ( CONFIG_CONNECTION_DRIVER_CLASS_ALTERNATE ) ; } if ( url != null ) { this . config . setJdbcUrl ( url ) ; } if ( username != null ) { this . config . setUsername ( username ) ; } if ( password != null ) { this . config . setPassword ( password ) ; } this . isolation = ConfigurationHelper . getInteger ( AvailableSettings . ISOLATION , props ) ; this . autocommit = ConfigurationHelper . getBoolean ( AvailableSettings . AUTOCOMMIT , props ) ; logger . debug ( this . config . toString ( ) ) ; if ( driver != null && ! driver . trim ( ) . equals ( "" ) ) { loadClass ( driver ) ; } if ( this . config . getConnectionHookClassName ( ) != null ) { Object hookClass = loadClass ( this . config . getConnectionHookClassName ( ) ) . newInstance ( ) ; this . config . setConnectionHook ( ( ConnectionHook ) hookClass ) ; } this . pool = createPool ( this . config ) ; } catch ( Exception e ) { throw new HibernateException ( e ) ; } }
Pool configuration .
26,422
protected BoneCP createPool ( BoneCPConfig config ) { try { return new BoneCP ( config ) ; } catch ( SQLException e ) { throw new HibernateException ( e ) ; } }
Creates the given connection pool with the given configuration . Extracted here to make unit mocking easier .
26,423
private Properties mapToProperties ( Map < String , String > map ) { Properties p = new Properties ( ) ; for ( Map . Entry < String , String > entry : map . entrySet ( ) ) { p . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } return p ; }
Legacy conversion .
26,424
protected synchronized void stealExistingAllocations ( ) { for ( ConnectionHandle handle : this . threadFinalizableRefs . keySet ( ) ) { if ( handle . logicallyClosed . compareAndSet ( true , false ) ) { try { this . pool . releaseConnection ( handle ) ; } catch ( SQLException e ) { logger . error ( "Error releasing connection" , e ) ; } } } if ( this . warnApp . compareAndSet ( false , true ) ) { logger . warn ( "Cached strategy chosen, but more threads are requesting a connection than are configured. Switching permanently to default strategy." ) ; } this . threadFinalizableRefs . clear ( ) ; }
Tries to close off all the unused assigned connections back to the pool . Assumes that the strategy mode has already been flipped prior to calling this routine . Called whenever our no of connection requests > no of threads .
26,425
protected void threadWatch ( final ConnectionHandle c ) { this . threadFinalizableRefs . put ( c , new FinalizableWeakReference < Thread > ( Thread . currentThread ( ) , this . finalizableRefQueue ) { public void finalizeReferent ( ) { try { if ( ! CachedConnectionStrategy . this . pool . poolShuttingDown ) { logger . debug ( "Monitored thread is dead, closing off allocated connection." ) ; } c . internalClose ( ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; } CachedConnectionStrategy . this . threadFinalizableRefs . remove ( c ) ; } } ) ; }
Keep track of this handle tied to which thread so that if the thread is terminated we can reclaim our connection handle . We also
26,426
public synchronized void shutdown ( ) { if ( ! this . poolShuttingDown ) { logger . info ( "Shutting down connection pool..." ) ; this . poolShuttingDown = true ; this . shutdownStackTrace = captureStackTrace ( SHUTDOWN_LOCATION_TRACE ) ; this . keepAliveScheduler . shutdownNow ( ) ; this . maxAliveScheduler . shutdownNow ( ) ; this . connectionsScheduler . shutdownNow ( ) ; this . asyncExecutor . shutdownNow ( ) ; try { this . connectionsScheduler . awaitTermination ( 5 , TimeUnit . SECONDS ) ; this . maxAliveScheduler . awaitTermination ( 5 , TimeUnit . SECONDS ) ; this . keepAliveScheduler . awaitTermination ( 5 , TimeUnit . SECONDS ) ; this . asyncExecutor . awaitTermination ( 5 , TimeUnit . SECONDS ) ; if ( this . closeConnectionExecutor != null ) { this . closeConnectionExecutor . shutdownNow ( ) ; this . closeConnectionExecutor . awaitTermination ( 5 , TimeUnit . SECONDS ) ; } } catch ( InterruptedException e ) { } this . connectionStrategy . terminateAllConnections ( ) ; unregisterDriver ( ) ; registerUnregisterJMX ( false ) ; if ( finalizableRefQueue != null ) { finalizableRefQueue . close ( ) ; } logger . info ( "Connection pool has been shutdown." ) ; } }
Closes off this connection pool .
26,427
protected void unregisterDriver ( ) { String jdbcURL = this . config . getJdbcUrl ( ) ; if ( ( jdbcURL != null ) && this . config . isDeregisterDriverOnClose ( ) ) { logger . info ( "Unregistering JDBC driver for : " + jdbcURL ) ; try { DriverManager . deregisterDriver ( DriverManager . getDriver ( jdbcURL ) ) ; } catch ( SQLException e ) { logger . info ( "Unregistering driver failed." , e ) ; } } }
Drops a driver from the DriverManager s list .
26,428
protected void destroyConnection ( ConnectionHandle conn ) { postDestroyConnection ( conn ) ; conn . setInReplayMode ( true ) ; try { conn . internalClose ( ) ; } catch ( SQLException e ) { logger . error ( "Error in attempting to close connection" , e ) ; } }
Physically close off the internal connection .
26,429
protected void postDestroyConnection ( ConnectionHandle handle ) { ConnectionPartition partition = handle . getOriginatingPartition ( ) ; if ( this . finalizableRefQueue != null && handle . getInternalConnection ( ) != null ) { this . finalizableRefs . remove ( handle . getInternalConnection ( ) ) ; } partition . updateCreatedConnections ( - 1 ) ; partition . setUnableToCreateMoreTransactions ( false ) ; if ( handle . getConnectionHook ( ) != null ) { handle . getConnectionHook ( ) . onDestroy ( handle ) ; } }
Update counters and call hooks .
26,430
protected Connection obtainInternalConnection ( ConnectionHandle connectionHandle ) throws SQLException { boolean tryAgain = false ; Connection result = null ; Connection oldRawConnection = connectionHandle . getInternalConnection ( ) ; String url = this . getConfig ( ) . getJdbcUrl ( ) ; int acquireRetryAttempts = this . getConfig ( ) . getAcquireRetryAttempts ( ) ; long acquireRetryDelayInMs = this . getConfig ( ) . getAcquireRetryDelayInMs ( ) ; AcquireFailConfig acquireConfig = new AcquireFailConfig ( ) ; acquireConfig . setAcquireRetryAttempts ( new AtomicInteger ( acquireRetryAttempts ) ) ; acquireConfig . setAcquireRetryDelayInMs ( acquireRetryDelayInMs ) ; acquireConfig . setLogMessage ( "Failed to acquire connection to " + url ) ; ConnectionHook connectionHook = this . getConfig ( ) . getConnectionHook ( ) ; do { result = null ; try { result = this . obtainRawInternalConnection ( ) ; tryAgain = false ; if ( acquireRetryAttempts != this . getConfig ( ) . getAcquireRetryAttempts ( ) ) { logger . info ( "Successfully re-established connection to " + url ) ; } this . getDbIsDown ( ) . set ( false ) ; connectionHandle . setInternalConnection ( result ) ; if ( connectionHook != null ) { connectionHook . onAcquire ( connectionHandle ) ; } ConnectionHandle . sendInitSQL ( result , this . getConfig ( ) . getInitSQL ( ) ) ; } catch ( SQLException e ) { if ( connectionHook != null ) { tryAgain = connectionHook . onAcquireFail ( e , acquireConfig ) ; } else { logger . error ( String . format ( "Failed to acquire connection to %s. Sleeping for %d ms. Attempts left: %d" , url , acquireRetryDelayInMs , acquireRetryAttempts ) , e ) ; try { if ( acquireRetryAttempts > 0 ) { Thread . sleep ( acquireRetryDelayInMs ) ; } tryAgain = ( acquireRetryAttempts -- ) > 0 ; } catch ( InterruptedException e1 ) { tryAgain = false ; } } if ( ! tryAgain ) { if ( oldRawConnection != null ) { oldRawConnection . close ( ) ; } if ( result != null ) { result . close ( ) ; } connectionHandle . setInternalConnection ( oldRawConnection ) ; throw e ; } } } while ( tryAgain ) ; return result ; }
Obtains a database connection retrying if necessary .
26,431
protected void registerUnregisterJMX ( boolean doRegister ) { if ( this . mbs == null ) { this . mbs = ManagementFactory . getPlatformMBeanServer ( ) ; } try { String suffix = "" ; if ( this . config . getPoolName ( ) != null ) { suffix = "-" + this . config . getPoolName ( ) ; } ObjectName name = new ObjectName ( MBEAN_BONECP + suffix ) ; ObjectName configname = new ObjectName ( MBEAN_CONFIG + suffix ) ; if ( doRegister ) { if ( ! this . mbs . isRegistered ( name ) ) { this . mbs . registerMBean ( this . statistics , name ) ; } if ( ! this . mbs . isRegistered ( configname ) ) { this . mbs . registerMBean ( this . config , configname ) ; } } else { if ( this . mbs . isRegistered ( name ) ) { this . mbs . unregisterMBean ( name ) ; } if ( this . mbs . isRegistered ( configname ) ) { this . mbs . unregisterMBean ( configname ) ; } } } catch ( Exception e ) { logger . error ( "Unable to start/stop JMX" , e ) ; } }
Initialises JMX stuff .
26,432
protected void watchConnection ( ConnectionHandle connectionHandle ) { String message = captureStackTrace ( UNCLOSED_EXCEPTION_MESSAGE ) ; this . closeConnectionExecutor . submit ( new CloseThreadMonitor ( Thread . currentThread ( ) , connectionHandle , message , this . closeConnectionWatchTimeoutInMs ) ) ; }
Starts off a new thread to monitor this connection attempt .
26,433
public ListenableFuture < Connection > getAsyncConnection ( ) { return this . asyncExecutor . submit ( new Callable < Connection > ( ) { public Connection call ( ) throws Exception { return getConnection ( ) ; } } ) ; }
Obtain a connection asynchronously by queueing a request to obtain a connection in a separate thread .
26,434
protected void maybeSignalForMoreConnections ( ConnectionPartition connectionPartition ) { if ( ! connectionPartition . isUnableToCreateMoreTransactions ( ) && ! this . poolShuttingDown && connectionPartition . getAvailableConnections ( ) * 100 / connectionPartition . getMaxConnections ( ) <= this . poolAvailabilityThreshold ) { connectionPartition . getPoolWatchThreadSignalQueue ( ) . offer ( new Object ( ) ) ; } }
Tests if this partition has hit a threshold and signal to the pool watch thread to create new connections
26,435
protected void internalReleaseConnection ( ConnectionHandle connectionHandle ) throws SQLException { if ( ! this . cachedPoolStrategy ) { connectionHandle . clearStatementCaches ( false ) ; } if ( connectionHandle . getReplayLog ( ) != null ) { connectionHandle . getReplayLog ( ) . clear ( ) ; connectionHandle . recoveryResult . getReplaceTarget ( ) . clear ( ) ; } if ( connectionHandle . isExpired ( ) || ( ! this . poolShuttingDown && connectionHandle . isPossiblyBroken ( ) && ! isConnectionHandleAlive ( connectionHandle ) ) ) { if ( connectionHandle . isExpired ( ) ) { connectionHandle . internalClose ( ) ; } ConnectionPartition connectionPartition = connectionHandle . getOriginatingPartition ( ) ; postDestroyConnection ( connectionHandle ) ; maybeSignalForMoreConnections ( connectionPartition ) ; connectionHandle . clearStatementCaches ( true ) ; return ; } connectionHandle . setConnectionLastUsedInMs ( System . currentTimeMillis ( ) ) ; if ( ! this . poolShuttingDown ) { putConnectionBackInPartition ( connectionHandle ) ; } else { connectionHandle . internalClose ( ) ; } }
Release a connection by placing the connection back in the pool .
26,436
protected void putConnectionBackInPartition ( ConnectionHandle connectionHandle ) throws SQLException { if ( this . cachedPoolStrategy && ( ( CachedConnectionStrategy ) this . connectionStrategy ) . tlConnections . dumbGet ( ) . getValue ( ) ) { connectionHandle . logicallyClosed . set ( true ) ; ( ( CachedConnectionStrategy ) this . connectionStrategy ) . tlConnections . set ( new AbstractMap . SimpleEntry < ConnectionHandle , Boolean > ( connectionHandle , false ) ) ; } else { BlockingQueue < ConnectionHandle > queue = connectionHandle . getOriginatingPartition ( ) . getFreeConnections ( ) ; if ( ! queue . offer ( connectionHandle ) ) { connectionHandle . internalClose ( ) ; } } }
Places a connection back in the originating partition .
26,437
public boolean isConnectionHandleAlive ( ConnectionHandle connection ) { Statement stmt = null ; boolean result = false ; boolean logicallyClosed = connection . logicallyClosed . get ( ) ; try { connection . logicallyClosed . compareAndSet ( true , false ) ; String testStatement = this . config . getConnectionTestStatement ( ) ; ResultSet rs = null ; if ( testStatement == null ) { rs = connection . getMetaData ( ) . getTables ( null , null , KEEPALIVEMETADATA , METADATATABLE ) ; } else { stmt = connection . createStatement ( ) ; stmt . execute ( testStatement ) ; } if ( rs != null ) { rs . close ( ) ; } result = true ; } catch ( SQLException e ) { result = false ; } finally { connection . logicallyClosed . set ( logicallyClosed ) ; connection . setConnectionLastResetInMs ( System . currentTimeMillis ( ) ) ; result = closeStatement ( stmt , result ) ; } return result ; }
Sends a dummy statement to the server to keep the connection alive
26,438
public int getTotalLeased ( ) { int total = 0 ; for ( int i = 0 ; i < this . partitionCount && this . partitions [ i ] != null ; i ++ ) { total += this . partitions [ i ] . getCreatedConnections ( ) - this . partitions [ i ] . getAvailableConnections ( ) ; } return total ; }
Return total number of connections currently in use by an application
26,439
public int getTotalCreatedConnections ( ) { int total = 0 ; for ( int i = 0 ; i < this . partitionCount && this . partitions [ i ] != null ; i ++ ) { total += this . partitions [ i ] . getCreatedConnections ( ) ; } return total ; }
Return total number of connections created in all partitions .
26,440
protected void addFreeConnection ( ConnectionHandle connectionHandle ) throws SQLException { connectionHandle . setOriginatingPartition ( this ) ; updateCreatedConnections ( 1 ) ; if ( ! this . disableTracking ) { trackConnectionFinalizer ( connectionHandle ) ; } if ( ! this . freeConnections . offer ( connectionHandle ) ) { updateCreatedConnections ( - 1 ) ; if ( ! this . disableTracking ) { this . pool . getFinalizableRefs ( ) . remove ( connectionHandle . getInternalConnection ( ) ) ; } connectionHandle . internalClose ( ) ; } }
Adds a free connection .
26,441
public void terminateAllConnections ( ) { this . terminationLock . lock ( ) ; try { for ( int i = 0 ; i < this . pool . partitionCount ; i ++ ) { this . pool . partitions [ i ] . setUnableToCreateMoreTransactions ( false ) ; List < ConnectionHandle > clist = new LinkedList < ConnectionHandle > ( ) ; this . pool . partitions [ i ] . getFreeConnections ( ) . drainTo ( clist ) ; for ( ConnectionHandle c : clist ) { this . pool . destroyConnection ( c ) ; } } } finally { this . terminationLock . unlock ( ) ; } }
Closes off all connections in all partitions .
26,442
protected void queryTimerEnd ( String sql , long queryStartTime ) { if ( ( this . queryExecuteTimeLimit != 0 ) && ( this . connectionHook != null ) ) { long timeElapsed = ( System . nanoTime ( ) - queryStartTime ) ; if ( timeElapsed > this . queryExecuteTimeLimit ) { this . connectionHook . onQueryExecuteTimeLimitExceeded ( this . connectionHandle , this , sql , this . logParams , timeElapsed ) ; } } if ( this . statisticsEnabled ) { this . statistics . incrementStatementsExecuted ( ) ; this . statistics . addStatementExecuteTime ( System . nanoTime ( ) - queryStartTime ) ; } }
Call the onQueryExecuteTimeLimitExceeded hook if necessary
26,443
public static MBeanServerConnection getMBeanServerConnection ( Process p , boolean startAgent ) { try { final JMXServiceURL serviceURL = getLocalConnectorAddress ( p , startAgent ) ; final JMXConnector connector = JMXConnectorFactory . connect ( serviceURL ) ; final MBeanServerConnection mbsc = connector . getMBeanServerConnection ( ) ; return mbsc ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Connects to a child JVM process
26,444
public static JMXServiceURL getLocalConnectorAddress ( Process p , boolean startAgent ) { return getLocalConnectorAddress ( Integer . toString ( getPid ( p ) ) , startAgent ) ; }
Returns the JMX connector address of a child process .
26,445
public final Jar setAttribute ( String name , String value ) { verifyNotSealed ( ) ; if ( jos != null ) throw new IllegalStateException ( "Manifest cannot be modified after entries are added." ) ; getManifest ( ) . getMainAttributes ( ) . putValue ( name , value ) ; return this ; }
Sets an attribute in the main section of the manifest .
26,446
public final Jar setAttribute ( String section , String name , String value ) { verifyNotSealed ( ) ; if ( jos != null ) throw new IllegalStateException ( "Manifest cannot be modified after entries are added." ) ; Attributes attr = getManifest ( ) . getAttributes ( section ) ; if ( attr == null ) { attr = new Attributes ( ) ; getManifest ( ) . getEntries ( ) . put ( section , attr ) ; } attr . putValue ( name , value ) ; return this ; }
Sets an attribute in a non - main section of the manifest .
26,447
public Jar setListAttribute ( String name , Collection < ? > values ) { return setAttribute ( name , join ( values ) ) ; }
Sets an attribute in the main section of the manifest to a list . The list elements will be joined with a single whitespace character .
26,448
public Jar setMapAttribute ( String name , Map < String , ? > values ) { return setAttribute ( name , join ( values ) ) ; }
Sets an attribute in the main section of the manifest to a map . The map entries will be joined with a single whitespace character and each key - value pair will be joined with a = .
26,449
public String getAttribute ( String section , String name ) { Attributes attr = getManifest ( ) . getAttributes ( section ) ; return attr != null ? attr . getValue ( name ) : null ; }
Returns an attribute s value from a non - main section of this JAR s manifest .
26,450
public List < String > getListAttribute ( String section , String name ) { return split ( getAttribute ( section , name ) ) ; }
Returns an attribute s list value from a non - main section of this JAR s manifest . The attributes string value will be split on whitespace into the returned list . The returned list may be safely modified .
26,451
public Map < String , String > getMapAttribute ( String name , String defaultValue ) { return mapSplit ( getAttribute ( name ) , defaultValue ) ; }
Returns an attribute s map value from this JAR s manifest s main section . The attributes string value will be split on whitespace into map entries and each entry will be split on = to get the key - value pair . The returned map may be safely modified .
26,452
public Jar addClass ( Class < ? > clazz ) throws IOException { final String resource = clazz . getName ( ) . replace ( '.' , '/' ) + ".class" ; return addEntry ( resource , clazz . getClassLoader ( ) . getResourceAsStream ( resource ) ) ; }
Adds a class entry to this JAR .
26,453
public Jar addPackageOf ( Class < ? > clazz , Filter filter ) throws IOException { try { final String path = clazz . getPackage ( ) . getName ( ) . replace ( '.' , '/' ) ; URL dirURL = clazz . getClassLoader ( ) . getResource ( path ) ; if ( dirURL != null && dirURL . getProtocol ( ) . equals ( "file" ) ) addDir ( Paths . get ( path ) , Paths . get ( dirURL . toURI ( ) ) , filter , false ) ; else { if ( dirURL == null ) dirURL = clazz . getClassLoader ( ) . getResource ( clazz . getName ( ) . replace ( '.' , '/' ) + ".class" ) ; if ( dirURL . getProtocol ( ) . equals ( "jar" ) ) { final URI jarUri = new URI ( dirURL . getPath ( ) . substring ( 0 , dirURL . getPath ( ) . indexOf ( '!' ) ) ) ; try ( JarInputStream jis1 = newJarInputStream ( Files . newInputStream ( Paths . get ( jarUri ) ) ) ) { for ( JarEntry entry ; ( entry = jis1 . getNextJarEntry ( ) ) != null ; ) { try { if ( entry . getName ( ) . startsWith ( path + '/' ) ) { if ( filter == null || filter . filter ( entry . getName ( ) ) ) addEntryNoClose ( jos , entry . getName ( ) , jis1 ) ; } } catch ( ZipException e ) { if ( ! e . getMessage ( ) . startsWith ( "duplicate entry" ) ) throw e ; } } } } else throw new AssertionError ( ) ; } return this ; } catch ( URISyntaxException e ) { throw new AssertionError ( e ) ; } }
Adds the contents of a Java package to this JAR .
26,454
public Jar setJarPrefix ( String value ) { verifyNotSealed ( ) ; if ( jos != null ) throw new IllegalStateException ( "Really executable cannot be set after entries are added." ) ; if ( value != null && jarPrefixFile != null ) throw new IllegalStateException ( "A prefix has already been set (" + jarPrefixFile + ")" ) ; this . jarPrefixStr = value ; return this ; }
Sets a string that will be prepended to the JAR file s data .
26,455
public Jar setJarPrefix ( Path file ) { verifyNotSealed ( ) ; if ( jos != null ) throw new IllegalStateException ( "Really executable cannot be set after entries are added." ) ; if ( file != null && jarPrefixStr != null ) throw new IllegalStateException ( "A prefix has already been set (" + jarPrefixStr + ")" ) ; this . jarPrefixFile = file ; return this ; }
Sets a file whose contents will be prepended to the JAR file s data .
26,456
public < T extends OutputStream > T write ( T os ) throws IOException { close ( ) ; if ( ! ( this . os instanceof ByteArrayOutputStream ) ) throw new IllegalStateException ( "Cannot write to another target if setOutputStream has been called" ) ; final byte [ ] content = ( ( ByteArrayOutputStream ) this . os ) . toByteArray ( ) ; if ( packer != null ) packer . pack ( new JarInputStream ( new ByteArrayInputStream ( content ) ) , os ) ; else os . write ( content ) ; os . close ( ) ; return os ; }
Writes this JAR to an output stream and closes the stream .
26,457
public Capsule newCapsule ( String mode , Path wrappedJar ) { final String oldMode = properties . getProperty ( PROP_MODE ) ; final ClassLoader oldCl = Thread . currentThread ( ) . getContextClassLoader ( ) ; Thread . currentThread ( ) . setContextClassLoader ( capsuleClass . getClassLoader ( ) ) ; try { setProperty ( PROP_MODE , mode ) ; final Constructor < ? > ctor = accessible ( capsuleClass . getDeclaredConstructor ( Path . class ) ) ; final Object capsule = ctor . newInstance ( jarFile ) ; if ( wrappedJar != null ) { final Method setTarget = accessible ( capsuleClass . getDeclaredMethod ( "setTarget" , Path . class ) ) ; setTarget . invoke ( capsule , wrappedJar ) ; } return wrap ( capsule ) ; } catch ( ReflectiveOperationException e ) { throw new RuntimeException ( "Could not create capsule instance." , e ) ; } finally { setProperty ( PROP_MODE , oldMode ) ; Thread . currentThread ( ) . setContextClassLoader ( oldCl ) ; } }
Creates a new capsule
26,458
@ SuppressWarnings ( "unchecked" ) public static Map < String , List < Path > > findJavaHomes ( ) { try { return ( Map < String , List < Path > > ) accessible ( Class . forName ( CAPSULE_CLASS_NAME ) . getDeclaredMethod ( "getJavaHomes" ) ) . invoke ( null ) ; } catch ( ReflectiveOperationException e ) { throw new AssertionError ( e ) ; } }
Returns all known Java installations
26,459
public static List < String > enableJMX ( List < String > jvmArgs ) { final String arg = "-D" + OPT_JMX_REMOTE ; if ( jvmArgs . contains ( arg ) ) return jvmArgs ; final List < String > cmdLine2 = new ArrayList < > ( jvmArgs ) ; cmdLine2 . add ( arg ) ; return cmdLine2 ; }
Adds an option to the JVM arguments to enable JMX connection
26,460
public final void setVolumeByIncrement ( float level ) throws IOException { Volume volume = this . getStatus ( ) . volume ; float total = volume . level ; if ( volume . increment <= 0f ) { throw new ChromeCastException ( "Volume.increment is <= 0" ) ; } if ( level > total ) { while ( total < level ) { total = Math . min ( total + volume . increment , level ) ; setVolume ( total ) ; } } else if ( level < total ) { while ( total > level ) { total = Math . max ( total - volume . increment , level ) ; setVolume ( total ) ; } } }
ChromeCast does not allow you to jump levels too quickly to avoid blowing speakers . Setting by increment allows us to easily get the level we want
26,461
private void connect ( ) throws IOException , GeneralSecurityException { synchronized ( closedSync ) { if ( socket == null || socket . isClosed ( ) ) { SSLContext sc = SSLContext . getInstance ( "SSL" ) ; sc . init ( null , new TrustManager [ ] { new X509TrustAllManager ( ) } , new SecureRandom ( ) ) ; socket = sc . getSocketFactory ( ) . createSocket ( ) ; socket . connect ( address ) ; } CastChannel . DeviceAuthMessage authMessage = CastChannel . DeviceAuthMessage . newBuilder ( ) . setChallenge ( CastChannel . AuthChallenge . newBuilder ( ) . build ( ) ) . build ( ) ; CastChannel . CastMessage msg = CastChannel . CastMessage . newBuilder ( ) . setDestinationId ( DEFAULT_RECEIVER_ID ) . setNamespace ( "urn:x-cast:com.google.cast.tp.deviceauth" ) . setPayloadType ( CastChannel . CastMessage . PayloadType . BINARY ) . setProtocolVersion ( CastChannel . CastMessage . ProtocolVersion . CASTV2_1_0 ) . setSourceId ( name ) . setPayloadBinary ( authMessage . toByteString ( ) ) . build ( ) ; write ( msg ) ; CastChannel . CastMessage response = read ( ) ; CastChannel . DeviceAuthMessage authResponse = CastChannel . DeviceAuthMessage . parseFrom ( response . getPayloadBinary ( ) ) ; if ( authResponse . hasError ( ) ) { throw new ChromeCastException ( "Authentication failed: " + authResponse . getError ( ) . getErrorType ( ) . toString ( ) ) ; } PingThread pingThread = new PingThread ( ) ; pingThread . run ( ) ; write ( "urn:x-cast:com.google.cast.tp.connection" , StandardMessage . connect ( ) , DEFAULT_RECEIVER_ID ) ; pingTimer = new Timer ( name + " PING" ) ; pingTimer . schedule ( pingThread , 1000 , PING_PERIOD ) ; reader = new ReadThread ( ) ; reader . start ( ) ; if ( closed ) { closed = false ; notifyListenerOfConnectionEvent ( true ) ; } } }
Establish connection to the ChromeCast device
26,462
public static ExecutorService newSingleThreadDaemonExecutor ( ) { return Executors . newSingleThreadExecutor ( r -> { Thread t = Executors . defaultThreadFactory ( ) . newThread ( r ) ; t . setDaemon ( true ) ; return t ; } ) ; }
Creates an Executor that is based on daemon threads . This allows the program to quit without explicitly calling shutdown on the pool
26,463
public static ScheduledExecutorService newScheduledDaemonThreadPool ( int corePoolSize ) { return Executors . newScheduledThreadPool ( corePoolSize , r -> { Thread t = Executors . defaultThreadFactory ( ) . newThread ( r ) ; t . setDaemon ( true ) ; return t ; } ) ; }
Creates a scheduled thread pool where each thread has the daemon property set to true . This allows the program to quit without explicitly calling shutdown on the pool
26,464
private static MenuDrawer createMenuDrawer ( Activity activity , int dragMode , Position position , Type type ) { MenuDrawer drawer ; if ( type == Type . STATIC ) { drawer = new StaticDrawer ( activity ) ; } else if ( type == Type . OVERLAY ) { drawer = new OverlayDrawer ( activity , dragMode ) ; if ( position == Position . LEFT || position == Position . START ) { drawer . setupUpIndicator ( activity ) ; } } else { drawer = new SlidingDrawer ( activity , dragMode ) ; if ( position == Position . LEFT || position == Position . START ) { drawer . setupUpIndicator ( activity ) ; } } drawer . mDragMode = dragMode ; drawer . setPosition ( position ) ; return drawer ; }
Constructs the appropriate MenuDrawer based on the position .
26,465
private static void attachToContent ( Activity activity , MenuDrawer menuDrawer ) { ViewGroup content = ( ViewGroup ) activity . findViewById ( android . R . id . content ) ; content . removeAllViews ( ) ; content . addView ( menuDrawer , LayoutParams . MATCH_PARENT , LayoutParams . MATCH_PARENT ) ; }
Attaches the menu drawer to the content view .
26,466
private static void attachToDecor ( Activity activity , MenuDrawer menuDrawer ) { ViewGroup decorView = ( ViewGroup ) activity . getWindow ( ) . getDecorView ( ) ; ViewGroup decorChild = ( ViewGroup ) decorView . getChildAt ( 0 ) ; decorView . removeAllViews ( ) ; decorView . addView ( menuDrawer , LayoutParams . MATCH_PARENT , LayoutParams . MATCH_PARENT ) ; menuDrawer . mContentContainer . addView ( decorChild , decorChild . getLayoutParams ( ) ) ; }
Attaches the menu drawer to the window .
26,467
public void setActiveView ( View v , int position ) { final View oldView = mActiveView ; mActiveView = v ; mActivePosition = position ; if ( mAllowIndicatorAnimation && oldView != null ) { startAnimatingIndicator ( ) ; } invalidate ( ) ; }
Set the active view . If the mdActiveIndicator attribute is set this View will have the indicator drawn next to it .
26,468
private int getIndicatorStartPos ( ) { switch ( getPosition ( ) ) { case TOP : return mIndicatorClipRect . left ; case RIGHT : return mIndicatorClipRect . top ; case BOTTOM : return mIndicatorClipRect . left ; default : return mIndicatorClipRect . top ; } }
Returns the start position of the indicator .
26,469
private void animateIndicatorInvalidate ( ) { if ( mIndicatorScroller . computeScrollOffset ( ) ) { mIndicatorOffset = mIndicatorScroller . getCurr ( ) ; invalidate ( ) ; if ( ! mIndicatorScroller . isFinished ( ) ) { postOnAnimation ( mIndicatorRunnable ) ; return ; } } completeAnimatingIndicator ( ) ; }
Callback when each frame in the indicator animation should be drawn .
26,470
public void setDropShadowColor ( int color ) { GradientDrawable . Orientation orientation = getDropShadowOrientation ( ) ; final int endColor = color & 0x00FFFFFF ; mDropShadowDrawable = new GradientDrawable ( orientation , new int [ ] { color , endColor , } ) ; invalidate ( ) ; }
Sets the color of the drop shadow .
26,471
public void setSlideDrawable ( Drawable drawable ) { mSlideDrawable = new SlideDrawable ( drawable ) ; mSlideDrawable . setIsRtl ( ViewHelper . getLayoutDirection ( this ) == LAYOUT_DIRECTION_RTL ) ; if ( mActionBarHelper != null ) { mActionBarHelper . setDisplayShowHomeAsUpEnabled ( true ) ; if ( mDrawerIndicatorEnabled ) { mActionBarHelper . setActionBarUpIndicator ( mSlideDrawable , isMenuVisible ( ) ? mDrawerOpenContentDesc : mDrawerClosedContentDesc ) ; } } }
Sets the drawable used as the drawer indicator .
26,472
public ViewGroup getContentContainer ( ) { if ( mDragMode == MENU_DRAG_CONTENT ) { return mContentContainer ; } else { return ( ViewGroup ) findViewById ( android . R . id . content ) ; } }
Returns the ViewGroup used as a parent for the content view .
26,473
public void setMenuView ( int layoutResId ) { mMenuContainer . removeAllViews ( ) ; mMenuView = LayoutInflater . from ( getContext ( ) ) . inflate ( layoutResId , mMenuContainer , false ) ; mMenuContainer . addView ( mMenuView ) ; }
Set the menu view from a layout resource .
26,474
public void onClick ( View v ) { String tag = ( String ) v . getTag ( ) ; mContentTextView . setText ( String . format ( "%s clicked." , tag ) ) ; mMenuDrawer . setActiveView ( v ) ; }
Click handler for bottom drawer items .
26,475
protected void animateOffsetTo ( int position , int velocity , boolean animate ) { endDrag ( ) ; endPeek ( ) ; final int startX = ( int ) mOffsetPixels ; final int dx = position - startX ; if ( dx == 0 || ! animate ) { setOffsetPixels ( position ) ; setDrawerState ( position == 0 ? STATE_CLOSED : STATE_OPEN ) ; stopLayerTranslation ( ) ; return ; } int duration ; velocity = Math . abs ( velocity ) ; if ( velocity > 0 ) { duration = 4 * Math . round ( 1000.f * Math . abs ( ( float ) dx / velocity ) ) ; } else { duration = ( int ) ( 600.f * Math . abs ( ( float ) dx / mMenuSize ) ) ; } duration = Math . min ( duration , mMaxAnimationDuration ) ; animateOffsetTo ( position , duration ) ; }
Moves the drawer to the position passed .
26,476
public ParsedWord pollParsedWord ( ) { if ( hasNextWord ( ) ) { if ( parsedLine . words ( ) . size ( ) > ( word + 1 ) ) character = parsedLine . words ( ) . get ( word + 1 ) . lineIndex ( ) ; else character = - 1 ; return parsedLine . words ( ) . get ( word ++ ) ; } else return new ParsedWord ( null , - 1 ) ; }
Polls the next ParsedWord from the stack .
26,477
public char pollChar ( ) { if ( hasNextChar ( ) ) { if ( hasNextWord ( ) && character + 1 >= parsedLine . words ( ) . get ( word ) . lineIndex ( ) + parsedLine . words ( ) . get ( word ) . word ( ) . length ( ) ) word ++ ; return parsedLine . line ( ) . charAt ( character ++ ) ; } return '\u0000' ; }
Polls the next char from the stack
26,478
public void updateIteratorPosition ( int length ) { if ( length > 0 ) { if ( ( length + character ) > parsedLine . line ( ) . length ( ) ) length = parsedLine . line ( ) . length ( ) - character ; while ( hasNextWord ( ) && ( length + character ) >= parsedLine . words ( ) . get ( word ) . lineIndex ( ) + parsedLine . words ( ) . get ( word ) . word ( ) . length ( ) ) word ++ ; character = length + character ; } else throw new IllegalArgumentException ( "The length given must be > 0 and not exceed the boundary of the line (including the current position)" ) ; }
Update the current position with specified length . The input will append to the current position of the iterator .
26,479
public String printHelp ( ) { List < CommandLineParser < CI > > parsers = getChildParsers ( ) ; if ( parsers != null && parsers . size ( ) > 0 ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( processedCommand . printHelp ( helpNames ( ) ) ) . append ( Config . getLineSeparator ( ) ) . append ( processedCommand . name ( ) ) . append ( " commands:" ) . append ( Config . getLineSeparator ( ) ) ; int maxLength = 0 ; for ( CommandLineParser child : parsers ) { int length = child . getProcessedCommand ( ) . name ( ) . length ( ) ; if ( length > maxLength ) { maxLength = length ; } } for ( CommandLineParser child : parsers ) { sb . append ( child . getFormattedCommand ( 4 , maxLength + 2 ) ) . append ( Config . getLineSeparator ( ) ) ; } return sb . toString ( ) ; } else return processedCommand . printHelp ( helpNames ( ) ) ; }
Returns a usage String based on the defined command and options . Useful when printing help info etc .
26,480
public void parse ( String line , Mode mode ) { parse ( lineParser . parseLine ( line , line . length ( ) ) . iterator ( ) , mode ) ; }
Parse a command line with the defined command as base of the rules . If any options are found but not defined in the command object an CommandLineParserException will be thrown . Also if a required option is not found or options specified with value but is not given any value an CommandLineParserException will be thrown .
26,481
public void populateObject ( ProcessedCommand < Command < CI > , CI > processedCommand , InvocationProviders invocationProviders , AeshContext aeshContext , CommandLineParser . Mode mode ) throws CommandLineParserException , OptionValidatorException { if ( processedCommand . parserExceptions ( ) . size ( ) > 0 && mode == CommandLineParser . Mode . VALIDATE ) throw processedCommand . parserExceptions ( ) . get ( 0 ) ; for ( ProcessedOption option : processedCommand . getOptions ( ) ) { if ( option . getValues ( ) != null && option . getValues ( ) . size ( ) > 0 ) option . injectValueIntoField ( getObject ( ) , invocationProviders , aeshContext , mode == CommandLineParser . Mode . VALIDATE ) ; else if ( option . getDefaultValues ( ) . size ( ) > 0 ) { option . injectValueIntoField ( getObject ( ) , invocationProviders , aeshContext , mode == CommandLineParser . Mode . VALIDATE ) ; } else if ( option . getOptionType ( ) . equals ( OptionType . GROUP ) && option . getProperties ( ) . size ( ) > 0 ) option . injectValueIntoField ( getObject ( ) , invocationProviders , aeshContext , mode == CommandLineParser . Mode . VALIDATE ) ; else resetField ( getObject ( ) , option . getFieldName ( ) , option . hasValue ( ) ) ; } if ( processedCommand . getArguments ( ) != null && ( processedCommand . getArguments ( ) . getValues ( ) . size ( ) > 0 || processedCommand . getArguments ( ) . getDefaultValues ( ) . size ( ) > 0 ) ) processedCommand . getArguments ( ) . injectValueIntoField ( getObject ( ) , invocationProviders , aeshContext , mode == CommandLineParser . Mode . VALIDATE ) ; else if ( processedCommand . getArguments ( ) != null ) resetField ( getObject ( ) , processedCommand . getArguments ( ) . getFieldName ( ) , true ) ; if ( processedCommand . getArgument ( ) != null && ( processedCommand . getArgument ( ) . getValues ( ) . size ( ) > 0 || processedCommand . getArgument ( ) . getDefaultValues ( ) . size ( ) > 0 ) ) processedCommand . getArgument ( ) . injectValueIntoField ( getObject ( ) , invocationProviders , aeshContext , mode == CommandLineParser . Mode . VALIDATE ) ; else if ( processedCommand . getArgument ( ) != null ) resetField ( getObject ( ) , processedCommand . getArgument ( ) . getFieldName ( ) , true ) ; }
Populate a Command instance with the values parsed from a command line If any parser errors are detected it will throw an exception
26,482
public List < TerminalString > getOptionLongNamesWithDash ( ) { List < ProcessedOption > opts = getOptions ( ) ; List < TerminalString > names = new ArrayList < > ( opts . size ( ) ) ; for ( ProcessedOption o : opts ) { if ( o . getValues ( ) . size ( ) == 0 && o . activator ( ) . isActivated ( new ParsedCommand ( this ) ) ) names . add ( o . getRenderedNameWithDashes ( ) ) ; } return names ; }
Return all option names that not already have a value and is enabled
26,483
public String printHelp ( String commandName ) { int maxLength = 0 ; int width = 80 ; List < ProcessedOption > opts = getOptions ( ) ; for ( ProcessedOption o : opts ) { if ( o . getFormattedLength ( ) > maxLength ) maxLength = o . getFormattedLength ( ) ; } StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Usage: " ) ; if ( commandName == null || commandName . length ( ) == 0 ) sb . append ( name ( ) ) ; else sb . append ( commandName ) ; if ( opts . size ( ) > 0 ) sb . append ( " [<options>]" ) ; if ( argument != null ) { if ( argument . isTypeAssignableByResourcesOrFile ( ) ) sb . append ( " <file>" ) ; else sb . append ( " <" ) . append ( argument . getFieldName ( ) ) . append ( ">" ) ; } if ( arguments != null ) { if ( arguments . isTypeAssignableByResourcesOrFile ( ) ) sb . append ( " [<files>]" ) ; else sb . append ( " [<" ) . append ( arguments . getFieldName ( ) ) . append ( ">]" ) ; } sb . append ( Config . getLineSeparator ( ) ) ; sb . append ( description ( ) ) . append ( Config . getLineSeparator ( ) ) ; if ( opts . size ( ) > 0 ) sb . append ( Config . getLineSeparator ( ) ) . append ( "Options:" ) . append ( Config . getLineSeparator ( ) ) ; for ( ProcessedOption o : opts ) sb . append ( o . getFormattedOption ( 2 , maxLength + 4 , width ) ) . append ( Config . getLineSeparator ( ) ) ; if ( arguments != null ) { sb . append ( Config . getLineSeparator ( ) ) . append ( "Arguments:" ) . append ( Config . getLineSeparator ( ) ) ; sb . append ( arguments . getFormattedOption ( 2 , maxLength + 4 , width ) ) . append ( Config . getLineSeparator ( ) ) ; } if ( argument != null ) { sb . append ( Config . getLineSeparator ( ) ) . append ( "Argument:" ) . append ( Config . getLineSeparator ( ) ) ; sb . append ( argument . getFormattedOption ( 2 , maxLength + 4 , width ) ) . append ( Config . getLineSeparator ( ) ) ; } return sb . toString ( ) ; }
Returns a description String based on the defined command and options . Useful when printing help info etc .
26,484
public boolean hasUniqueLongOption ( String optionName ) { if ( hasLongOption ( optionName ) ) { for ( ProcessedOption o : getOptions ( ) ) { if ( o . name ( ) . startsWith ( optionName ) && ! o . name ( ) . equals ( optionName ) ) return false ; } return true ; } return false ; }
not start with another option name
26,485
public void seek ( final int position ) throws IOException { if ( position < 0 ) { throw new IllegalArgumentException ( "position < 0: " + position ) ; } if ( position > size ) { throw new EOFException ( ) ; } this . pointer = position ; }
Sets the file - pointer offset measured from the beginning of this file at which the next read or write occurs .
26,486
public EditMode editMode ( ) { if ( readInputrc ) { try { return EditModeBuilder . builder ( ) . parseInputrc ( new FileInputStream ( inputrc ( ) ) ) . create ( ) ; } catch ( FileNotFoundException e ) { return EditModeBuilder . builder ( mode ( ) ) . create ( ) ; } } else return EditModeBuilder . builder ( mode ( ) ) . create ( ) ; }
Get EditMode based on os and mode
26,487
public String logFile ( ) { if ( logFile == null ) { logFile = Config . getTmpDir ( ) + Config . getPathSeparator ( ) + "aesh.log" ; } return logFile ; }
Get log file
26,488
public void detect ( final String ... packageNames ) throws IOException { final String [ ] pkgNameFilter = new String [ packageNames . length ] ; for ( int i = 0 ; i < pkgNameFilter . length ; ++ i ) { pkgNameFilter [ i ] = packageNames [ i ] . replace ( '.' , '/' ) ; if ( ! pkgNameFilter [ i ] . endsWith ( "/" ) ) { pkgNameFilter [ i ] = pkgNameFilter [ i ] . concat ( "/" ) ; } } final Set < File > files = new HashSet < > ( ) ; final ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; for ( final String packageName : pkgNameFilter ) { final Enumeration < URL > resourceEnum = loader . getResources ( packageName ) ; while ( resourceEnum . hasMoreElements ( ) ) { final URL url = resourceEnum . nextElement ( ) ; if ( "file" . equals ( url . getProtocol ( ) ) ) { final File dir = toFile ( url ) ; if ( dir . isDirectory ( ) ) { files . add ( dir ) ; } else { throw new AssertionError ( "Not a recognized file URL: " + url ) ; } } else { final File jarFile = toFile ( openJarURLConnection ( url ) . getJarFileURL ( ) ) ; if ( jarFile . isFile ( ) ) { files . add ( jarFile ) ; } else { throw new AssertionError ( "Not a File: " + jarFile ) ; } } } } if ( DEBUG ) { print ( "Files to scan: %s" , files ) ; } if ( ! files . isEmpty ( ) ) { detect ( new ClassFileIterator ( files . toArray ( new File [ 0 ] ) , pkgNameFilter ) ) ; } }
Report all Java ClassFile files available on the class path within the specified packages and sub packages .
26,489
private void addReverse ( final File [ ] files ) { for ( int i = files . length - 1 ; i >= 0 ; -- i ) { stack . add ( files [ i ] ) ; } }
Add the specified files in reverse order .
26,490
public < C extends Contextual < I > , I > C getContextual ( String id ) { return this . < C , I > getContextual ( new StringBeanIdentifier ( id ) ) ; }
Given a particular id return the correct contextual . For contextuals which aren t passivation capable the contextual can t be found in another container and null will be returned .
26,491
private void processDestructionQueue ( HttpServletRequest request ) { Object contextsAttribute = request . getAttribute ( DESTRUCTION_QUEUE_ATTRIBUTE_NAME ) ; if ( contextsAttribute instanceof Map ) { Map < String , List < ContextualInstance < ? > > > contexts = cast ( contextsAttribute ) ; synchronized ( contexts ) { FastEvent < String > beforeDestroyedEvent = FastEvent . of ( String . class , beanManager , BeforeDestroyed . Literal . CONVERSATION ) ; FastEvent < String > destroyedEvent = FastEvent . of ( String . class , beanManager , Destroyed . Literal . CONVERSATION ) ; for ( Iterator < Entry < String , List < ContextualInstance < ? > > > > iterator = contexts . entrySet ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { Entry < String , List < ContextualInstance < ? > > > entry = iterator . next ( ) ; beforeDestroyedEvent . fire ( entry . getKey ( ) ) ; for ( ContextualInstance < ? > contextualInstance : entry . getValue ( ) ) { destroyContextualInstance ( contextualInstance ) ; } destroyedEvent . fire ( entry . getKey ( ) ) ; iterator . remove ( ) ; } } } }
If needed destroy the remaining conversation contexts after an HTTP session was invalidated within the current request .
26,492
public static void unregisterContextualInstance ( EjbDescriptor < ? > descriptor ) { Set < Class < ? > > classes = CONTEXTUAL_SESSION_BEANS . get ( ) ; classes . remove ( descriptor . getBeanClass ( ) ) ; if ( classes . isEmpty ( ) ) { CONTEXTUAL_SESSION_BEANS . remove ( ) ; } }
Indicates that contextual session bean instance has been constructed .
26,493
protected Object [ ] getParameterValues ( Object specialVal , BeanManagerImpl manager , CreationalContext < ? > ctx , CreationalContext < ? > transientReferenceContext ) { if ( getInjectionPoints ( ) . isEmpty ( ) ) { if ( specialInjectionPointIndex == - 1 ) { return Arrays2 . EMPTY_ARRAY ; } else { return new Object [ ] { specialVal } ; } } Object [ ] parameterValues = new Object [ getParameterInjectionPoints ( ) . size ( ) ] ; List < ParameterInjectionPoint < ? , X > > parameters = getParameterInjectionPoints ( ) ; for ( int i = 0 ; i < parameterValues . length ; i ++ ) { ParameterInjectionPoint < ? , ? > param = parameters . get ( i ) ; if ( i == specialInjectionPointIndex ) { parameterValues [ i ] = specialVal ; } else if ( hasTransientReferenceParameter && param . getAnnotated ( ) . isAnnotationPresent ( TransientReference . class ) ) { parameterValues [ i ] = param . getValueToInject ( manager , transientReferenceContext ) ; } else { parameterValues [ i ] = param . getValueToInject ( manager , ctx ) ; } } return parameterValues ; }
Helper method for getting the current parameter values from a list of annotated parameters .
26,494
public Set < ? extends AbstractBean < ? , ? > > resolveSpecializedBeans ( Bean < ? > specializingBean ) { if ( specializingBean instanceof AbstractClassBean < ? > ) { AbstractClassBean < ? > abstractClassBean = ( AbstractClassBean < ? > ) specializingBean ; if ( abstractClassBean . isSpecializing ( ) ) { return specializedBeans . getValue ( specializingBean ) ; } } if ( specializingBean instanceof ProducerMethod < ? , ? > ) { ProducerMethod < ? , ? > producerMethod = ( ProducerMethod < ? , ? > ) specializingBean ; if ( producerMethod . isSpecializing ( ) ) { return specializedBeans . getValue ( specializingBean ) ; } } return Collections . emptySet ( ) ; }
Returns a set of beans specialized by this bean . An empty set is returned if this bean does not specialize another beans .
26,495
private void addHandlerInitializerMethod ( ClassFile proxyClassType , ClassMethod staticConstructor ) throws Exception { ClassMethod classMethod = proxyClassType . addMethod ( AccessFlag . PRIVATE , INIT_MH_METHOD_NAME , BytecodeUtils . VOID_CLASS_DESCRIPTOR , LJAVA_LANG_OBJECT ) ; final CodeAttribute b = classMethod . getCodeAttribute ( ) ; b . aload ( 0 ) ; StaticMethodInformation methodInfo = new StaticMethodInformation ( INIT_MH_METHOD_NAME , new Class [ ] { Object . class } , void . class , classMethod . getClassFile ( ) . getName ( ) ) ; invokeMethodHandler ( classMethod , methodInfo , false , DEFAULT_METHOD_RESOLVER , staticConstructor ) ; b . checkcast ( MethodHandler . class ) ; b . putfield ( classMethod . getClassFile ( ) . getName ( ) , METHOD_HANDLER_FIELD_NAME , DescriptorUtils . makeDescriptor ( MethodHandler . class ) ) ; b . returnInstruction ( ) ; BeanLogger . LOG . createdMethodHandlerInitializerForDecoratorProxy ( getBeanType ( ) ) ; }
calls _initMH on the method handler and then stores the result in the methodHandler field as then new methodHandler
26,496
private static boolean isEqual ( Method m , Method a ) { if ( m . getName ( ) . equals ( a . getName ( ) ) && m . getParameterTypes ( ) . length == a . getParameterTypes ( ) . length && m . getReturnType ( ) . isAssignableFrom ( a . getReturnType ( ) ) ) { for ( int i = 0 ; i < m . getParameterTypes ( ) . length ; i ++ ) { if ( ! ( m . getParameterTypes ( ) [ i ] . isAssignableFrom ( a . getParameterTypes ( ) [ i ] ) ) ) { return false ; } } return true ; } return false ; }
m is more generic than a
26,497
protected CDI11Deployment createDeployment ( ServletContext context , CDI11Bootstrap bootstrap ) { ImmutableSet . Builder < Metadata < Extension > > extensionsBuilder = ImmutableSet . builder ( ) ; extensionsBuilder . addAll ( bootstrap . loadExtensions ( WeldResourceLoader . getClassLoader ( ) ) ) ; if ( isDevModeEnabled ) { extensionsBuilder . add ( new MetadataImpl < Extension > ( DevelopmentMode . getProbeExtension ( resourceLoader ) , "N/A" ) ) ; } final Iterable < Metadata < Extension > > extensions = extensionsBuilder . build ( ) ; final TypeDiscoveryConfiguration typeDiscoveryConfiguration = bootstrap . startExtensions ( extensions ) ; final EEModuleDescriptor eeModule = new EEModuleDescriptorImpl ( context . getContextPath ( ) , ModuleType . WEB ) ; final DiscoveryStrategy strategy = DiscoveryStrategyFactory . create ( resourceLoader , bootstrap , typeDiscoveryConfiguration . getKnownBeanDefiningAnnotations ( ) , Boolean . parseBoolean ( context . getInitParameter ( Jandex . DISABLE_JANDEX_DISCOVERY_STRATEGY ) ) ) ; if ( Jandex . isJandexAvailable ( resourceLoader ) ) { try { Class < ? extends BeanArchiveHandler > handlerClass = Reflections . loadClass ( resourceLoader , JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER ) ; strategy . registerHandler ( ( SecurityActions . newConstructorInstance ( handlerClass , new Class < ? > [ ] { ServletContext . class } , context ) ) ) ; } catch ( Exception e ) { throw CommonLogger . LOG . unableToInstantiate ( JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER , Arrays . toString ( new Object [ ] { context } ) , e ) ; } } else { strategy . registerHandler ( new ServletContextBeanArchiveHandler ( context ) ) ; } strategy . setScanner ( new WebAppBeanArchiveScanner ( resourceLoader , bootstrap , context ) ) ; Set < WeldBeanDeploymentArchive > beanDeploymentArchives = strategy . performDiscovery ( ) ; String isolation = context . getInitParameter ( CONTEXT_PARAM_ARCHIVE_ISOLATION ) ; if ( isolation == null || Boolean . valueOf ( isolation ) ) { CommonLogger . LOG . archiveIsolationEnabled ( ) ; } else { CommonLogger . LOG . archiveIsolationDisabled ( ) ; Set < WeldBeanDeploymentArchive > flatDeployment = new HashSet < WeldBeanDeploymentArchive > ( ) ; flatDeployment . add ( WeldBeanDeploymentArchive . merge ( bootstrap , beanDeploymentArchives ) ) ; beanDeploymentArchives = flatDeployment ; } for ( BeanDeploymentArchive archive : beanDeploymentArchives ) { archive . getServices ( ) . add ( EEModuleDescriptor . class , eeModule ) ; } CDI11Deployment deployment = new WeldDeployment ( resourceLoader , bootstrap , beanDeploymentArchives , extensions ) { protected WeldBeanDeploymentArchive createAdditionalBeanDeploymentArchive ( ) { WeldBeanDeploymentArchive archive = super . createAdditionalBeanDeploymentArchive ( ) ; archive . getServices ( ) . add ( EEModuleDescriptor . class , eeModule ) ; return archive ; } } ; if ( strategy . getClassFileServices ( ) != null ) { deployment . getServices ( ) . add ( ClassFileServices . class , strategy . getClassFileServices ( ) ) ; } return deployment ; }
Create servlet deployment .
26,498
protected Container findContainer ( ContainerContext ctx , StringBuilder dump ) { Container container = null ; String containerClassName = ctx . getServletContext ( ) . getInitParameter ( Container . CONTEXT_PARAM_CONTAINER_CLASS ) ; if ( containerClassName != null ) { try { Class < Container > containerClass = Reflections . classForName ( resourceLoader , containerClassName ) ; container = SecurityActions . newInstance ( containerClass ) ; WeldServletLogger . LOG . containerDetectionSkipped ( containerClassName ) ; } catch ( Exception e ) { WeldServletLogger . LOG . unableToInstantiateCustomContainerClass ( containerClassName ) ; WeldServletLogger . LOG . catchingDebug ( e ) ; } } if ( container == null ) { Iterable < Container > extContainers = ServiceLoader . load ( Container . class , getClass ( ) . getClassLoader ( ) ) ; container = checkContainers ( ctx , dump , extContainers ) ; if ( container == null ) { container = checkContainers ( ctx , dump , Arrays . asList ( TomcatContainer . INSTANCE , JettyContainer . INSTANCE , UndertowContainer . INSTANCE , GwtDevHostedModeContainer . INSTANCE ) ) ; } } return container ; }
Find container env .
26,499
private Resolvable createMetadataProvider ( Class < ? > rawType ) { Set < Type > types = Collections . < Type > singleton ( rawType ) ; return new ResolvableImpl ( rawType , types , declaringBean , qualifierInstances , delegate ) ; }
just as facade but we keep the qualifiers so that we can recognize Bean from