idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
29,600
private static void searchProbableMaster ( AuroraListener listener , final GlobalStateInfo globalInfo , HostAddress probableMaster ) { AuroraProtocol protocol = getNewProtocol ( listener . getProxy ( ) , globalInfo , listener . getUrlParser ( ) ) ; try { protocol . setHostAddress ( probableMaster ) ; protocol . connect ( ) ; listener . removeFromBlacklist ( protocol . getHostAddress ( ) ) ; if ( listener . isMasterHostFailReconnect ( ) && protocol . isMasterConnection ( ) ) { protocol . setMustBeMasterConnection ( true ) ; listener . foundActiveMaster ( protocol ) ; } else if ( listener . isSecondaryHostFailReconnect ( ) && ! protocol . isMasterConnection ( ) ) { protocol . setMustBeMasterConnection ( false ) ; listener . foundActiveSecondary ( protocol ) ; } else { protocol . close ( ) ; protocol = getNewProtocol ( listener . getProxy ( ) , globalInfo , listener . getUrlParser ( ) ) ; } } catch ( SQLException e ) { listener . addToBlacklist ( protocol . getHostAddress ( ) ) ; } }
Connect aurora probable master . Aurora master change in time . The only way to check that a server is a master is to asked him .
29,601
public static AuroraProtocol getNewProtocol ( FailoverProxy proxy , final GlobalStateInfo globalInfo , UrlParser urlParser ) { AuroraProtocol newProtocol = new AuroraProtocol ( urlParser , globalInfo , proxy . lock ) ; newProtocol . setProxy ( proxy ) ; return newProtocol ; }
Initialize new protocol instance .
29,602
public void reset ( ) { insertIds . clear ( ) ; updateCounts . clear ( ) ; insertIdNumber = 0 ; hasException = false ; rewritten = false ; }
Clear error state used for clear exception after first batch query when fall back to per - query execution .
29,603
private boolean readNextValue ( ) throws IOException , SQLException { byte [ ] buf = reader . getPacketArray ( false ) ; if ( buf [ 0 ] == ERROR ) { protocol . removeActiveStreamingResult ( ) ; protocol . removeHasMoreResults ( ) ; protocol . setHasWarnings ( false ) ; ErrorPacket errorPacket = new ErrorPacket ( new Buffer ( buf ) ) ; resetVariables ( ) ; throw ExceptionMapper . get ( errorPacket . getMessage ( ) , errorPacket . getSqlState ( ) , errorPacket . getErrorNumber ( ) , null , false ) ; } if ( buf [ 0 ] == EOF && ( ( eofDeprecated && buf . length < 0xffffff ) || ( ! eofDeprecated && buf . length < 8 ) ) ) { int serverStatus ; int warnings ; if ( ! eofDeprecated ) { warnings = ( buf [ 1 ] & 0xff ) + ( ( buf [ 2 ] & 0xff ) << 8 ) ; serverStatus = ( ( buf [ 3 ] & 0xff ) + ( ( buf [ 4 ] & 0xff ) << 8 ) ) ; if ( callableResult ) { serverStatus |= MORE_RESULTS_EXISTS ; } } else { int pos = skipLengthEncodedValue ( buf , 1 ) ; pos = skipLengthEncodedValue ( buf , pos ) ; serverStatus = ( ( buf [ pos ++ ] & 0xff ) + ( ( buf [ pos ++ ] & 0xff ) << 8 ) ) ; warnings = ( buf [ pos ++ ] & 0xff ) + ( ( buf [ pos ] & 0xff ) << 8 ) ; callableResult = ( serverStatus & PS_OUT_PARAMETERS ) != 0 ; } protocol . setServerStatus ( ( short ) serverStatus ) ; protocol . setHasWarnings ( warnings > 0 ) ; if ( ( serverStatus & MORE_RESULTS_EXISTS ) == 0 ) { protocol . removeActiveStreamingResult ( ) ; } resetVariables ( ) ; return false ; } if ( dataSize + 1 >= data . length ) { growDataArray ( ) ; } data [ dataSize ++ ] = buf ; return true ; }
Read next value .
29,604
protected void deleteCurrentRowData ( ) throws SQLException { System . arraycopy ( data , rowPointer + 1 , data , rowPointer , dataSize - 1 - rowPointer ) ; data [ dataSize - 1 ] = null ; dataSize -- ; lastRowPointer = - 1 ; previous ( ) ; }
Delete current data . Position cursor to the previous row .
29,605
public void close ( ) throws SQLException { isClosed = true ; if ( ! isEof ) { lock . lock ( ) ; try { while ( ! isEof ) { dataSize = 0 ; readNextValue ( ) ; } } catch ( SQLException queryException ) { throw ExceptionMapper . getException ( queryException , null , this . statement , false ) ; } catch ( IOException ioe ) { throw handleIoException ( ioe ) ; } finally { resetVariables ( ) ; lock . unlock ( ) ; } } resetVariables ( ) ; for ( int i = 0 ; i < data . length ; i ++ ) { data [ i ] = null ; } if ( statement != null ) { statement . checkCloseOnCompletion ( this ) ; statement = null ; } }
Close resultSet .
29,606
private int nameToIndex ( String parameterName ) throws SQLException { parameterMetadata . readMetadataFromDbIfRequired ( ) ; for ( int i = 1 ; i <= parameterMetadata . getParameterCount ( ) ; i ++ ) { String name = parameterMetadata . getName ( i ) ; if ( name != null && name . equalsIgnoreCase ( parameterName ) ) { return i ; } } throw new SQLException ( "there is no parameter with the name " + parameterName ) ; }
Convert parameter name to parameter index in the query .
29,607
private int nameToOutputIndex ( String parameterName ) throws SQLException { parameterMetadata . readMetadataFromDbIfRequired ( ) ; for ( int i = 0 ; i < parameterMetadata . getParameterCount ( ) ; i ++ ) { String name = parameterMetadata . getName ( i + 1 ) ; if ( name != null && name . equalsIgnoreCase ( parameterName ) ) { if ( outputParameterMapper [ i ] == - 1 ) { throw new SQLException ( "Parameter '" + parameterName + "' is not declared as output parameter with method registerOutParameter" ) ; } return outputParameterMapper [ i ] ; } } throw new SQLException ( "there is no parameter with the name " + parameterName ) ; }
Convert parameter name to output parameter index in the query .
29,608
private int indexToOutputIndex ( int parameterIndex ) throws SQLException { try { if ( outputParameterMapper [ parameterIndex - 1 ] == - 1 ) { throw new SQLException ( "Parameter in index '" + parameterIndex + "' is not declared as output parameter with method registerOutParameter" ) ; } return outputParameterMapper [ parameterIndex - 1 ] ; } catch ( ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException ) { if ( parameterIndex < 1 ) { throw new SQLException ( "Index " + parameterIndex + " must at minimum be 1" ) ; } throw new SQLException ( "Index value '" + parameterIndex + "' is incorrect. Maximum value is " + params . size ( ) ) ; } }
Convert parameter index to corresponding outputIndex .
29,609
public void writeTo ( PacketOutputStream pos ) throws IOException { pos . write ( QUOTE ) ; if ( length == Long . MAX_VALUE ) { pos . write ( reader , true , noBackslashEscapes ) ; } else { pos . write ( reader , length , true , noBackslashEscapes ) ; } pos . write ( QUOTE ) ; }
Write reader to database in text format .
29,610
public void reset ( ) throws SQLException { cmdPrologue ( ) ; try { writer . startPacket ( 0 ) ; writer . write ( COM_RESET_CONNECTION ) ; writer . flush ( ) ; getResult ( new Results ( ) ) ; if ( options . cachePrepStmts && options . useServerPrepStmts ) { serverPrepareStatementCache . clear ( ) ; } } catch ( SQLException sqlException ) { throw logQuery . exceptionWithQuery ( "COM_RESET_CONNECTION failed." , sqlException , explicitClosed ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } }
Reset connection state .
29,611
public void executeQuery ( boolean mustExecuteOnMaster , Results results , final String sql ) throws SQLException { cmdPrologue ( ) ; try { writer . startPacket ( 0 ) ; writer . write ( COM_QUERY ) ; writer . write ( sql ) ; writer . flush ( ) ; getResult ( results ) ; } catch ( SQLException sqlException ) { if ( "70100" . equals ( sqlException . getSQLState ( ) ) && 1927 == sqlException . getErrorCode ( ) ) { throw handleIoException ( sqlException ) ; } throw logQuery . exceptionWithQuery ( sql , sqlException , explicitClosed ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } }
Execute query directly to outputStream .
29,612
public void executeQuery ( boolean mustExecuteOnMaster , Results results , final ClientPrepareResult clientPrepareResult , ParameterHolder [ ] parameters ) throws SQLException { cmdPrologue ( ) ; try { if ( clientPrepareResult . getParamCount ( ) == 0 && ! clientPrepareResult . isQueryMultiValuesRewritable ( ) ) { if ( clientPrepareResult . getQueryParts ( ) . size ( ) == 1 ) { ComQuery . sendDirect ( writer , clientPrepareResult . getQueryParts ( ) . get ( 0 ) ) ; } else { ComQuery . sendMultiDirect ( writer , clientPrepareResult . getQueryParts ( ) ) ; } } else { writer . startPacket ( 0 ) ; ComQuery . sendSubCmd ( writer , clientPrepareResult , parameters , - 1 ) ; writer . flush ( ) ; } getResult ( results ) ; } catch ( SQLException queryException ) { throw logQuery . exceptionWithQuery ( parameters , queryException , clientPrepareResult ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } }
Execute a unique clientPrepareQuery .
29,613
private void executeBatch ( Results results , final List < String > queries ) throws SQLException { if ( ! options . useBatchMultiSend ) { String sql = null ; SQLException exception = null ; for ( int i = 0 ; i < queries . size ( ) && ! isInterrupted ( ) ; i ++ ) { try { sql = queries . get ( i ) ; writer . startPacket ( 0 ) ; writer . write ( COM_QUERY ) ; writer . write ( sql ) ; writer . flush ( ) ; getResult ( results ) ; } catch ( SQLException sqlException ) { if ( exception == null ) { exception = logQuery . exceptionWithQuery ( sql , sqlException , explicitClosed ) ; if ( ! options . continueBatchOnError ) { throw exception ; } } } catch ( IOException e ) { if ( exception == null ) { exception = handleIoException ( e ) ; if ( ! options . continueBatchOnError ) { throw exception ; } } } } stopIfInterrupted ( ) ; if ( exception != null ) { throw exception ; } return ; } initializeBatchReader ( ) ; new AbstractMultiSend ( this , writer , results , queries ) { public void sendCmd ( PacketOutputStream pos , Results results , List < ParameterHolder [ ] > parametersList , List < String > queries , int paramCount , BulkStatus status , PrepareResult prepareResult ) throws IOException { String sql = queries . get ( status . sendCmdCounter ) ; pos . startPacket ( 0 ) ; pos . write ( COM_QUERY ) ; pos . write ( sql ) ; pos . flush ( ) ; } public SQLException handleResultException ( SQLException qex , Results results , List < ParameterHolder [ ] > parametersList , List < String > queries , int currentCounter , int sendCmdCounter , int paramCount , PrepareResult prepareResult ) { String sql = queries . get ( currentCounter + sendCmdCounter ) ; return logQuery . exceptionWithQuery ( sql , qex , explicitClosed ) ; } public int getParamCount ( ) { return - 1 ; } public int getTotalExecutionNumber ( ) { return queries . size ( ) ; } } . executeBatch ( ) ; }
Execute list of queries not rewritable .
29,614
public ServerPrepareResult prepare ( String sql , boolean executeOnMaster ) throws SQLException { cmdPrologue ( ) ; lock . lock ( ) ; try { if ( options . cachePrepStmts && options . useServerPrepStmts ) { ServerPrepareResult pr = serverPrepareStatementCache . get ( database + "-" + sql ) ; if ( pr != null && pr . incrementShareCounter ( ) ) { return pr ; } } writer . startPacket ( 0 ) ; writer . write ( COM_STMT_PREPARE ) ; writer . write ( sql ) ; writer . flush ( ) ; ComStmtPrepare comStmtPrepare = new ComStmtPrepare ( this , sql ) ; return comStmtPrepare . read ( reader , eofDeprecated ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } finally { lock . unlock ( ) ; } }
Prepare query on server side . Will permit to know the parameter number of the query and permit to send only the data on next results .
29,615
private void executeBatchRewrite ( Results results , final ClientPrepareResult prepareResult , List < ParameterHolder [ ] > parameterList , boolean rewriteValues ) throws SQLException { cmdPrologue ( ) ; ParameterHolder [ ] parameters ; int currentIndex = 0 ; int totalParameterList = parameterList . size ( ) ; try { do { currentIndex = ComQuery . sendRewriteCmd ( writer , prepareResult . getQueryParts ( ) , currentIndex , prepareResult . getParamCount ( ) , parameterList , rewriteValues ) ; getResult ( results ) ; if ( Thread . currentThread ( ) . isInterrupted ( ) ) { throw new SQLException ( "Interrupted during batch" , INTERRUPTED_EXCEPTION . getSqlState ( ) , - 1 ) ; } } while ( currentIndex < totalParameterList ) ; } catch ( SQLException sqlEx ) { throw logQuery . exceptionWithQuery ( sqlEx , prepareResult ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } finally { results . setRewritten ( rewriteValues ) ; } }
Specific execution for batch rewrite that has specific query for memory .
29,616
public boolean executeBatchServer ( boolean mustExecuteOnMaster , ServerPrepareResult serverPrepareResult , Results results , String sql , final List < ParameterHolder [ ] > parametersList , boolean hasLongData ) throws SQLException { cmdPrologue ( ) ; if ( options . useBulkStmts && ! hasLongData && results . getAutoGeneratedKeys ( ) == Statement . NO_GENERATED_KEYS && versionGreaterOrEqual ( 10 , 2 , 7 ) && executeBulkBatch ( results , sql , serverPrepareResult , parametersList ) ) { return true ; } if ( ! options . useBatchMultiSend ) { return false ; } initializeBatchReader ( ) ; new AbstractMultiSend ( this , writer , results , serverPrepareResult , parametersList , true , sql ) { public void sendCmd ( PacketOutputStream writer , Results results , List < ParameterHolder [ ] > parametersList , List < String > queries , int paramCount , BulkStatus status , PrepareResult prepareResult ) throws SQLException , IOException { ParameterHolder [ ] parameters = parametersList . get ( status . sendCmdCounter ) ; if ( parameters . length < paramCount ) { throw new SQLException ( "Parameter at position " + ( paramCount - 1 ) + " is not set" , "07004" ) ; } for ( int i = 0 ; i < paramCount ; i ++ ) { if ( parameters [ i ] . isLongData ( ) ) { writer . startPacket ( 0 ) ; writer . write ( COM_STMT_SEND_LONG_DATA ) ; writer . writeInt ( statementId ) ; writer . writeShort ( ( short ) i ) ; parameters [ i ] . writeBinary ( writer ) ; writer . flush ( ) ; } } writer . startPacket ( 0 ) ; ComStmtExecute . writeCmd ( statementId , parameters , paramCount , parameterTypeHeader , writer , CURSOR_TYPE_NO_CURSOR ) ; writer . flush ( ) ; } public SQLException handleResultException ( SQLException qex , Results results , List < ParameterHolder [ ] > parametersList , List < String > queries , int currentCounter , int sendCmdCounter , int paramCount , PrepareResult prepareResult ) { return logQuery . exceptionWithQuery ( qex , prepareResult ) ; } public int getParamCount ( ) { return getPrepareResult ( ) == null ? parametersList . get ( 0 ) . length : ( ( ServerPrepareResult ) getPrepareResult ( ) ) . getParameters ( ) . length ; } public int getTotalExecutionNumber ( ) { return parametersList . size ( ) ; } } . executeBatch ( ) ; return true ; }
Execute Prepare if needed and execute COM_STMT_EXECUTE queries in batch .
29,617
public void executePreparedQuery ( boolean mustExecuteOnMaster , ServerPrepareResult serverPrepareResult , Results results , ParameterHolder [ ] parameters ) throws SQLException { cmdPrologue ( ) ; try { int parameterCount = serverPrepareResult . getParameters ( ) . length ; for ( int i = 0 ; i < parameterCount ; i ++ ) { if ( parameters [ i ] . isLongData ( ) ) { writer . startPacket ( 0 ) ; writer . write ( COM_STMT_SEND_LONG_DATA ) ; writer . writeInt ( serverPrepareResult . getStatementId ( ) ) ; writer . writeShort ( ( short ) i ) ; parameters [ i ] . writeBinary ( writer ) ; writer . flush ( ) ; } } ComStmtExecute . send ( writer , serverPrepareResult . getStatementId ( ) , parameters , parameterCount , serverPrepareResult . getParameterTypeHeader ( ) , CURSOR_TYPE_NO_CURSOR ) ; getResult ( results ) ; } catch ( SQLException qex ) { throw logQuery . exceptionWithQuery ( parameters , qex , serverPrepareResult ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } }
Execute a query that is already prepared .
29,618
public void rollback ( ) throws SQLException { cmdPrologue ( ) ; lock . lock ( ) ; try { if ( inTransaction ( ) ) { executeQuery ( "ROLLBACK" ) ; } } catch ( Exception e ) { } finally { lock . unlock ( ) ; } }
Rollback transaction .
29,619
public boolean forceReleasePrepareStatement ( int statementId ) throws SQLException { if ( lock . tryLock ( ) ) { try { checkClose ( ) ; try { writer . startPacket ( 0 ) ; writer . write ( COM_STMT_CLOSE ) ; writer . writeInt ( statementId ) ; writer . flush ( ) ; return true ; } catch ( IOException e ) { connected = false ; throw new SQLException ( "Could not deallocate query: " + e . getMessage ( ) , CONNECTION_EXCEPTION . getSqlState ( ) , e ) ; } } finally { lock . unlock ( ) ; } } else { statementIdToRelease = statementId ; } return false ; }
Force release of prepare statement that are not used . This method will be call when adding a new prepare statement in cache so the packet can be send to server without problem .
29,620
public void cancelCurrentQuery ( ) throws SQLException { try ( MasterProtocol copiedProtocol = new MasterProtocol ( urlParser , new GlobalStateInfo ( ) , new ReentrantLock ( ) ) ) { copiedProtocol . setHostAddress ( getHostAddress ( ) ) ; copiedProtocol . connect ( ) ; copiedProtocol . executeQuery ( "KILL QUERY " + serverThreadId ) ; } interrupted = true ; }
Cancels the current query - clones the current protocol and executes a query using the new connection .
29,621
public void releasePrepareStatement ( ServerPrepareResult serverPrepareResult ) throws SQLException { serverPrepareResult . decrementShareCounter ( ) ; if ( serverPrepareResult . canBeDeallocate ( ) ) { forceReleasePrepareStatement ( serverPrepareResult . getStatementId ( ) ) ; } }
Deallocate prepare statement if not used anymore .
29,622
public void setTimeout ( int timeout ) throws SocketException { lock . lock ( ) ; try { this . socket . setSoTimeout ( timeout ) ; } finally { lock . unlock ( ) ; } }
Sets the connection timeout .
29,623
public void setTransactionIsolation ( final int level ) throws SQLException { cmdPrologue ( ) ; lock . lock ( ) ; try { String query = "SET SESSION TRANSACTION ISOLATION LEVEL" ; switch ( level ) { case Connection . TRANSACTION_READ_UNCOMMITTED : query += " READ UNCOMMITTED" ; break ; case Connection . TRANSACTION_READ_COMMITTED : query += " READ COMMITTED" ; break ; case Connection . TRANSACTION_REPEATABLE_READ : query += " REPEATABLE READ" ; break ; case Connection . TRANSACTION_SERIALIZABLE : query += " SERIALIZABLE" ; break ; default : throw new SQLException ( "Unsupported transaction isolation level" ) ; } executeQuery ( query ) ; transactionIsolationLevel = level ; } finally { lock . unlock ( ) ; } }
Set transaction isolation .
29,624
private void readPacket ( Results results ) throws SQLException { Buffer buffer ; try { buffer = reader . getPacket ( true ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } switch ( buffer . getByteAt ( 0 ) ) { case OK : readOkPacket ( buffer , results ) ; break ; case ERROR : throw readErrorPacket ( buffer , results ) ; case LOCAL_INFILE : readLocalInfilePacket ( buffer , results ) ; break ; default : readResultSet ( buffer , results ) ; break ; } }
Read server response packet .
29,625
private void readOkPacket ( Buffer buffer , Results results ) { buffer . skipByte ( ) ; final long updateCount = buffer . getLengthEncodedNumeric ( ) ; final long insertId = buffer . getLengthEncodedNumeric ( ) ; serverStatus = buffer . readShort ( ) ; hasWarnings = ( buffer . readShort ( ) > 0 ) ; if ( ( serverStatus & ServerStatus . SERVER_SESSION_STATE_CHANGED ) != 0 ) { handleStateChange ( buffer , results ) ; } results . addStats ( updateCount , insertId , hasMoreResults ( ) ) ; }
Read OK_Packet .
29,626
private SQLException readErrorPacket ( Buffer buffer , Results results ) { removeHasMoreResults ( ) ; this . hasWarnings = false ; buffer . skipByte ( ) ; final int errorNumber = buffer . readShort ( ) ; String message ; String sqlState ; if ( buffer . readByte ( ) == '#' ) { sqlState = new String ( buffer . readRawBytes ( 5 ) ) ; message = buffer . readStringNullEnd ( StandardCharsets . UTF_8 ) ; } else { buffer . position -= 1 ; message = new String ( buffer . buf , buffer . position , buffer . limit - buffer . position , StandardCharsets . UTF_8 ) ; sqlState = "HY000" ; } results . addStatsError ( false ) ; serverStatus |= ServerStatus . IN_TRANSACTION ; removeActiveStreamingResult ( ) ; return new SQLException ( message , sqlState , errorNumber ) ; }
Read ERR_Packet .
29,627
private void readLocalInfilePacket ( Buffer buffer , Results results ) throws SQLException { int seq = 2 ; buffer . getLengthEncodedNumeric ( ) ; String fileName = buffer . readStringNullEnd ( StandardCharsets . UTF_8 ) ; try { InputStream is ; writer . startPacket ( seq ) ; if ( localInfileInputStream == null ) { if ( ! getUrlParser ( ) . getOptions ( ) . allowLocalInfile ) { writer . writeEmptyPacket ( ) ; reader . getPacket ( true ) ; throw new SQLException ( "Usage of LOCAL INFILE is disabled. To use it enable it via the connection property allowLocalInfile=true" , FEATURE_NOT_SUPPORTED . getSqlState ( ) , - 1 ) ; } ServiceLoader < LocalInfileInterceptor > loader = ServiceLoader . load ( LocalInfileInterceptor . class ) ; for ( LocalInfileInterceptor interceptor : loader ) { if ( ! interceptor . validate ( fileName ) ) { writer . writeEmptyPacket ( ) ; reader . getPacket ( true ) ; throw new SQLException ( "LOCAL DATA LOCAL INFILE request to send local file named \"" + fileName + "\" not validated by interceptor \"" + interceptor . getClass ( ) . getName ( ) + "\"" ) ; } } try { URL url = new URL ( fileName ) ; is = url . openStream ( ) ; } catch ( IOException ioe ) { try { is = new FileInputStream ( fileName ) ; } catch ( FileNotFoundException f ) { writer . writeEmptyPacket ( ) ; reader . getPacket ( true ) ; throw new SQLException ( "Could not send file : " + f . getMessage ( ) , "22000" , - 1 , f ) ; } } } else { is = localInfileInputStream ; localInfileInputStream = null ; } try { byte [ ] buf = new byte [ 8192 ] ; int len ; while ( ( len = is . read ( buf ) ) > 0 ) { writer . startPacket ( seq ++ ) ; writer . write ( buf , 0 , len ) ; writer . flush ( ) ; } writer . writeEmptyPacket ( ) ; } catch ( IOException ioe ) { throw handleIoException ( ioe ) ; } finally { is . close ( ) ; } getResult ( results ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } }
Read Local_infile Packet .
29,628
private void readResultSet ( Buffer buffer , Results results ) throws SQLException { long fieldCount = buffer . getLengthEncodedNumeric ( ) ; try { ColumnInformation [ ] ci = new ColumnInformation [ ( int ) fieldCount ] ; for ( int i = 0 ; i < fieldCount ; i ++ ) { ci [ i ] = new ColumnInformation ( reader . getPacket ( false ) ) ; } boolean callableResult = false ; if ( ! eofDeprecated ) { Buffer bufferEof = reader . getPacket ( true ) ; if ( bufferEof . readByte ( ) != EOF ) { throw new IOException ( "Packets out of order when reading field packets, expected was EOF stream." + ( ( options . enablePacketDebug ) ? getTraces ( ) : "Packet contents (hex) = " + Utils . hexdump ( options . maxQuerySizeToLog , 0 , bufferEof . limit , bufferEof . buf ) ) ) ; } bufferEof . skipBytes ( 2 ) ; callableResult = ( bufferEof . readShort ( ) & ServerStatus . PS_OUT_PARAMETERS ) != 0 ; } SelectResultSet selectResultSet ; if ( results . getResultSetConcurrency ( ) == ResultSet . CONCUR_READ_ONLY ) { selectResultSet = new SelectResultSet ( ci , results , this , reader , callableResult , eofDeprecated ) ; } else { results . removeFetchSize ( ) ; selectResultSet = new UpdatableResultSet ( ci , results , this , reader , callableResult , eofDeprecated ) ; } results . addResultSet ( selectResultSet , hasMoreResults ( ) || results . getFetchSize ( ) > 0 ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } }
Read ResultSet Packet .
29,629
public void prolog ( long maxRows , boolean hasProxy , MariaDbConnection connection , MariaDbStatement statement ) throws SQLException { if ( explicitClosed ) { throw new SQLException ( "execute() is called on closed connection" ) ; } if ( ! hasProxy && shouldReconnectWithoutProxy ( ) ) { try { connectWithoutProxy ( ) ; } catch ( SQLException qe ) { ExceptionMapper . throwException ( qe , connection , statement ) ; } } try { setMaxRows ( maxRows ) ; } catch ( SQLException qe ) { ExceptionMapper . throwException ( qe , connection , statement ) ; } connection . reenableWarnings ( ) ; }
Preparation before command .
29,630
public SQLException handleIoException ( Exception initialException ) { boolean mustReconnect ; boolean driverPreventError = false ; if ( initialException instanceof MaxAllowedPacketException ) { mustReconnect = ( ( MaxAllowedPacketException ) initialException ) . isMustReconnect ( ) ; driverPreventError = ! mustReconnect ; } else { mustReconnect = writer . exceedMaxLength ( ) ; } if ( mustReconnect ) { try { connect ( ) ; } catch ( SQLException queryException ) { connected = false ; return new SQLNonTransientConnectionException ( initialException . getMessage ( ) + "\nError during reconnection" + getTraces ( ) , CONNECTION_EXCEPTION . getSqlState ( ) , initialException ) ; } try { resetStateAfterFailover ( getMaxRows ( ) , getTransactionIsolationLevel ( ) , getDatabase ( ) , getAutocommit ( ) ) ; } catch ( SQLException queryException ) { return new SQLException ( "reconnection succeed, but resetting previous state failed" , UNDEFINED_SQLSTATE . getSqlState ( ) + getTraces ( ) , initialException ) ; } return new SQLTransientConnectionException ( "Could not send query: query size is >= to max_allowed_packet (" + writer . getMaxAllowedPacket ( ) + ")" + getTraces ( ) , UNDEFINED_SQLSTATE . getSqlState ( ) , initialException ) ; } if ( ! driverPreventError ) { connected = false ; } return new SQLNonTransientConnectionException ( initialException . getMessage ( ) + getTraces ( ) , driverPreventError ? UNDEFINED_SQLSTATE . getSqlState ( ) : CONNECTION_EXCEPTION . getSqlState ( ) , initialException ) ; }
Handle IoException ( reconnect if Exception is due to having send too much data making server close the connection .
29,631
public void writeTo ( final PacketOutputStream pos ) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat ( "HH:mm:ss" ) ; sdf . setTimeZone ( timeZone ) ; String dateString = sdf . format ( time ) ; pos . write ( QUOTE ) ; pos . write ( dateString . getBytes ( ) ) ; int microseconds = ( int ) ( time . getTime ( ) % 1000 ) * 1000 ; if ( microseconds > 0 && fractionalSeconds ) { pos . write ( '.' ) ; int factor = 100000 ; while ( microseconds > 0 ) { int dig = microseconds / factor ; pos . write ( '0' + dig ) ; microseconds -= dig * factor ; factor /= 10 ; } } pos . write ( QUOTE ) ; }
Write Time parameter to outputStream .
29,632
public Connection connect ( final String url , final Properties props ) throws SQLException { UrlParser urlParser = UrlParser . parse ( url , props ) ; if ( urlParser == null || urlParser . getHostAddresses ( ) == null ) { return null ; } else { return MariaDbConnection . newConnection ( urlParser , null ) ; } }
Connect to the given connection string .
29,633
public DriverPropertyInfo [ ] getPropertyInfo ( String url , Properties info ) throws SQLException { if ( url != null ) { UrlParser urlParser = UrlParser . parse ( url , info ) ; if ( urlParser == null || urlParser . getOptions ( ) == null ) { return new DriverPropertyInfo [ 0 ] ; } List < DriverPropertyInfo > props = new ArrayList < > ( ) ; for ( DefaultOptions o : DefaultOptions . values ( ) ) { try { Field field = Options . class . getField ( o . getOptionName ( ) ) ; Object value = field . get ( urlParser . getOptions ( ) ) ; DriverPropertyInfo propertyInfo = new DriverPropertyInfo ( field . getName ( ) , value == null ? null : value . toString ( ) ) ; propertyInfo . description = o . getDescription ( ) ; propertyInfo . required = o . isRequired ( ) ; props . add ( propertyInfo ) ; } catch ( NoSuchFieldException | IllegalAccessException e ) { } } return props . toArray ( new DriverPropertyInfo [ props . size ( ) ] ) ; } return new DriverPropertyInfo [ 0 ] ; }
Get the property info .
29,634
public void initializeConnection ( ) throws SQLException { super . initializeConnection ( ) ; try { reconnectFailedConnection ( new SearchFilter ( true ) ) ; } catch ( SQLException e ) { checkInitialConnection ( e ) ; } }
Initialize connections .
29,635
public void checkWaitingConnection ( ) throws SQLException { if ( isSecondaryHostFail ( ) ) { proxy . lock . lock ( ) ; try { Protocol waitingProtocol = waitNewSecondaryProtocol . getAndSet ( null ) ; if ( waitingProtocol != null && pingSecondaryProtocol ( waitingProtocol ) ) { lockAndSwitchSecondary ( waitingProtocol ) ; } } finally { proxy . lock . unlock ( ) ; } } if ( isMasterHostFail ( ) ) { proxy . lock . lock ( ) ; try { Protocol waitingProtocol = waitNewMasterProtocol . getAndSet ( null ) ; if ( waitingProtocol != null && pingMasterProtocol ( waitingProtocol ) ) { lockAndSwitchMaster ( waitingProtocol ) ; } } finally { proxy . lock . unlock ( ) ; } } }
Verify that there is waiting connection that have to replace failing one . If there is replace failed connection with new one .
29,636
public void reconnectFailedConnection ( SearchFilter searchFilter ) throws SQLException { if ( ! searchFilter . isInitialConnection ( ) && ( isExplicitClosed ( ) || ( searchFilter . isFineIfFoundOnlyMaster ( ) && ! isMasterHostFail ( ) ) || searchFilter . isFineIfFoundOnlySlave ( ) && ! isSecondaryHostFail ( ) ) ) { return ; } if ( ! searchFilter . isFailoverLoop ( ) ) { try { checkWaitingConnection ( ) ; if ( ( searchFilter . isFineIfFoundOnlyMaster ( ) && ! isMasterHostFail ( ) ) || searchFilter . isFineIfFoundOnlySlave ( ) && ! isSecondaryHostFail ( ) ) { return ; } } catch ( ReconnectDuringTransactionException e ) { return ; } } currentConnectionAttempts . incrementAndGet ( ) ; resetOldsBlackListHosts ( ) ; List < HostAddress > loopAddress = new LinkedList < > ( urlParser . getHostAddresses ( ) ) ; loopAddress . removeAll ( getBlacklistKeys ( ) ) ; Collections . shuffle ( loopAddress ) ; List < HostAddress > blacklistShuffle = new LinkedList < > ( getBlacklistKeys ( ) ) ; blacklistShuffle . retainAll ( urlParser . getHostAddresses ( ) ) ; Collections . shuffle ( blacklistShuffle ) ; loopAddress . addAll ( blacklistShuffle ) ; if ( masterProtocol != null && ! isMasterHostFail ( ) ) { loopAddress . remove ( masterProtocol . getHostAddress ( ) ) ; loopAddress . add ( masterProtocol . getHostAddress ( ) ) ; } if ( secondaryProtocol != null && ! isSecondaryHostFail ( ) ) { loopAddress . remove ( secondaryProtocol . getHostAddress ( ) ) ; loopAddress . add ( secondaryProtocol . getHostAddress ( ) ) ; } if ( ( isMasterHostFail ( ) || isSecondaryHostFail ( ) ) || searchFilter . isInitialConnection ( ) ) { do { MastersSlavesProtocol . loop ( this , globalInfo , loopAddress , searchFilter ) ; if ( ! searchFilter . isFailoverLoop ( ) ) { try { checkWaitingConnection ( ) ; } catch ( ReconnectDuringTransactionException e ) { } } } while ( searchFilter . isInitialConnection ( ) && ! ( masterProtocol != null || ( urlParser . getOptions ( ) . allowMasterDownConnection && secondaryProtocol != null ) ) ) ; if ( searchFilter . isInitialConnection ( ) && masterProtocol == null && currentReadOnlyAsked ) { currentProtocol = this . secondaryProtocol ; currentReadOnlyAsked = true ; } } }
Loop to connect .
29,637
public void foundActiveMaster ( Protocol newMasterProtocol ) { if ( isMasterHostFail ( ) ) { if ( isExplicitClosed ( ) ) { newMasterProtocol . close ( ) ; return ; } if ( ! waitNewMasterProtocol . compareAndSet ( null , newMasterProtocol ) ) { newMasterProtocol . close ( ) ; } } else { newMasterProtocol . close ( ) ; } }
Method called when a new Master connection is found after a fallback .
29,638
public void lockAndSwitchMaster ( Protocol newMasterProtocol ) throws ReconnectDuringTransactionException { if ( masterProtocol != null && ! masterProtocol . isClosed ( ) ) { masterProtocol . close ( ) ; } if ( ! currentReadOnlyAsked || isSecondaryHostFail ( ) ) { if ( currentProtocol != null ) { try { syncConnection ( currentProtocol , newMasterProtocol ) ; } catch ( Exception e ) { } } currentProtocol = newMasterProtocol ; } boolean inTransaction = this . masterProtocol != null && this . masterProtocol . inTransaction ( ) ; this . masterProtocol = newMasterProtocol ; resetMasterFailoverData ( ) ; if ( inTransaction ) { throw new ReconnectDuringTransactionException ( "Connection reconnect automatically during an active transaction" , 1401 , "25S03" ) ; } }
Use the parameter newMasterProtocol as new current master connection .
29,639
public void foundActiveSecondary ( Protocol newSecondaryProtocol ) throws SQLException { if ( isSecondaryHostFail ( ) ) { if ( isExplicitClosed ( ) ) { newSecondaryProtocol . close ( ) ; return ; } if ( proxy . lock . tryLock ( ) ) { try { lockAndSwitchSecondary ( newSecondaryProtocol ) ; } finally { proxy . lock . unlock ( ) ; } } else { if ( ! waitNewSecondaryProtocol . compareAndSet ( null , newSecondaryProtocol ) ) { newSecondaryProtocol . close ( ) ; } } } else { newSecondaryProtocol . close ( ) ; } }
Method called when a new secondary connection is found after a fallback .
29,640
public void lockAndSwitchSecondary ( Protocol newSecondaryProtocol ) throws SQLException { if ( secondaryProtocol != null && ! secondaryProtocol . isClosed ( ) ) { secondaryProtocol . close ( ) ; } if ( currentReadOnlyAsked || ( urlParser . getOptions ( ) . failOnReadOnly && ! currentReadOnlyAsked && isMasterHostFail ( ) ) ) { if ( currentProtocol == null ) { try { syncConnection ( currentProtocol , newSecondaryProtocol ) ; } catch ( Exception e ) { } } currentProtocol = newSecondaryProtocol ; } this . secondaryProtocol = newSecondaryProtocol ; if ( urlParser . getOptions ( ) . assureReadOnly ) { setSessionReadOnly ( true , this . secondaryProtocol ) ; } resetSecondaryFailoverData ( ) ; }
Use the parameter newSecondaryProtocol as new current secondary connection .
29,641
public HandleErrorResult primaryFail ( Method method , Object [ ] args , boolean killCmd ) { boolean alreadyClosed = masterProtocol == null || ! masterProtocol . isConnected ( ) ; boolean inTransaction = masterProtocol != null && masterProtocol . inTransaction ( ) ; if ( masterProtocol != null && masterProtocol . isConnected ( ) ) { masterProtocol . close ( ) ; } if ( urlParser . getOptions ( ) . failOnReadOnly && ! isSecondaryHostFail ( ) ) { try { if ( this . secondaryProtocol != null && this . secondaryProtocol . ping ( ) ) { proxy . lock . lock ( ) ; try { if ( masterProtocol != null ) { syncConnection ( masterProtocol , this . secondaryProtocol ) ; } currentProtocol = this . secondaryProtocol ; } finally { proxy . lock . unlock ( ) ; } FailoverLoop . addListener ( this ) ; try { return relaunchOperation ( method , args ) ; } catch ( Exception e ) { } return new HandleErrorResult ( ) ; } } catch ( Exception e ) { if ( setSecondaryHostFail ( ) ) { blackListAndCloseConnection ( this . secondaryProtocol ) ; } } } try { reconnectFailedConnection ( new SearchFilter ( true , urlParser . getOptions ( ) . failOnReadOnly ) ) ; handleFailLoop ( ) ; if ( currentProtocol != null ) { if ( killCmd ) { return new HandleErrorResult ( true , false ) ; } if ( currentReadOnlyAsked || alreadyClosed || ! inTransaction && isQueryRelaunchable ( method , args ) ) { logger . info ( "Connection to master lost, new master {}, conn={} found" + ", query type permit to be re-execute on new server without throwing exception" , currentProtocol . getHostAddress ( ) , currentProtocol . getServerThreadId ( ) ) ; return relaunchOperation ( method , args ) ; } return new HandleErrorResult ( true ) ; } else { setMasterHostFail ( ) ; FailoverLoop . removeListener ( this ) ; return new HandleErrorResult ( ) ; } } catch ( Exception e ) { if ( e . getCause ( ) != null && proxy . hasToHandleFailover ( ( SQLException ) e . getCause ( ) ) && currentProtocol != null && currentProtocol . isConnected ( ) ) { currentProtocol . close ( ) ; } setMasterHostFail ( ) ; FailoverLoop . removeListener ( this ) ; return new HandleErrorResult ( ) ; } }
To handle the newly detected failover on the master connection .
29,642
public void reconnect ( ) throws SQLException { SearchFilter filter ; boolean inTransaction = false ; if ( currentReadOnlyAsked ) { filter = new SearchFilter ( true , true ) ; } else { inTransaction = masterProtocol != null && masterProtocol . inTransaction ( ) ; filter = new SearchFilter ( true , urlParser . getOptions ( ) . failOnReadOnly ) ; } reconnectFailedConnection ( filter ) ; handleFailLoop ( ) ; if ( inTransaction ) { throw new ReconnectDuringTransactionException ( "Connection reconnect automatically during an active transaction" , 1401 , "25S03" ) ; } }
Reconnect failed connection .
29,643
private boolean pingSecondaryProtocol ( Protocol protocol ) { try { if ( protocol != null && protocol . isConnected ( ) && protocol . ping ( ) ) { return true ; } } catch ( Exception e ) { protocol . close ( ) ; if ( setSecondaryHostFail ( ) ) { addToBlacklist ( protocol . getHostAddress ( ) ) ; } } return false ; }
Ping secondary protocol . ! lock must be set !
29,644
public HandleErrorResult secondaryFail ( Method method , Object [ ] args , boolean killCmd ) throws Throwable { proxy . lock . lock ( ) ; try { if ( pingSecondaryProtocol ( this . secondaryProtocol ) ) { return relaunchOperation ( method , args ) ; } } finally { proxy . lock . unlock ( ) ; } if ( ! isMasterHostFail ( ) ) { try { if ( masterProtocol != null && masterProtocol . isValid ( 1000 ) ) { syncConnection ( secondaryProtocol , masterProtocol ) ; proxy . lock . lock ( ) ; try { currentProtocol = masterProtocol ; } finally { proxy . lock . unlock ( ) ; } FailoverLoop . addListener ( this ) ; logger . info ( "Connection to slave lost, using master connection" + ", query is re-execute on master server without throwing exception" ) ; return relaunchOperation ( method , args ) ; } } catch ( Exception e ) { if ( setMasterHostFail ( ) ) { blackListAndCloseConnection ( masterProtocol ) ; } } } try { reconnectFailedConnection ( new SearchFilter ( true , true ) ) ; handleFailLoop ( ) ; if ( isSecondaryHostFail ( ) ) { syncConnection ( this . secondaryProtocol , this . masterProtocol ) ; proxy . lock . lock ( ) ; try { currentProtocol = this . masterProtocol ; } finally { proxy . lock . unlock ( ) ; } } if ( killCmd ) { return new HandleErrorResult ( true , false ) ; } logger . info ( "Connection to slave lost, new slave {}, conn={} found" + ", query is re-execute on new server without throwing exception" , currentProtocol . getHostAddress ( ) , currentProtocol . getServerThreadId ( ) ) ; return relaunchOperation ( method , args ) ; } catch ( Exception ee ) { FailoverLoop . removeListener ( this ) ; return new HandleErrorResult ( ) ; } }
To handle the newly detected failover on the secondary connection .
29,645
public List < HostAddress > connectedHosts ( ) { List < HostAddress > usedHost = new ArrayList < > ( ) ; if ( isMasterHostFail ( ) ) { Protocol masterProtocol = waitNewMasterProtocol . get ( ) ; if ( masterProtocol != null ) { usedHost . add ( masterProtocol . getHostAddress ( ) ) ; } } else { usedHost . add ( masterProtocol . getHostAddress ( ) ) ; } if ( isSecondaryHostFail ( ) ) { Protocol secondProtocol = waitNewSecondaryProtocol . get ( ) ; if ( secondProtocol != null ) { usedHost . add ( secondProtocol . getHostAddress ( ) ) ; } } else { usedHost . add ( secondaryProtocol . getHostAddress ( ) ) ; } return usedHost ; }
List current connected HostAddress .
29,646
public HandleErrorResult handleFailover ( SQLException qe , Method method , Object [ ] args , Protocol protocol ) throws Throwable { if ( isExplicitClosed ( ) ) { throw new SQLException ( "Connection has been closed !" ) ; } boolean killCmd = qe != null && qe . getSQLState ( ) != null && qe . getSQLState ( ) . equals ( "70100" ) && 1927 == qe . getErrorCode ( ) ; if ( protocol != null ) { if ( protocol . mustBeMasterConnection ( ) ) { if ( ! protocol . isMasterConnection ( ) ) { logger . warn ( "SQL Primary node [{}, conn={}] is now in read-only mode. Exception : {}" , this . currentProtocol . getHostAddress ( ) . toString ( ) , this . currentProtocol . getServerThreadId ( ) , qe . getMessage ( ) ) ; } else if ( setMasterHostFail ( ) ) { logger . warn ( "SQL Primary node [{}, conn={}] connection fail. Reason : {}" , this . currentProtocol . getHostAddress ( ) . toString ( ) , this . currentProtocol . getServerThreadId ( ) , qe . getMessage ( ) ) ; addToBlacklist ( protocol . getHostAddress ( ) ) ; } return primaryFail ( method , args , killCmd ) ; } else { if ( setSecondaryHostFail ( ) ) { logger . warn ( "SQL secondary node [{}, conn={}] connection fail. Reason : {}" , this . currentProtocol . getHostAddress ( ) . toString ( ) , this . currentProtocol . getServerThreadId ( ) , qe . getMessage ( ) ) ; addToBlacklist ( protocol . getHostAddress ( ) ) ; } return secondaryFail ( method , args , killCmd ) ; } } else { return primaryFail ( method , args , killCmd ) ; } }
Handle failover on master or slave connection .
29,647
public boolean setSecondaryHostFail ( ) { if ( secondaryHostFail . compareAndSet ( false , true ) ) { secondaryHostFailNanos = System . nanoTime ( ) ; currentConnectionAttempts . set ( 0 ) ; return true ; } return false ; }
Set slave connection lost variables .
29,648
public void remove ( ) { for ( int i = 0 ; i < buf . length ; i ++ ) { buf [ i ] = null ; } buf = null ; }
Clear trace array for easy garbage .
29,649
public PooledConnection getPooledConnection ( String user , String password ) throws SQLException { return new MariaDbPooledConnection ( ( MariaDbConnection ) getConnection ( user , password ) ) ; }
Attempts to establish a physical database connection that can be used as a pooled connection .
29,650
public void initializeConnection ( ) throws SQLException { super . initializeConnection ( ) ; this . currentProtocol = null ; reconnectFailedConnection ( new SearchFilter ( true , false ) ) ; resetMasterFailoverData ( ) ; }
Connect to database .
29,651
public void preExecute ( ) throws SQLException { lastQueryNanos = System . nanoTime ( ) ; if ( this . currentProtocol != null && this . currentProtocol . isClosed ( ) ) { preAutoReconnect ( ) ; } }
Before executing query reconnect if connection is closed and autoReconnect option is set .
29,652
public void reconnectFailedConnection ( SearchFilter searchFilter ) throws SQLException { proxy . lock . lock ( ) ; try { if ( ! searchFilter . isInitialConnection ( ) && ( isExplicitClosed ( ) || ! isMasterHostFail ( ) ) ) { return ; } currentConnectionAttempts . incrementAndGet ( ) ; resetOldsBlackListHosts ( ) ; List < HostAddress > loopAddress = new LinkedList < > ( urlParser . getHostAddresses ( ) ) ; if ( HaMode . FAILOVER . equals ( mode ) ) { loopAddress . removeAll ( getBlacklistKeys ( ) ) ; Collections . shuffle ( loopAddress ) ; List < HostAddress > blacklistShuffle = new LinkedList < > ( getBlacklistKeys ( ) ) ; blacklistShuffle . retainAll ( urlParser . getHostAddresses ( ) ) ; Collections . shuffle ( blacklistShuffle ) ; loopAddress . addAll ( blacklistShuffle ) ; } else { loopAddress . removeAll ( getBlacklistKeys ( ) ) ; loopAddress . addAll ( getBlacklistKeys ( ) ) ; loopAddress . retainAll ( urlParser . getHostAddresses ( ) ) ; } if ( currentProtocol != null && ! isMasterHostFail ( ) ) { loopAddress . remove ( currentProtocol . getHostAddress ( ) ) ; } MasterProtocol . loop ( this , globalInfo , loopAddress , searchFilter ) ; if ( ! isMasterHostFail ( ) ) { FailoverLoop . removeListener ( this ) ; } resetMasterFailoverData ( ) ; } finally { proxy . lock . unlock ( ) ; } }
Loop to connect failed hosts .
29,653
public void switchReadOnlyConnection ( Boolean mustBeReadOnly ) throws SQLException { if ( urlParser . getOptions ( ) . assureReadOnly && currentReadOnlyAsked != mustBeReadOnly ) { proxy . lock . lock ( ) ; try { if ( currentReadOnlyAsked != mustBeReadOnly ) { currentReadOnlyAsked = mustBeReadOnly ; setSessionReadOnly ( mustBeReadOnly , currentProtocol ) ; } } finally { proxy . lock . unlock ( ) ; } } }
Force session to read - only according to options .
29,654
public void foundActiveMaster ( Protocol protocol ) throws SQLException { if ( isExplicitClosed ( ) ) { proxy . lock . lock ( ) ; try { protocol . close ( ) ; } finally { proxy . lock . unlock ( ) ; } return ; } syncConnection ( this . currentProtocol , protocol ) ; proxy . lock . lock ( ) ; try { if ( currentProtocol != null && ! currentProtocol . isClosed ( ) ) { currentProtocol . close ( ) ; } currentProtocol = protocol ; } finally { proxy . lock . unlock ( ) ; } resetMasterFailoverData ( ) ; FailoverLoop . removeListener ( this ) ; }
method called when a new Master connection is found after a fallback .
29,655
public void reconnect ( ) throws SQLException { boolean inTransaction = currentProtocol != null && currentProtocol . inTransaction ( ) ; reconnectFailedConnection ( new SearchFilter ( true , false ) ) ; handleFailLoop ( ) ; if ( inTransaction ) { throw new ReconnectDuringTransactionException ( "Connection reconnect automatically during an active transaction" , 1401 , "25S03" ) ; } }
Try to reconnect connection .
29,656
public void authenticate ( final PacketOutputStream out , final PacketInputStream in , final AtomicInteger sequence , final String servicePrincipalName , String mechanisms ) throws SQLException , IOException { if ( "" . equals ( servicePrincipalName ) ) { throw new SQLException ( "No principal name defined on server. " + "Please set server variable \"gssapi-principal-name\" or set option \"servicePrincipalName\"" , "28000" ) ; } if ( System . getProperty ( "java.security.auth.login.config" ) == null ) { final File jaasConfFile ; try { jaasConfFile = File . createTempFile ( "jaas.conf" , null ) ; try ( PrintStream bos = new PrintStream ( new FileOutputStream ( jaasConfFile ) ) ) { bos . print ( "Krb5ConnectorContext {\n" + "com.sun.security.auth.module.Krb5LoginModule required " + "useTicketCache=true " + "debug=true " + "renewTGT=true " + "doNotPrompt=true; };" ) ; } jaasConfFile . deleteOnExit ( ) ; } catch ( final IOException ex ) { throw new UncheckedIOException ( ex ) ; } System . setProperty ( "java.security.auth.login.config" , jaasConfFile . getCanonicalPath ( ) ) ; } try { LoginContext loginContext = new LoginContext ( "Krb5ConnectorContext" ) ; loginContext . login ( ) ; final Subject mySubject = loginContext . getSubject ( ) ; if ( ! mySubject . getPrincipals ( ) . isEmpty ( ) ) { try { PrivilegedExceptionAction < Void > action = ( ) -> { try { Oid krb5Mechanism = new Oid ( "1.2.840.113554.1.2.2" ) ; GSSManager manager = GSSManager . getInstance ( ) ; GSSName peerName = manager . createName ( servicePrincipalName , GSSName . NT_USER_NAME ) ; GSSContext context = manager . createContext ( peerName , krb5Mechanism , null , GSSContext . DEFAULT_LIFETIME ) ; context . requestMutualAuth ( true ) ; byte [ ] inToken = new byte [ 0 ] ; byte [ ] outToken ; while ( ! context . isEstablished ( ) ) { outToken = context . initSecContext ( inToken , 0 , inToken . length ) ; if ( outToken != null ) { out . startPacket ( sequence . incrementAndGet ( ) ) ; out . write ( outToken ) ; out . flush ( ) ; } if ( ! context . isEstablished ( ) ) { Buffer buffer = in . getPacket ( true ) ; sequence . set ( in . getLastPacketSeq ( ) ) ; inToken = buffer . readRawBytes ( buffer . remaining ( ) ) ; } } } catch ( GSSException le ) { throw new SQLException ( "GSS-API authentication exception" , "28000" , 1045 , le ) ; } return null ; } ; Subject . doAs ( mySubject , action ) ; } catch ( PrivilegedActionException exception ) { throw new SQLException ( "GSS-API authentication exception" , "28000" , 1045 , exception ) ; } } else { throw new SQLException ( "GSS-API authentication exception : no credential cache not found." , "28000" , 1045 ) ; } } catch ( LoginException le ) { throw new SQLException ( "GSS-API authentication exception" , "28000" , 1045 , le ) ; } }
Process default GSS plugin authentication .
29,657
public static void send ( final PacketOutputStream pos , final String username , final String password , final HostAddress currentHost , final String database , final long clientCapabilities , final long serverCapabilities , final byte serverLanguage , final byte packetSeq , final Options options , final ReadInitialHandShakePacket greetingPacket ) throws IOException { pos . startPacket ( packetSeq ) ; final byte [ ] authData ; switch ( greetingPacket . getPluginName ( ) ) { case "" : case DefaultAuthenticationProvider . MYSQL_NATIVE_PASSWORD : pos . permitTrace ( false ) ; try { authData = Utils . encryptPassword ( password , greetingPacket . getSeed ( ) , options . passwordCharacterEncoding ) ; break ; } catch ( NoSuchAlgorithmException e ) { throw new IOException ( "Unknown algorithm SHA-1. Cannot encrypt password" , e ) ; } case DefaultAuthenticationProvider . MYSQL_CLEAR_PASSWORD : pos . permitTrace ( false ) ; if ( options . passwordCharacterEncoding != null && ! options . passwordCharacterEncoding . isEmpty ( ) ) { authData = password . getBytes ( options . passwordCharacterEncoding ) ; } else { authData = password . getBytes ( ) ; } break ; default : authData = new byte [ 0 ] ; } pos . writeInt ( ( int ) clientCapabilities ) ; pos . writeInt ( 1024 * 1024 * 1024 ) ; pos . write ( serverLanguage ) ; pos . writeBytes ( ( byte ) 0 , 19 ) ; pos . writeInt ( ( int ) ( clientCapabilities >> 32 ) ) ; if ( username == null || username . isEmpty ( ) ) { pos . write ( System . getProperty ( "user.name" ) . getBytes ( ) ) ; } else { pos . write ( username . getBytes ( ) ) ; } pos . write ( ( byte ) 0 ) ; if ( ( serverCapabilities & MariaDbServerCapabilities . PLUGIN_AUTH_LENENC_CLIENT_DATA ) != 0 ) { pos . writeFieldLength ( authData . length ) ; pos . write ( authData ) ; } else if ( ( serverCapabilities & MariaDbServerCapabilities . SECURE_CONNECTION ) != 0 ) { pos . write ( ( byte ) authData . length ) ; pos . write ( authData ) ; } else { pos . write ( authData ) ; pos . write ( ( byte ) 0 ) ; } if ( ( serverCapabilities & MariaDbServerCapabilities . CONNECT_WITH_DB ) != 0 ) { pos . write ( database ) ; pos . write ( ( byte ) 0 ) ; } if ( ( serverCapabilities & MariaDbServerCapabilities . PLUGIN_AUTH ) != 0 ) { pos . write ( greetingPacket . getPluginName ( ) ) ; pos . write ( ( byte ) 0 ) ; } if ( ( serverCapabilities & MariaDbServerCapabilities . CONNECT_ATTRS ) != 0 ) { writeConnectAttributes ( pos , options . connectionAttributes , currentHost ) ; } pos . flush ( ) ; pos . permitTrace ( true ) ; }
Send handshake response packet .
29,658
public static List < HostAddress > parse ( String spec , HaMode haMode ) { if ( spec == null ) { throw new IllegalArgumentException ( "Invalid connection URL, host address must not be empty " ) ; } if ( "" . equals ( spec ) ) { return new ArrayList < > ( 0 ) ; } String [ ] tokens = spec . trim ( ) . split ( "," ) ; int size = tokens . length ; List < HostAddress > arr = new ArrayList < > ( size ) ; if ( haMode == HaMode . AURORA ) { Pattern clusterPattern = Pattern . compile ( "(.+)\\.cluster-([a-z0-9]+\\.[a-z0-9\\-]+\\.rds\\.amazonaws\\.com)" , Pattern . CASE_INSENSITIVE ) ; Matcher matcher = clusterPattern . matcher ( spec ) ; if ( ! matcher . find ( ) ) { logger . warn ( "Aurora recommended connection URL must only use cluster end-point like " + "\"jdbc:mariadb:aurora://xx.cluster-yy.zz.rds.amazonaws.com\". " + "Using end-point permit auto-discovery of new replicas" ) ; } } for ( String token : tokens ) { if ( token . startsWith ( "address=" ) ) { arr . add ( parseParameterHostAddress ( token ) ) ; } else { arr . add ( parseSimpleHostAddress ( token ) ) ; } } if ( haMode == HaMode . REPLICATION ) { for ( int i = 0 ; i < size ; i ++ ) { if ( i == 0 && arr . get ( i ) . type == null ) { arr . get ( i ) . type = ParameterConstant . TYPE_MASTER ; } else if ( i != 0 && arr . get ( i ) . type == null ) { arr . get ( i ) . type = ParameterConstant . TYPE_SLAVE ; } } } return arr ; }
parse - parse server addresses from the URL fragment .
29,659
public void writeTo ( final PacketOutputStream os ) throws IOException { os . write ( QUOTE ) ; os . write ( dateByteFormat ( ) ) ; os . write ( QUOTE ) ; }
Write to server OutputStream in text protocol .
29,660
public ServerPrepareResult read ( PacketInputStream reader , boolean eofDeprecated ) throws IOException , SQLException { Buffer buffer = reader . getPacket ( true ) ; byte firstByte = buffer . getByteAt ( buffer . position ) ; if ( firstByte == ERROR ) { throw buildErrorException ( buffer ) ; } if ( firstByte == OK ) { buffer . readByte ( ) ; final int statementId = buffer . readInt ( ) ; final int numColumns = buffer . readShort ( ) & 0xffff ; final int numParams = buffer . readShort ( ) & 0xffff ; ColumnInformation [ ] params = new ColumnInformation [ numParams ] ; ColumnInformation [ ] columns = new ColumnInformation [ numColumns ] ; if ( numParams > 0 ) { for ( int i = 0 ; i < numParams ; i ++ ) { params [ i ] = new ColumnInformation ( reader . getPacket ( false ) ) ; } if ( numColumns > 0 ) { if ( ! eofDeprecated ) { protocol . skipEofPacket ( ) ; } for ( int i = 0 ; i < numColumns ; i ++ ) { columns [ i ] = new ColumnInformation ( reader . getPacket ( false ) ) ; } } if ( ! eofDeprecated ) { protocol . readEofPacket ( ) ; } } else { if ( numColumns > 0 ) { for ( int i = 0 ; i < numColumns ; i ++ ) { columns [ i ] = new ColumnInformation ( reader . getPacket ( false ) ) ; } if ( ! eofDeprecated ) { protocol . readEofPacket ( ) ; } } else { buffer . readByte ( ) ; protocol . setHasWarnings ( buffer . readShort ( ) > 0 ) ; } } ServerPrepareResult serverPrepareResult = new ServerPrepareResult ( sql , statementId , columns , params , protocol ) ; if ( protocol . getOptions ( ) . cachePrepStmts && protocol . getOptions ( ) . useServerPrepStmts && sql != null && sql . length ( ) < protocol . getOptions ( ) . prepStmtCacheSqlLimit ) { String key = protocol . getDatabase ( ) + "-" + sql ; ServerPrepareResult cachedServerPrepareResult = protocol . addPrepareInCache ( key , serverPrepareResult ) ; return cachedServerPrepareResult != null ? cachedServerPrepareResult : serverPrepareResult ; } return serverPrepareResult ; } else { throw new SQLException ( "Unexpected packet returned by server, first byte " + firstByte ) ; } }
Read COM_PREPARE_RESULT .
29,661
private static void resetHostList ( MastersSlavesListener listener , Deque < HostAddress > loopAddresses ) { List < HostAddress > servers = new ArrayList < > ( ) ; servers . addAll ( listener . getUrlParser ( ) . getHostAddresses ( ) ) ; Collections . shuffle ( servers ) ; servers . removeAll ( listener . connectedHosts ( ) ) ; loopAddresses . clear ( ) ; loopAddresses . addAll ( servers ) ; }
Reinitialize loopAddresses with all servers in randomize order .
29,662
public void fireStatementClosed ( Statement st ) { if ( st instanceof PreparedStatement ) { StatementEvent event = new StatementEvent ( this , ( PreparedStatement ) st ) ; for ( StatementEventListener listener : statementEventListeners ) { listener . statementClosed ( event ) ; } } }
Fire statement close event to listeners .
29,663
public void fireStatementErrorOccured ( Statement st , SQLException ex ) { if ( st instanceof PreparedStatement ) { StatementEvent event = new StatementEvent ( this , ( PreparedStatement ) st , ex ) ; for ( StatementEventListener listener : statementEventListeners ) { listener . statementErrorOccurred ( event ) ; } } }
Fire statement error to listeners .
29,664
public void fireConnectionClosed ( ) { ConnectionEvent event = new ConnectionEvent ( this ) ; for ( ConnectionEventListener listener : connectionEventListeners ) { listener . connectionClosed ( event ) ; } }
Fire Connection close to listening listeners .
29,665
public void fireConnectionErrorOccured ( SQLException ex ) { ConnectionEvent event = new ConnectionEvent ( this , ex ) ; for ( ConnectionEventListener listener : connectionEventListeners ) { listener . connectionErrorOccurred ( event ) ; } }
Fire connection error to listening listeners .
29,666
protected void setTimerTask ( boolean isBatch ) { assert ( timerTaskFuture == null ) ; timerTaskFuture = timeoutScheduler . schedule ( ( ) -> { try { isTimedout = true ; if ( ! isBatch ) { protocol . cancelCurrentQuery ( ) ; } protocol . interrupt ( ) ; } catch ( Throwable e ) { } } , queryTimeout , TimeUnit . SECONDS ) ; }
Part of query prolog - setup timeout timer
29,667
protected SQLException executeExceptionEpilogue ( SQLException sqle ) { if ( sqle . getSQLState ( ) != null && sqle . getSQLState ( ) . startsWith ( "08" ) ) { try { close ( ) ; } catch ( SQLException sqlee ) { } } if ( isTimedout ) { return new SQLTimeoutException ( "(conn:" + getServerThreadId ( ) + ") Query timed out" , "JZ0002" , 1317 , sqle ) ; } SQLException sqlException = ExceptionMapper . getException ( sqle , connection , this , queryTimeout != 0 ) ; logger . error ( "error executing query" , sqlException ) ; return sqlException ; }
Reset timeout after query re - throw SQL exception .
29,668
public long executeLargeUpdate ( String sql ) throws SQLException { if ( executeInternal ( sql , fetchSize , Statement . NO_GENERATED_KEYS ) ) { return 0 ; } return getLargeUpdateCount ( ) ; }
Executes the given SQL statement which may be an INSERT UPDATE or DELETE statement or an SQL statement that returns nothing such as an SQL DDL statement . This method should be used when the returned row count may exceed Integer . MAX_VALUE .
29,669
public int getUpdateCount ( ) { if ( results != null && results . getCmdInformation ( ) != null && ! results . isBatch ( ) ) { return results . getCmdInformation ( ) . getUpdateCount ( ) ; } return - 1 ; }
Retrieves the current result as an update count ; if the result is a ResultSet object or there are no more results - 1 is returned . This method should be called only once per result .
29,670
public long getLargeUpdateCount ( ) { if ( results != null && results . getCmdInformation ( ) != null && ! results . isBatch ( ) ) { return results . getCmdInformation ( ) . getLargeUpdateCount ( ) ; } return - 1 ; }
Retrieves the current result as an update count ; if the result is a ResultSet object or there are no more results - 1 is returned .
29,671
private void internalBatchExecution ( int size ) throws SQLException { executeQueryPrologue ( true ) ; results = new Results ( this , 0 , true , size , false , resultSetScrollType , resultSetConcurrency , Statement . RETURN_GENERATED_KEYS , protocol . getAutoIncrementIncrement ( ) ) ; protocol . executeBatchStmt ( protocol . isMasterConnection ( ) , results , batchQueries ) ; results . commandEnd ( ) ; }
Internal batch execution .
29,672
public void checkCloseOnCompletion ( ResultSet resultSet ) throws SQLException { if ( mustCloseOnCompletion && ! closed && results != null && resultSet . equals ( results . getResultSet ( ) ) ) { close ( ) ; } }
Check that close on completion is asked and close if so .
29,673
public void initFunctionData ( int parametersCount ) { params = new CallParameter [ parametersCount ] ; for ( int i = 0 ; i < parametersCount ; i ++ ) { params [ i ] = new CallParameter ( ) ; if ( i > 0 ) { params [ i ] . setInput ( true ) ; } } params [ 0 ] . setOutput ( true ) ; }
Data initialisation when parameterCount is defined .
29,674
private void executeQueryPrologue ( ServerPrepareResult serverPrepareResult ) throws SQLException { executing = true ; if ( closed ) { throw new SQLException ( "execute() is called on closed statement" ) ; } protocol . prologProxy ( serverPrepareResult , maxRows , protocol . getProxy ( ) != null , connection , this ) ; }
must have lock locked before invoking
29,675
public static void printButtons ( int buttonNumber ) { boolean buttonPressed = false ; System . out . print ( "Button Pressed: " ) ; for ( int i = 0 ; i < 7 ; i ++ ) { if ( ( buttonNumber & ( 1 << i ) ) != 0 ) { System . out . println ( i + " " ) ; buttonPressed = true ; } } if ( ! buttonPressed ) { System . out . println ( "None " ) ; } }
This function prints out the button numbers from 0 through 6
29,676
public static void transaction ( Runnable action , boolean readOnly ) { Ctx ctx = Ctxs . get ( ) ; boolean newContext = ctx == null ; if ( newContext ) { ctx = Ctxs . open ( "transaction" ) ; } try { EntityManager em = ctx . persister ( ) ; JPA . with ( em ) . transactional ( action , readOnly ) ; } finally { if ( newContext ) { Ctxs . close ( ) ; } } }
FIXME replace Runnable with Executable
29,677
public static synchronized void run ( String [ ] args , String ... extraArgs ) { AppStarter . startUp ( args , extraArgs ) ; boot ( ) ; onAppReady ( ) ; boot ( ) ; }
Initializes the app in non - atomic way . Then starts serving requests immediately when routes are configured .
29,678
public static synchronized void bootstrap ( String [ ] args , String ... extraArgs ) { AppStarter . startUp ( args , extraArgs ) ; boot ( ) ; App . scan ( ) ; onAppReady ( ) ; boot ( ) ; }
Initializes the app in non - atomic way . Then scans the classpath for beans . Then starts serving requests immediately when routes are configured .
29,679
private V setValueInsideWriteLock ( V newValue ) { CachedValue < V > cached = cachedValue ; V oldValue = cached != null ? cached . value : null ; if ( newValue != null ) { long expiresAt = ttlInMs > 0 ? U . time ( ) + ttlInMs : Long . MAX_VALUE ; cachedValue = new CachedValue < > ( newValue , expiresAt ) ; } else { cachedValue = null ; } return oldValue ; }
Sets new cached value executes inside already acquired write lock .
29,680
public static Factory newInstance ( ) { ScheduledExecutorService scheduler = newSingleThreadScheduledExecutor ( new ThreadFactory ( ) { public Thread newThread ( Runnable r ) { Thread result = new Thread ( r ) ; result . setDaemon ( true ) ; return result ; } } ) ; Properties props = new Properties ( ) ; return new DefaultFactory ( scheduler , props ) ; }
Returns a new instance of a config Factory object .
29,681
@ SuppressWarnings ( "unchecked" ) public static < T extends Config > T remove ( Object key ) { return ( T ) CACHE . remove ( key ) ; }
Removes the cached instance for the given key if it is present .
29,682
public void parse ( Class clazz , PrintWriter output , String headerName , String projectName ) throws Exception { long startTime = System . currentTimeMillis ( ) ; Group [ ] groups = parseMethods ( clazz ) ; long finishTime = System . currentTimeMillis ( ) ; lastExecutionTime = finishTime - startTime ; String result = toPropertiesString ( groups , headerName , projectName ) ; writeProperties ( output , result ) ; }
Method to parse the class and write file in the choosen output .
29,683
private Group [ ] parseMethods ( Class clazz ) { List < Group > groups = new ArrayList ( ) ; Group unknownGroup = new Group ( ) ; groups . add ( unknownGroup ) ; String [ ] groupsOrder = new String [ 0 ] ; for ( Method method : clazz . getMethods ( ) ) { Property prop = new Property ( ) ; prop . deprecated = method . isAnnotationPresent ( Deprecated . class ) ; if ( method . isAnnotationPresent ( Key . class ) ) { Key val = method . getAnnotation ( Key . class ) ; prop . name = val . value ( ) ; } else { prop . name = method . getName ( ) ; } if ( method . isAnnotationPresent ( DefaultValue . class ) ) { DefaultValue val = method . getAnnotation ( DefaultValue . class ) ; prop . defaultValue = val . value ( ) ; } unknownGroup . properties . add ( prop ) ; } return orderGroup ( groups , groupsOrder ) ; }
Method to get group array with subgroups and properties .
29,684
private Group [ ] orderGroup ( List < Group > groups , String [ ] groupsOrder ) { LinkedList < Group > groupsOrdered = new LinkedList ( ) ; List < Group > remained = new ArrayList ( groups ) ; for ( String order : groupsOrder ) { for ( Group remain : remained ) { if ( remain . title . equals ( order ) ) { groupsOrdered . add ( remain ) ; remained . remove ( remain ) ; break ; } } } groupsOrdered . addAll ( remained ) ; return groupsOrdered . toArray ( new Group [ groupsOrdered . size ( ) ] ) ; }
Order groups based on passed order .
29,685
private String toPropertiesString ( Group [ ] groups , String headerName , String projectName ) { StringBuilder result = new StringBuilder ( ) ; result . append ( format ( header , headerName , projectName ) ) ; for ( Group group : groups ) { result . append ( group . toString ( ) ) ; } result . append ( generateFileFooter ( ) ) ; return result . toString ( ) ; }
Convert groups list into string .
29,686
public BigInteger getBytes ( ) { return value . multiply ( unit . getFactor ( ) ) . setScale ( 0 , RoundingMode . CEILING ) . toBigIntegerExact ( ) ; }
Returns the number of bytes that this byte size represents after multiplying the unit factor with the value .
29,687
String replace ( String source ) { if ( source == null ) return null ; Matcher m = PATTERN . matcher ( source ) ; StringBuffer sb = new StringBuffer ( ) ; while ( m . find ( ) ) { String var = m . group ( 1 ) ; String value = values . getProperty ( var ) ; String replacement = ( value != null ) ? replace ( value ) : "" ; m . appendReplacement ( sb , Matcher . quoteReplacement ( replacement ) ) ; } m . appendTail ( sb ) ; return sb . toString ( ) ; }
Replaces all the occurrences of variables with their matching values from the resolver using the given source string as a template .
29,688
public List < JApiClass > compare ( JApiCmpArchive oldArchive , JApiCmpArchive newArchive ) { return compare ( Collections . singletonList ( oldArchive ) , Collections . singletonList ( newArchive ) ) ; }
Compares the two given archives .
29,689
public List < JApiClass > compare ( List < JApiCmpArchive > oldArchives , List < JApiCmpArchive > newArchives ) { return createAndCompareClassLists ( toFileList ( oldArchives ) , toFileList ( newArchives ) ) ; }
Compares the two given lists of archives .
29,690
List < JApiClass > compareClassLists ( JarArchiveComparatorOptions options , List < CtClass > oldClasses , List < CtClass > newClasses ) { List < CtClass > oldClassesFiltered = applyFilter ( options , oldClasses ) ; List < CtClass > newClassesFiltered = applyFilter ( options , newClasses ) ; ClassesComparator classesComparator = new ClassesComparator ( this , options ) ; classesComparator . compare ( oldClassesFiltered , newClassesFiltered ) ; List < JApiClass > classList = classesComparator . getClasses ( ) ; if ( LOGGER . isLoggable ( Level . FINE ) ) { for ( JApiClass jApiClass : classList ) { LOGGER . fine ( jApiClass . toString ( ) ) ; } } checkBinaryCompatibility ( classList ) ; checkJavaObjectSerializationCompatibility ( classList ) ; OutputFilter . sortClassesAndMethods ( classList ) ; return classList ; }
Compares the two lists with CtClass objects using the provided options instance .
29,691
public Optional < CtClass > loadClass ( ArchiveType archiveType , String name ) { Optional < CtClass > loadedClass = Optional . absent ( ) ; if ( this . options . getClassPathMode ( ) == JarArchiveComparatorOptions . ClassPathMode . ONE_COMMON_CLASSPATH ) { try { loadedClass = Optional . of ( commonClassPool . get ( name ) ) ; } catch ( NotFoundException e ) { if ( ! options . getIgnoreMissingClasses ( ) . ignoreClass ( e . getMessage ( ) ) ) { throw JApiCmpException . forClassLoading ( e , name , this ) ; } } } else if ( this . options . getClassPathMode ( ) == JarArchiveComparatorOptions . ClassPathMode . TWO_SEPARATE_CLASSPATHS ) { if ( archiveType == ArchiveType . OLD ) { try { loadedClass = Optional . of ( oldClassPool . get ( name ) ) ; } catch ( NotFoundException e ) { if ( ! options . getIgnoreMissingClasses ( ) . ignoreClass ( e . getMessage ( ) ) ) { throw JApiCmpException . forClassLoading ( e , name , this ) ; } } } else if ( archiveType == ArchiveType . NEW ) { try { loadedClass = Optional . of ( newClassPool . get ( name ) ) ; } catch ( NotFoundException e ) { if ( ! options . getIgnoreMissingClasses ( ) . ignoreClass ( e . getMessage ( ) ) ) { throw JApiCmpException . forClassLoading ( e , name , this ) ; } } } else { throw new JApiCmpException ( Reason . IllegalState , "Unknown archive type: " + archiveType ) ; } } else { throw new JApiCmpException ( Reason . IllegalState , "Unknown classpath mode: " + this . options . getClassPathMode ( ) ) ; } return loadedClass ; }
Loads a class either from the old new or common classpath .
29,692
private boolean isImplemented ( JApiMethod jApiMethod ) { JApiClass aClass = jApiMethod . getjApiClass ( ) ; while ( aClass != null ) { for ( JApiMethod method : aClass . getMethods ( ) ) { if ( jApiMethod . getName ( ) . equals ( method . getName ( ) ) && jApiMethod . hasSameParameter ( method ) && ! isAbstract ( method ) && method . getChangeStatus ( ) != JApiChangeStatus . REMOVED && isNotPrivate ( method ) ) { return true ; } } if ( aClass . getSuperclass ( ) != null && aClass . getSuperclass ( ) . getJApiClass ( ) . isPresent ( ) ) { aClass = aClass . getSuperclass ( ) . getJApiClass ( ) . get ( ) ; } else { aClass = null ; } } return false ; }
Is a method implemented in a super class
29,693
private void emitLoop ( ) { for ( ; ; ) { AppendOnlyLinkedArrayList < T > q ; synchronized ( this ) { q = queue ; if ( q == null ) { emitting = false ; return ; } queue = null ; } q . accept ( actual ) ; } }
Loops until all notifications in the queue has been processed .
29,694
public int geneCount ( ) { int count = 0 ; for ( int i = 0 , n = _chromosomes . length ( ) ; i < n ; ++ i ) { count += _chromosomes . get ( i ) . length ( ) ; } return count ; }
Return the number of genes this genotype consists of . This is the sum of the number of genes of the genotype chromosomes .
29,695
public void accept ( final C object ) { _min = min ( _comparator , _min , object ) ; _max = max ( _comparator , _max , object ) ; ++ _count ; }
Accept the element for min - max calculation .
29,696
public int [ ] toArray ( final int [ ] array ) { final int [ ] a = array . length >= length ( ) ? array : new int [ length ( ) ] ; for ( int i = length ( ) ; -- i >= 0 ; ) { a [ i ] = intValue ( i ) ; } return a ; }
Returns an int array containing all of the elements in this chromosome in proper sequence . If the chromosome fits in the specified array it is returned therein . Otherwise a new array is allocated with the length of this chromosome .
29,697
public DoubleAdder add ( final double [ ] values ) { for ( int i = values . length ; -- i >= 0 ; ) { add ( values [ i ] ) ; } return this ; }
Add the given values to this adder .
29,698
public void draw ( final Graphics2D g , final int width , final int height ) { g . setColor ( new Color ( _data [ 0 ] , _data [ 1 ] , _data [ 2 ] , _data [ 3 ] ) ) ; final GeneralPath path = new GeneralPath ( ) ; path . moveTo ( _data [ 4 ] * width , _data [ 5 ] * height ) ; for ( int j = 1 ; j < _length ; ++ j ) { path . lineTo ( _data [ 4 + j * 2 ] * width , _data [ 5 + j * 2 ] * height ) ; } path . closePath ( ) ; g . fill ( path ) ; }
Draw the Polygon to the buffer of the given size .
29,699
public static Polygon newRandom ( final int length , final Random random ) { require . positive ( length ) ; final Polygon p = new Polygon ( length ) ; p . _data [ 0 ] = random . nextFloat ( ) ; p . _data [ 1 ] = random . nextFloat ( ) ; p . _data [ 2 ] = random . nextFloat ( ) ; p . _data [ 3 ] = max ( 0.2F , random . nextFloat ( ) * random . nextFloat ( ) ) ; float px = 0.5F ; float py = 0.5F ; for ( int k = 0 ; k < length ; k ++ ) { p . _data [ 4 + 2 * k ] = px = clamp ( px + random . nextFloat ( ) - 0.5F ) ; p . _data [ 5 + 2 * k ] = py = clamp ( py + random . nextFloat ( ) - 0.5F ) ; } return p ; }
Creates a new random Polygon of the given length .