idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
29,500 | public String getSubString ( long pos , int length ) throws SQLException { if ( pos < 1 ) { throw ExceptionMapper . getSqlException ( "position must be >= 1" ) ; } if ( length < 0 ) { throw ExceptionMapper . getSqlException ( "length must be > 0" ) ; } try { String val = toString ( ) ; return val . substring ( ( int ) pos - 1 , Math . min ( ( int ) pos - 1 + length , val . length ( ) ) ) ; } catch ( Exception e ) { throw new SQLException ( e ) ; } } | Get sub string . |
29,501 | public Reader getCharacterStream ( long pos , long length ) throws SQLException { String val = toString ( ) ; if ( val . length ( ) < ( int ) pos - 1 + length ) { throw ExceptionMapper . getSqlException ( "pos + length is greater than the number of characters in the Clob" ) ; } String sub = val . substring ( ( int ) pos - 1 , ( int ) pos - 1 + ( int ) length ) ; return new StringReader ( sub ) ; } | Returns a Reader object that contains a partial Clob value starting with the character specified by pos which is length characters in length . |
29,502 | public Writer setCharacterStream ( long pos ) throws SQLException { int bytePosition = utf8Position ( ( int ) pos - 1 ) ; OutputStream stream = setBinaryStream ( bytePosition + 1 ) ; return new OutputStreamWriter ( stream , StandardCharsets . UTF_8 ) ; } | Set character stream . |
29,503 | private int utf8Position ( int charPosition ) { int pos = offset ; for ( int i = 0 ; i < charPosition ; i ++ ) { int byteValue = data [ pos ] & 0xff ; if ( byteValue < 0x80 ) { pos += 1 ; } else if ( byteValue < 0xC2 ) { throw new UncheckedIOException ( "invalid UTF8" , new CharacterCodingException ( ) ) ; } else if ( byteValue < 0xE0 ) { pos += 2 ; } else if ( byteValue < 0xF0 ) { pos += 3 ; } else if ( byteValue < 0xF8 ) { pos += 4 ; } else { throw new UncheckedIOException ( "invalid UTF8" , new CharacterCodingException ( ) ) ; } } return pos ; } | Convert character position into byte position in UTF8 byte array . |
29,504 | public int setString ( long pos , String str ) throws SQLException { int bytePosition = utf8Position ( ( int ) pos - 1 ) ; super . setBytes ( bytePosition + 1 - offset , str . getBytes ( StandardCharsets . UTF_8 ) ) ; return str . length ( ) ; } | Set String . |
29,505 | public long length ( ) { long len = 0 ; int pos = offset ; for ( ; len < length && data [ pos ] >= 0 ; ) { len ++ ; pos ++ ; } while ( pos < offset + length ) { byte firstByte = data [ pos ++ ] ; if ( firstByte < 0 ) { if ( firstByte >> 5 != - 2 || ( firstByte & 30 ) == 0 ) { if ( firstByte >> 4 == - 2 ) { if ( pos + 1 < offset + length ) { pos += 2 ; len ++ ; } else { throw new UncheckedIOException ( "invalid UTF8" , new CharacterCodingException ( ) ) ; } } else if ( firstByte >> 3 != - 2 ) { throw new UncheckedIOException ( "invalid UTF8" , new CharacterCodingException ( ) ) ; } else if ( pos + 2 < offset + length ) { pos += 3 ; len += 2 ; } else { pos += offset + length ; len += 1 ; } } else { pos ++ ; len ++ ; } } else { len ++ ; } } return len ; } | Return character length of the Clob . Assume UTF8 encoding . |
29,506 | private ArrayList < String > searchAccurateAliases ( String [ ] keyTypes , Principal [ ] issuers ) { if ( keyTypes == null || keyTypes . length == 0 ) { return null ; } ArrayList < String > accurateAliases = new ArrayList < > ( ) ; for ( Map . Entry < String , KeyStore . PrivateKeyEntry > mapEntry : privateKeyHash . entrySet ( ) ) { Certificate [ ] certs = mapEntry . getValue ( ) . getCertificateChain ( ) ; String alg = certs [ 0 ] . getPublicKey ( ) . getAlgorithm ( ) ; for ( String keyType : keyTypes ) { if ( alg . equals ( keyType ) ) { if ( issuers != null && issuers . length != 0 ) { checkLoop : for ( Certificate cert : certs ) { if ( cert instanceof X509Certificate ) { X500Principal certificateIssuer = ( ( X509Certificate ) cert ) . getIssuerX500Principal ( ) ; for ( Principal issuer : issuers ) { if ( certificateIssuer . equals ( issuer ) ) { accurateAliases . add ( mapEntry . getKey ( ) ) ; break checkLoop ; } } } } } else { accurateAliases . add ( mapEntry . getKey ( ) ) ; } } } } return accurateAliases ; } | Search aliases corresponding to algorithms and issuers . |
29,507 | @ SuppressWarnings ( "unchecked" ) public static SocketHandlerFunction getSocketHandler ( ) { try { Platform . getOSType ( ) ; return ( urlParser , host ) -> { if ( urlParser . getOptions ( ) . pipe != null ) { return new NamedPipeSocket ( host , urlParser . getOptions ( ) . pipe ) ; } else if ( urlParser . getOptions ( ) . localSocket != null ) { try { return new UnixDomainSocket ( urlParser . getOptions ( ) . localSocket ) ; } catch ( RuntimeException re ) { throw new IOException ( re . getMessage ( ) , re . getCause ( ) ) ; } } else if ( urlParser . getOptions ( ) . sharedMemory != null ) { try { return new SharedMemorySocket ( urlParser . getOptions ( ) . sharedMemory ) ; } catch ( RuntimeException re ) { throw new IOException ( re . getMessage ( ) , re . getCause ( ) ) ; } } else { return Utils . standardSocket ( urlParser , host ) ; } } ; } catch ( Throwable cle ) { } return ( urlParser , host ) -> Utils . standardSocket ( urlParser , host ) ; } | Create socket according to options . In case of compilation ahead of time will throw an error if dependencies found then use default socket implementation . |
29,508 | public void blockTillTerminated ( ) { while ( ! runState . compareAndSet ( State . IDLE , State . REMOVED ) ) { LockSupport . parkNanos ( TimeUnit . MILLISECONDS . toNanos ( 10 ) ) ; if ( Thread . currentThread ( ) . isInterrupted ( ) ) { runState . set ( State . REMOVED ) ; return ; } } } | Unschedule next launched and wait for the current task to complete before closing it . |
29,509 | public void unscheduleTask ( ) { if ( unschedule . compareAndSet ( false , true ) ) { scheduledFuture . cancel ( false ) ; scheduledFuture = null ; } } | Unschedule task if active and cancel thread to inform it must be interrupted in a proper way . |
29,510 | public ResultSet getGeneratedKeys ( Protocol protocol ) { if ( insertId == 0 ) { return SelectResultSet . createEmptyResultSet ( ) ; } if ( updateCount > 1 ) { long [ ] insertIds = new long [ ( int ) updateCount ] ; for ( int i = 0 ; i < updateCount ; i ++ ) { insertIds [ i ] = insertId + i * autoIncrement ; } return SelectResultSet . createGeneratedData ( insertIds , protocol , true ) ; } return SelectResultSet . createGeneratedData ( new long [ ] { insertId } , protocol , true ) ; } | Get generated Keys . |
29,511 | public BigDecimal getInternalBigDecimal ( ColumnInformation columnInfo ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } switch ( columnInfo . getColumnType ( ) ) { case BIT : return BigDecimal . valueOf ( parseBit ( ) ) ; case TINYINT : return BigDecimal . valueOf ( ( long ) getInternalTinyInt ( columnInfo ) ) ; case SMALLINT : case YEAR : return BigDecimal . valueOf ( ( long ) getInternalSmallInt ( columnInfo ) ) ; case INTEGER : case MEDIUMINT : return BigDecimal . valueOf ( getInternalMediumInt ( columnInfo ) ) ; case BIGINT : long value = ( ( buf [ pos ] & 0xff ) + ( ( long ) ( buf [ pos + 1 ] & 0xff ) << 8 ) + ( ( long ) ( buf [ pos + 2 ] & 0xff ) << 16 ) + ( ( long ) ( buf [ pos + 3 ] & 0xff ) << 24 ) + ( ( long ) ( buf [ pos + 4 ] & 0xff ) << 32 ) + ( ( long ) ( buf [ pos + 5 ] & 0xff ) << 40 ) + ( ( long ) ( buf [ pos + 6 ] & 0xff ) << 48 ) + ( ( long ) ( buf [ pos + 7 ] & 0xff ) << 56 ) ) ; if ( columnInfo . isSigned ( ) ) { return new BigDecimal ( String . valueOf ( BigInteger . valueOf ( value ) ) ) . setScale ( columnInfo . getDecimals ( ) ) ; } else { return new BigDecimal ( String . valueOf ( new BigInteger ( 1 , new byte [ ] { ( byte ) ( value >> 56 ) , ( byte ) ( value >> 48 ) , ( byte ) ( value >> 40 ) , ( byte ) ( value >> 32 ) , ( byte ) ( value >> 24 ) , ( byte ) ( value >> 16 ) , ( byte ) ( value >> 8 ) , ( byte ) value } ) ) ) . setScale ( columnInfo . getDecimals ( ) ) ; } case FLOAT : return BigDecimal . valueOf ( getInternalFloat ( columnInfo ) ) ; case DOUBLE : return BigDecimal . valueOf ( getInternalDouble ( columnInfo ) ) ; case DECIMAL : case VARSTRING : case VARCHAR : case STRING : case OLDDECIMAL : return new BigDecimal ( new String ( buf , pos , length , StandardCharsets . UTF_8 ) ) ; default : throw new SQLException ( "getBigDecimal not available for data field type " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) ) ; } } | Get BigDecimal from raw binary format . |
29,512 | @ SuppressWarnings ( "deprecation" ) public Date getInternalDate ( ColumnInformation columnInfo , Calendar cal , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } switch ( columnInfo . getColumnType ( ) ) { case TIMESTAMP : case DATETIME : Timestamp timestamp = getInternalTimestamp ( columnInfo , cal , timeZone ) ; return ( timestamp == null ) ? null : new Date ( timestamp . getTime ( ) ) ; case TIME : throw new SQLException ( "Cannot read Date using a Types.TIME field" ) ; case STRING : String rawValue = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; if ( "0000-00-00" . equals ( rawValue ) ) { lastValueNull |= BIT_LAST_ZERO_DATE ; return null ; } return new Date ( Integer . parseInt ( rawValue . substring ( 0 , 4 ) ) - 1900 , Integer . parseInt ( rawValue . substring ( 5 , 7 ) ) - 1 , Integer . parseInt ( rawValue . substring ( 8 , 10 ) ) ) ; default : if ( length == 0 ) { lastValueNull |= BIT_LAST_FIELD_NULL ; return null ; } int year = ( ( buf [ pos ] & 0xff ) | ( buf [ pos + 1 ] & 0xff ) << 8 ) ; if ( length == 2 && columnInfo . getLength ( ) == 2 ) { if ( year <= 69 ) { year += 2000 ; } else { year += 1900 ; } } int month = 1 ; int day = 1 ; if ( length >= 4 ) { month = buf [ pos + 2 ] ; day = buf [ pos + 3 ] ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . clear ( ) ; calendar . set ( Calendar . YEAR , year ) ; calendar . set ( Calendar . MONTH , month - 1 ) ; calendar . set ( Calendar . DAY_OF_MONTH , day ) ; calendar . set ( Calendar . HOUR_OF_DAY , 0 ) ; calendar . set ( Calendar . MINUTE , 0 ) ; calendar . set ( Calendar . SECOND , 0 ) ; calendar . set ( Calendar . MILLISECOND , 0 ) ; Date dt = new Date ( calendar . getTimeInMillis ( ) ) ; return dt ; } } | Get date from raw binary format . |
29,513 | public Time getInternalTime ( ColumnInformation columnInfo , Calendar cal , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } switch ( columnInfo . getColumnType ( ) ) { case TIMESTAMP : case DATETIME : Timestamp ts = getInternalTimestamp ( columnInfo , cal , timeZone ) ; return ( ts == null ) ? null : new Time ( ts . getTime ( ) ) ; case DATE : throw new SQLException ( "Cannot read Time using a Types.DATE field" ) ; default : Calendar calendar = Calendar . getInstance ( ) ; calendar . clear ( ) ; int day = 0 ; int hour = 0 ; int minutes = 0 ; int seconds = 0 ; boolean negate = false ; if ( length > 0 ) { negate = ( buf [ pos ] & 0xff ) == 0x01 ; } if ( length > 4 ) { day = ( ( buf [ pos + 1 ] & 0xff ) + ( ( buf [ pos + 2 ] & 0xff ) << 8 ) + ( ( buf [ pos + 3 ] & 0xff ) << 16 ) + ( ( buf [ pos + 4 ] & 0xff ) << 24 ) ) ; } if ( length > 7 ) { hour = buf [ pos + 5 ] ; minutes = buf [ pos + 6 ] ; seconds = buf [ pos + 7 ] ; } calendar . set ( 1970 , Calendar . JANUARY , ( ( negate ? - 1 : 1 ) * day ) + 1 , ( negate ? - 1 : 1 ) * hour , minutes , seconds ) ; int nanoseconds = 0 ; if ( length > 8 ) { nanoseconds = ( ( buf [ pos + 8 ] & 0xff ) + ( ( buf [ pos + 9 ] & 0xff ) << 8 ) + ( ( buf [ pos + 10 ] & 0xff ) << 16 ) + ( ( buf [ pos + 11 ] & 0xff ) << 24 ) ) ; } calendar . set ( Calendar . MILLISECOND , nanoseconds / 1000 ) ; return new Time ( calendar . getTimeInMillis ( ) ) ; } } | Get time from raw binary format . |
29,514 | public Object getInternalObject ( ColumnInformation columnInfo , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } switch ( columnInfo . getColumnType ( ) ) { case BIT : if ( columnInfo . getLength ( ) == 1 ) { return buf [ pos ] != 0 ; } byte [ ] dataBit = new byte [ length ] ; System . arraycopy ( buf , pos , dataBit , 0 , length ) ; return dataBit ; case TINYINT : if ( options . tinyInt1isBit && columnInfo . getLength ( ) == 1 ) { return buf [ pos ] != 0 ; } return getInternalInt ( columnInfo ) ; case INTEGER : if ( ! columnInfo . isSigned ( ) ) { return getInternalLong ( columnInfo ) ; } return getInternalInt ( columnInfo ) ; case BIGINT : if ( ! columnInfo . isSigned ( ) ) { return getInternalBigInteger ( columnInfo ) ; } return getInternalLong ( columnInfo ) ; case DOUBLE : return getInternalDouble ( columnInfo ) ; case VARCHAR : case VARSTRING : case STRING : if ( columnInfo . isBinary ( ) ) { byte [ ] data = new byte [ getLengthMaxFieldSize ( ) ] ; System . arraycopy ( buf , pos , data , 0 , getLengthMaxFieldSize ( ) ) ; return data ; } return getInternalString ( columnInfo , null , timeZone ) ; case TIMESTAMP : case DATETIME : return getInternalTimestamp ( columnInfo , null , timeZone ) ; case DATE : return getInternalDate ( columnInfo , null , timeZone ) ; case DECIMAL : return getInternalBigDecimal ( columnInfo ) ; case BLOB : case LONGBLOB : case MEDIUMBLOB : case TINYBLOB : byte [ ] dataBlob = new byte [ getLengthMaxFieldSize ( ) ] ; System . arraycopy ( buf , pos , dataBlob , 0 , getLengthMaxFieldSize ( ) ) ; return dataBlob ; case NULL : return null ; case YEAR : if ( options . yearIsDateType ) { return getInternalDate ( columnInfo , null , timeZone ) ; } return getInternalShort ( columnInfo ) ; case SMALLINT : case MEDIUMINT : return getInternalInt ( columnInfo ) ; case FLOAT : return getInternalFloat ( columnInfo ) ; case TIME : return getInternalTime ( columnInfo , null , timeZone ) ; case OLDDECIMAL : case JSON : return getInternalString ( columnInfo , null , timeZone ) ; case GEOMETRY : byte [ ] data = new byte [ length ] ; System . arraycopy ( buf , pos , data , 0 , length ) ; return data ; case ENUM : break ; case NEWDATE : break ; case SET : break ; default : break ; } throw ExceptionMapper . getFeatureNotSupportedException ( "Type '" + columnInfo . getColumnType ( ) . getTypeName ( ) + "' is not supported" ) ; } | Get Object from raw binary format . |
29,515 | public boolean getInternalBoolean ( ColumnInformation columnInfo ) throws SQLException { if ( lastValueWasNull ( ) ) { return false ; } switch ( columnInfo . getColumnType ( ) ) { case BIT : return parseBit ( ) != 0 ; case TINYINT : return getInternalTinyInt ( columnInfo ) != 0 ; case SMALLINT : case YEAR : return getInternalSmallInt ( columnInfo ) != 0 ; case INTEGER : case MEDIUMINT : return getInternalMediumInt ( columnInfo ) != 0 ; case BIGINT : return getInternalLong ( columnInfo ) != 0 ; case FLOAT : return getInternalFloat ( columnInfo ) != 0 ; case DOUBLE : return getInternalDouble ( columnInfo ) != 0 ; case DECIMAL : case OLDDECIMAL : return getInternalBigDecimal ( columnInfo ) . longValue ( ) != 0 ; default : final String rawVal = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; return ! ( "false" . equals ( rawVal ) || "0" . equals ( rawVal ) ) ; } } | Get boolean from raw binary format . |
29,516 | public byte getInternalByte ( ColumnInformation columnInfo ) throws SQLException { if ( lastValueWasNull ( ) ) { return 0 ; } long value ; switch ( columnInfo . getColumnType ( ) ) { case BIT : value = parseBit ( ) ; break ; case TINYINT : value = getInternalTinyInt ( columnInfo ) ; break ; case SMALLINT : case YEAR : value = getInternalSmallInt ( columnInfo ) ; break ; case INTEGER : case MEDIUMINT : value = getInternalMediumInt ( columnInfo ) ; break ; case BIGINT : value = getInternalLong ( columnInfo ) ; break ; case FLOAT : value = ( long ) getInternalFloat ( columnInfo ) ; break ; case DOUBLE : value = ( long ) getInternalDouble ( columnInfo ) ; break ; case DECIMAL : case OLDDECIMAL : BigDecimal bigDecimal = getInternalBigDecimal ( columnInfo ) ; rangeCheck ( Byte . class , Byte . MIN_VALUE , Byte . MAX_VALUE , bigDecimal , columnInfo ) ; return bigDecimal . byteValue ( ) ; case VARSTRING : case VARCHAR : case STRING : value = Long . parseLong ( new String ( buf , pos , length , StandardCharsets . UTF_8 ) ) ; break ; default : throw new SQLException ( "getByte not available for data field type " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) ) ; } rangeCheck ( Byte . class , Byte . MIN_VALUE , Byte . MAX_VALUE , value , columnInfo ) ; return ( byte ) value ; } | Get byte from raw binary format . |
29,517 | public String getInternalTimeString ( ColumnInformation columnInfo ) { if ( lastValueWasNull ( ) ) { return null ; } if ( length == 0 ) { if ( columnInfo . getDecimals ( ) == 0 ) { return "00:00:00" ; } else { StringBuilder value = new StringBuilder ( "00:00:00." ) ; int decimal = columnInfo . getDecimals ( ) ; while ( decimal -- > 0 ) { value . append ( "0" ) ; } return value . toString ( ) ; } } String rawValue = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; if ( "0000-00-00" . equals ( rawValue ) ) { return null ; } int day = ( ( buf [ pos + 1 ] & 0xff ) | ( ( buf [ pos + 2 ] & 0xff ) << 8 ) | ( ( buf [ pos + 3 ] & 0xff ) << 16 ) | ( ( buf [ pos + 4 ] & 0xff ) << 24 ) ) ; int hour = buf [ pos + 5 ] ; int timeHour = hour + day * 24 ; String hourString ; if ( timeHour < 10 ) { hourString = "0" + timeHour ; } else { hourString = Integer . toString ( timeHour ) ; } String minuteString ; int minutes = buf [ pos + 6 ] ; if ( minutes < 10 ) { minuteString = "0" + minutes ; } else { minuteString = Integer . toString ( minutes ) ; } String secondString ; int seconds = buf [ pos + 7 ] ; if ( seconds < 10 ) { secondString = "0" + seconds ; } else { secondString = Integer . toString ( seconds ) ; } int microseconds = 0 ; if ( length > 8 ) { microseconds = ( ( buf [ pos + 8 ] & 0xff ) | ( buf [ pos + 9 ] & 0xff ) << 8 | ( buf [ pos + 10 ] & 0xff ) << 16 | ( buf [ pos + 11 ] & 0xff ) << 24 ) ; } StringBuilder microsecondString = new StringBuilder ( Integer . toString ( microseconds ) ) ; while ( microsecondString . length ( ) < 6 ) { microsecondString . insert ( 0 , "0" ) ; } boolean negative = ( buf [ pos ] == 0x01 ) ; return ( negative ? "-" : "" ) + ( hourString + ":" + minuteString + ":" + secondString + "." + microsecondString ) ; } | Get Time in string format from raw binary format . |
29,518 | public ZonedDateTime getInternalZonedDateTime ( ColumnInformation columnInfo , Class clazz , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } if ( length == 0 ) { lastValueNull |= BIT_LAST_FIELD_NULL ; return null ; } switch ( columnInfo . getColumnType ( ) . getSqlType ( ) ) { case Types . TIMESTAMP : int year = ( ( buf [ pos ] & 0xff ) | ( buf [ pos + 1 ] & 0xff ) << 8 ) ; int month = buf [ pos + 2 ] ; int day = buf [ pos + 3 ] ; int hour = 0 ; int minutes = 0 ; int seconds = 0 ; int microseconds = 0 ; if ( length > 4 ) { hour = buf [ pos + 4 ] ; minutes = buf [ pos + 5 ] ; seconds = buf [ pos + 6 ] ; if ( length > 7 ) { microseconds = ( ( buf [ pos + 7 ] & 0xff ) + ( ( buf [ pos + 8 ] & 0xff ) << 8 ) + ( ( buf [ pos + 9 ] & 0xff ) << 16 ) + ( ( buf [ pos + 10 ] & 0xff ) << 24 ) ) ; } } return ZonedDateTime . of ( year , month , day , hour , minutes , seconds , microseconds * 1000 , timeZone . toZoneId ( ) ) ; case Types . VARCHAR : case Types . LONGVARCHAR : case Types . CHAR : String raw = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; if ( raw . startsWith ( "0000-00-00 00:00:00" ) ) { return null ; } try { return ZonedDateTime . parse ( raw , TEXT_ZONED_DATE_TIME ) ; } catch ( DateTimeParseException dateParserEx ) { throw new SQLException ( raw + " cannot be parse as ZonedDateTime. time must have \"yyyy-MM-dd[T/ ]HH:mm:ss[.S]\" " + "with offset and timezone format (example : '2011-12-03 10:15:30+01:00[Europe/Paris]')" ) ; } default : throw new SQLException ( "Cannot read " + clazz . getName ( ) + " using a " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) + " field" ) ; } } | Get ZonedDateTime from raw binary format . |
29,519 | public LocalTime getInternalLocalTime ( ColumnInformation columnInfo , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } if ( length == 0 ) { lastValueNull |= BIT_LAST_FIELD_NULL ; return null ; } switch ( columnInfo . getColumnType ( ) . getSqlType ( ) ) { case Types . TIME : int day = 0 ; int hour = 0 ; int minutes = 0 ; int seconds = 0 ; int microseconds = 0 ; final boolean negate = ( buf [ pos ] & 0xff ) == 0x01 ; if ( length > 4 ) { day = ( ( buf [ pos + 1 ] & 0xff ) + ( ( buf [ pos + 2 ] & 0xff ) << 8 ) + ( ( buf [ pos + 3 ] & 0xff ) << 16 ) + ( ( buf [ pos + 4 ] & 0xff ) << 24 ) ) ; } if ( length > 7 ) { hour = buf [ pos + 5 ] ; minutes = buf [ pos + 6 ] ; seconds = buf [ pos + 7 ] ; } if ( length > 8 ) { microseconds = ( ( buf [ pos + 8 ] & 0xff ) + ( ( buf [ pos + 9 ] & 0xff ) << 8 ) + ( ( buf [ pos + 10 ] & 0xff ) << 16 ) + ( ( buf [ pos + 11 ] & 0xff ) << 24 ) ) ; } return LocalTime . of ( ( negate ? - 1 : 1 ) * ( day * 24 + hour ) , minutes , seconds , microseconds * 1000 ) ; case Types . VARCHAR : case Types . LONGVARCHAR : case Types . CHAR : String raw = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; try { return LocalTime . parse ( raw , DateTimeFormatter . ISO_LOCAL_TIME . withZone ( timeZone . toZoneId ( ) ) ) ; } catch ( DateTimeParseException dateParserEx ) { throw new SQLException ( raw + " cannot be parse as LocalTime (format is \"HH:mm:ss[.S]\" for data type \"" + columnInfo . getColumnType ( ) + "\")" ) ; } case Types . TIMESTAMP : ZonedDateTime zonedDateTime = getInternalZonedDateTime ( columnInfo , LocalTime . class , timeZone ) ; return zonedDateTime == null ? null : zonedDateTime . withZoneSameInstant ( ZoneId . systemDefault ( ) ) . toLocalTime ( ) ; default : throw new SQLException ( "Cannot read LocalTime using a " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) + " field" ) ; } } | Get LocalTime from raw binary format . |
29,520 | public static Pool retrievePool ( UrlParser urlParser ) { if ( ! poolMap . containsKey ( urlParser ) ) { synchronized ( poolMap ) { if ( ! poolMap . containsKey ( urlParser ) ) { if ( poolExecutor == null ) { poolExecutor = new ScheduledThreadPoolExecutor ( 1 , new MariaDbThreadFactory ( "MariaDbPool-maxTimeoutIdle-checker" ) ) ; } Pool pool = new Pool ( urlParser , poolIndex . incrementAndGet ( ) , poolExecutor ) ; poolMap . put ( urlParser , pool ) ; return pool ; } } } return poolMap . get ( urlParser ) ; } | Get existing pool for a configuration . Create it if doesn t exists . |
29,521 | public static void remove ( Pool pool ) { if ( poolMap . containsKey ( pool . getUrlParser ( ) ) ) { synchronized ( poolMap ) { if ( poolMap . containsKey ( pool . getUrlParser ( ) ) ) { poolMap . remove ( pool . getUrlParser ( ) ) ; shutdownExecutor ( ) ; } } } } | Remove pool . |
29,522 | public static void close ( ) { synchronized ( poolMap ) { for ( Pool pool : poolMap . values ( ) ) { try { pool . close ( ) ; } catch ( InterruptedException exception ) { } } shutdownExecutor ( ) ; poolMap . clear ( ) ; } } | Close all pools . |
29,523 | public static void close ( String poolName ) { if ( poolName == null ) { return ; } synchronized ( poolMap ) { for ( Pool pool : poolMap . values ( ) ) { if ( poolName . equals ( pool . getUrlParser ( ) . getOptions ( ) . poolName ) ) { try { pool . close ( ) ; } catch ( InterruptedException exception ) { } poolMap . remove ( pool . getUrlParser ( ) ) ; return ; } } if ( poolMap . isEmpty ( ) ) { shutdownExecutor ( ) ; } } } | Closing a pool with name defined in url . |
29,524 | public synchronized int read ( byte [ ] externalBuf , int off , int len ) throws IOException { if ( len == 0 ) { return 0 ; } int totalReads = 0 ; while ( true ) { if ( end - pos <= 0 ) { if ( len - totalReads >= buf . length ) { int reads = super . read ( externalBuf , off + totalReads , len - totalReads ) ; if ( reads <= 0 ) { return ( totalReads == 0 ) ? - 1 : totalReads ; } return totalReads + reads ; } else { fillBuffer ( len - totalReads ) ; if ( end <= 0 ) { return ( totalReads == 0 ) ? - 1 : totalReads ; } } } int copyLength = Math . min ( len - totalReads , end - pos ) ; System . arraycopy ( buf , pos , externalBuf , off + totalReads , copyLength ) ; pos += copyLength ; totalReads += copyLength ; if ( totalReads >= len || super . available ( ) <= 0 ) { return totalReads ; } } } | Returing byte array from cache of reading socket if needed . |
29,525 | private void fillBuffer ( int minNeededBytes ) throws IOException { int lengthToReallyRead = Math . min ( BUF_SIZE , Math . max ( super . available ( ) , minNeededBytes ) ) ; end = super . read ( buf , 0 , lengthToReallyRead ) ; pos = 0 ; } | Fill buffer with required length or available bytes . |
29,526 | public void checkClientTrusted ( X509Certificate [ ] x509Certificates , String string ) throws CertificateException { if ( trustManager == null ) { return ; } trustManager . checkClientTrusted ( x509Certificates , string ) ; } | Check client trusted . |
29,527 | private void addConnectionRequest ( ) { if ( totalConnection . get ( ) < options . maxPoolSize && poolState . get ( ) == POOL_STATE_OK ) { connectionAppender . prestartCoreThread ( ) ; connectionAppenderQueue . offer ( ( ) -> { if ( ( totalConnection . get ( ) < options . minPoolSize || pendingRequestNumber . get ( ) > 0 ) && totalConnection . get ( ) < options . maxPoolSize ) { try { addConnection ( ) ; } catch ( SQLException sqle ) { } } } ) ; } } | Add new connection if needed . Only one thread create new connection so new connection request will wait to newly created connection or for a released connection . |
29,528 | private void removeIdleTimeoutConnection ( ) { Iterator < MariaDbPooledConnection > iterator = idleConnections . descendingIterator ( ) ; MariaDbPooledConnection item ; while ( iterator . hasNext ( ) ) { item = iterator . next ( ) ; long idleTime = System . nanoTime ( ) - item . getLastUsed ( ) . get ( ) ; boolean timedOut = idleTime > TimeUnit . SECONDS . toNanos ( maxIdleTime ) ; boolean shouldBeReleased = false ; if ( globalInfo != null ) { if ( idleTime > TimeUnit . SECONDS . toNanos ( globalInfo . getWaitTimeout ( ) - 45 ) ) { shouldBeReleased = true ; } if ( timedOut && totalConnection . get ( ) > options . minPoolSize ) { shouldBeReleased = true ; } } else if ( timedOut ) { shouldBeReleased = true ; } if ( shouldBeReleased && idleConnections . remove ( item ) ) { totalConnection . decrementAndGet ( ) ; silentCloseConnection ( item ) ; addConnectionRequest ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "pool {} connection removed due to inactivity (total:{}, active:{}, pending:{})" , poolTag , totalConnection . get ( ) , getActiveConnections ( ) , pendingRequestNumber . get ( ) ) ; } } } } | Removing idle connection . Close them and recreate connection to reach minimal number of connection . |
29,529 | private void addConnection ( ) throws SQLException { Protocol protocol = Utils . retrieveProxy ( urlParser , globalInfo ) ; MariaDbConnection connection = new MariaDbConnection ( protocol ) ; MariaDbPooledConnection pooledConnection = createPoolConnection ( connection ) ; if ( options . staticGlobal ) { if ( globalInfo == null ) { initializePoolGlobalState ( connection ) ; } connection . setDefaultTransactionIsolation ( globalInfo . getDefaultTransactionIsolation ( ) ) ; } else { connection . setDefaultTransactionIsolation ( connection . getTransactionIsolation ( ) ) ; } if ( poolState . get ( ) == POOL_STATE_OK && totalConnection . incrementAndGet ( ) <= options . maxPoolSize ) { idleConnections . addFirst ( pooledConnection ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "pool {} new physical connection created (total:{}, active:{}, pending:{})" , poolTag , totalConnection . get ( ) , getActiveConnections ( ) , pendingRequestNumber . get ( ) ) ; } return ; } silentCloseConnection ( pooledConnection ) ; } | Create new connection . |
29,530 | private MariaDbPooledConnection getIdleConnection ( long timeout , TimeUnit timeUnit ) throws InterruptedException { while ( true ) { MariaDbPooledConnection item = ( timeout == 0 ) ? idleConnections . pollFirst ( ) : idleConnections . pollFirst ( timeout , timeUnit ) ; if ( item != null ) { MariaDbConnection connection = item . getConnection ( ) ; try { if ( TimeUnit . NANOSECONDS . toMillis ( System . nanoTime ( ) - item . getLastUsed ( ) . get ( ) ) > options . poolValidMinDelay ) { if ( connection . isValid ( 10 ) ) { item . lastUsedToNow ( ) ; return item ; } } else { item . lastUsedToNow ( ) ; return item ; } } catch ( SQLException sqle ) { } totalConnection . decrementAndGet ( ) ; silentAbortConnection ( item ) ; addConnectionRequest ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "pool {} connection removed from pool due to failed validation (total:{}, active:{}, pending:{})" , poolTag , totalConnection . get ( ) , getActiveConnections ( ) , pendingRequestNumber . get ( ) ) ; } continue ; } return null ; } } | Get an existing idle connection in pool . |
29,531 | public MariaDbConnection getConnection ( String username , String password ) throws SQLException { try { if ( ( urlParser . getUsername ( ) != null ? urlParser . getUsername ( ) . equals ( username ) : username == null ) && ( urlParser . getPassword ( ) != null ? urlParser . getPassword ( ) . equals ( password ) : password == null ) ) { return getConnection ( ) ; } UrlParser tmpUrlParser = ( UrlParser ) urlParser . clone ( ) ; tmpUrlParser . setUsername ( username ) ; tmpUrlParser . setPassword ( password ) ; Protocol protocol = Utils . retrieveProxy ( tmpUrlParser , globalInfo ) ; return new MariaDbConnection ( protocol ) ; } catch ( CloneNotSupportedException cloneException ) { throw new SQLException ( "Error getting connection, parameters cannot be cloned" , cloneException ) ; } } | Get new connection from pool if user and password correspond to pool . If username and password are different from pool will return a dedicated connection . |
29,532 | public void close ( ) throws InterruptedException { synchronized ( this ) { Pools . remove ( this ) ; poolState . set ( POOL_STATE_CLOSING ) ; pendingRequestNumber . set ( 0 ) ; scheduledFuture . cancel ( false ) ; connectionAppender . shutdown ( ) ; try { connectionAppender . awaitTermination ( 10 , TimeUnit . SECONDS ) ; } catch ( InterruptedException i ) { } if ( logger . isInfoEnabled ( ) ) { logger . info ( "closing pool {} (total:{}, active:{}, pending:{})" , poolTag , totalConnection . get ( ) , getActiveConnections ( ) , pendingRequestNumber . get ( ) ) ; } ExecutorService connectionRemover = new ThreadPoolExecutor ( totalConnection . get ( ) , options . maxPoolSize , 10 , TimeUnit . SECONDS , new LinkedBlockingQueue < > ( options . maxPoolSize ) , new MariaDbThreadFactory ( poolTag + "-destroyer" ) ) ; long start = System . nanoTime ( ) ; do { closeAll ( connectionRemover , idleConnections ) ; if ( totalConnection . get ( ) > 0 ) { Thread . sleep ( 0 , 10_00 ) ; } } while ( totalConnection . get ( ) > 0 && TimeUnit . NANOSECONDS . toSeconds ( System . nanoTime ( ) - start ) < 10 ) ; if ( totalConnection . get ( ) > 0 || idleConnections . isEmpty ( ) ) { closeAll ( connectionRemover , idleConnections ) ; } connectionRemover . shutdown ( ) ; try { unRegisterJmx ( ) ; } catch ( Exception exception ) { } connectionRemover . awaitTermination ( 10 , TimeUnit . SECONDS ) ; } } | Close pool and underlying connections . |
29,533 | public void addToBlacklist ( HostAddress hostAddress ) { if ( hostAddress != null && ! isExplicitClosed ( ) ) { blacklist . putIfAbsent ( hostAddress , System . nanoTime ( ) ) ; } } | After a failover put the hostAddress in a static list so the other connection will not take this host in account for a time . |
29,534 | public void resetOldsBlackListHosts ( ) { long currentTimeNanos = System . nanoTime ( ) ; Set < Map . Entry < HostAddress , Long > > entries = blacklist . entrySet ( ) ; for ( Map . Entry < HostAddress , Long > blEntry : entries ) { long entryNanos = blEntry . getValue ( ) ; long durationSeconds = TimeUnit . NANOSECONDS . toSeconds ( currentTimeNanos - entryNanos ) ; if ( durationSeconds >= urlParser . getOptions ( ) . loadBalanceBlacklistTimeout ) { blacklist . remove ( blEntry . getKey ( ) , entryNanos ) ; } } } | Permit to remove Host to blacklist after loadBalanceBlacklistTimeout seconds . |
29,535 | public boolean setMasterHostFail ( ) { if ( masterHostFail . compareAndSet ( false , true ) ) { masterHostFailNanos = System . nanoTime ( ) ; currentConnectionAttempts . set ( 0 ) ; return true ; } return false ; } | Set master fail variables . |
29,536 | public HandleErrorResult relaunchOperation ( Method method , Object [ ] args ) throws IllegalAccessException , InvocationTargetException { HandleErrorResult handleErrorResult = new HandleErrorResult ( true ) ; if ( method != null ) { switch ( method . getName ( ) ) { case "executeQuery" : if ( args [ 2 ] instanceof String ) { String query = ( ( String ) args [ 2 ] ) . toUpperCase ( Locale . ROOT ) ; if ( ! "ALTER SYSTEM CRASH" . equals ( query ) && ! query . startsWith ( "KILL" ) ) { logger . debug ( "relaunch query to new connection {}" , ( ( currentProtocol != null ) ? "(conn=" + currentProtocol . getServerThreadId ( ) + ")" : "" ) ) ; handleErrorResult . resultObject = method . invoke ( currentProtocol , args ) ; handleErrorResult . mustThrowError = false ; } } break ; case "executePreparedQuery" : try { boolean mustBeOnMaster = ( Boolean ) args [ 0 ] ; ServerPrepareResult oldServerPrepareResult = ( ServerPrepareResult ) args [ 1 ] ; ServerPrepareResult serverPrepareResult = currentProtocol . prepare ( oldServerPrepareResult . getSql ( ) , mustBeOnMaster ) ; oldServerPrepareResult . failover ( serverPrepareResult . getStatementId ( ) , currentProtocol ) ; logger . debug ( "relaunch query to new connection " + ( ( currentProtocol != null ) ? "server thread id " + currentProtocol . getServerThreadId ( ) : "" ) ) ; handleErrorResult . resultObject = method . invoke ( currentProtocol , args ) ; handleErrorResult . mustThrowError = false ; } catch ( Exception e ) { } break ; default : handleErrorResult . resultObject = method . invoke ( currentProtocol , args ) ; handleErrorResult . mustThrowError = false ; break ; } } return handleErrorResult ; } | After a failover that has bean done relaunch the operation that was in progress . In case of special operation that crash server doesn t relaunched it ; |
29,537 | public boolean isQueryRelaunchable ( Method method , Object [ ] args ) { if ( method != null ) { switch ( method . getName ( ) ) { case "executeQuery" : if ( ! ( ( Boolean ) args [ 0 ] ) ) { return true ; } if ( args [ 2 ] instanceof String ) { return ( ( String ) args [ 2 ] ) . toUpperCase ( Locale . ROOT ) . startsWith ( "SELECT" ) ; } else if ( args [ 2 ] instanceof ClientPrepareResult ) { @ SuppressWarnings ( "unchecked" ) String query = new String ( ( ( ClientPrepareResult ) args [ 2 ] ) . getQueryParts ( ) . get ( 0 ) ) . toUpperCase ( Locale . ROOT ) ; return query . startsWith ( "SELECT" ) ; } break ; case "executePreparedQuery" : if ( ! ( ( Boolean ) args [ 0 ] ) ) { return true ; } ServerPrepareResult serverPrepareResult = ( ServerPrepareResult ) args [ 1 ] ; return ( serverPrepareResult . getSql ( ) ) . toUpperCase ( Locale . ROOT ) . startsWith ( "SELECT" ) ; case "executeBatchStmt" : case "executeBatchClient" : case "executeBatchServer" : return ! ( ( Boolean ) args [ 0 ] ) ; default : return false ; } } return false ; } | Check if query can be re - executed . |
29,538 | public void syncConnection ( Protocol from , Protocol to ) throws SQLException { if ( from != null ) { proxy . lock . lock ( ) ; try { to . resetStateAfterFailover ( from . getMaxRows ( ) , from . getTransactionIsolationLevel ( ) , from . getDatabase ( ) , from . getAutocommit ( ) ) ; } finally { proxy . lock . unlock ( ) ; } } } | When switching between 2 connections report existing connection parameter to the new used connection . |
29,539 | public void throwFailoverMessage ( HostAddress failHostAddress , boolean wasMaster , SQLException queryException , boolean reconnected ) throws SQLException { String firstPart = "Communications link failure with " + ( wasMaster ? "primary" : "secondary" ) + ( ( failHostAddress != null ) ? " host " + failHostAddress . host + ":" + failHostAddress . port : "" ) + ". " ; String error = "" ; if ( reconnected ) { error += " Driver has reconnect connection" ; } else { if ( currentConnectionAttempts . get ( ) > urlParser . getOptions ( ) . retriesAllDown ) { error += " Driver will not try to reconnect (too much failure > " + urlParser . getOptions ( ) . retriesAllDown + ")" ; } } String message ; String sqlState ; int vendorCode = 0 ; Throwable cause = null ; if ( queryException == null ) { message = firstPart + error ; sqlState = CONNECTION_EXCEPTION . getSqlState ( ) ; } else { message = firstPart + queryException . getMessage ( ) + ". " + error ; sqlState = queryException . getSQLState ( ) ; vendorCode = queryException . getErrorCode ( ) ; cause = queryException . getCause ( ) ; } if ( sqlState != null && sqlState . startsWith ( "08" ) ) { if ( reconnected ) { sqlState = "25S03" ; } else { throw new SQLNonTransientConnectionException ( message , sqlState , vendorCode , cause ) ; } } throw new SQLException ( message , sqlState , vendorCode , cause ) ; } | Throw a human readable message after a failoverException . |
29,540 | public String getInternalString ( ColumnInformation columnInfo , Calendar cal , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } switch ( columnInfo . getColumnType ( ) ) { case BIT : return String . valueOf ( parseBit ( ) ) ; case DOUBLE : case FLOAT : return zeroFillingIfNeeded ( new String ( buf , pos , length , StandardCharsets . UTF_8 ) , columnInfo ) ; case TIME : return getInternalTimeString ( columnInfo ) ; case DATE : Date date = getInternalDate ( columnInfo , cal , timeZone ) ; if ( date == null ) { if ( ( lastValueNull & BIT_LAST_ZERO_DATE ) != 0 ) { lastValueNull ^= BIT_LAST_ZERO_DATE ; return new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; } return null ; } return date . toString ( ) ; case YEAR : if ( options . yearIsDateType ) { Date date1 = getInternalDate ( columnInfo , cal , timeZone ) ; return ( date1 == null ) ? null : date1 . toString ( ) ; } break ; case TIMESTAMP : case DATETIME : Timestamp timestamp = getInternalTimestamp ( columnInfo , cal , timeZone ) ; if ( timestamp == null ) { if ( ( lastValueNull & BIT_LAST_ZERO_DATE ) != 0 ) { lastValueNull ^= BIT_LAST_ZERO_DATE ; return new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; } return null ; } return timestamp . toString ( ) ; case DECIMAL : case OLDDECIMAL : BigDecimal bigDecimal = getInternalBigDecimal ( columnInfo ) ; return ( bigDecimal == null ) ? null : zeroFillingIfNeeded ( bigDecimal . toString ( ) , columnInfo ) ; case NULL : return null ; default : break ; } if ( maxFieldSize > 0 ) { return new String ( buf , pos , Math . min ( maxFieldSize * 3 , length ) , StandardCharsets . UTF_8 ) . substring ( 0 , Math . min ( maxFieldSize , length ) ) ; } return new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; } | Get String from raw text format . |
29,541 | public int getInternalInt ( ColumnInformation columnInfo ) throws SQLException { if ( lastValueWasNull ( ) ) { return 0 ; } long value = getInternalLong ( columnInfo ) ; rangeCheck ( Integer . class , Integer . MIN_VALUE , Integer . MAX_VALUE , value , columnInfo ) ; return ( int ) value ; } | Get int from raw text format . |
29,542 | public float getInternalFloat ( ColumnInformation columnInfo ) throws SQLException { if ( lastValueWasNull ( ) ) { return 0 ; } switch ( columnInfo . getColumnType ( ) ) { case BIT : return parseBit ( ) ; case TINYINT : case SMALLINT : case YEAR : case INTEGER : case MEDIUMINT : case FLOAT : case DOUBLE : case DECIMAL : case VARSTRING : case VARCHAR : case STRING : case OLDDECIMAL : case BIGINT : try { return Float . valueOf ( new String ( buf , pos , length , StandardCharsets . UTF_8 ) ) ; } catch ( NumberFormatException nfe ) { SQLException sqlException = new SQLException ( "Incorrect format \"" + new String ( buf , pos , length , StandardCharsets . UTF_8 ) + "\" for getFloat for data field with type " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) , "22003" , 1264 ) ; sqlException . initCause ( nfe ) ; throw sqlException ; } default : throw new SQLException ( "getFloat not available for data field type " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) ) ; } } | Get float from raw text format . |
29,543 | public BigDecimal getInternalBigDecimal ( ColumnInformation columnInfo ) { if ( lastValueWasNull ( ) ) { return null ; } if ( columnInfo . getColumnType ( ) == ColumnType . BIT ) { return BigDecimal . valueOf ( parseBit ( ) ) ; } return new BigDecimal ( new String ( buf , pos , length , StandardCharsets . UTF_8 ) ) ; } | Get BigDecimal from raw text format . |
29,544 | @ SuppressWarnings ( "deprecation" ) public Date getInternalDate ( ColumnInformation columnInfo , Calendar cal , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } switch ( columnInfo . getColumnType ( ) ) { case DATE : int [ ] datePart = new int [ ] { 0 , 0 , 0 } ; int partIdx = 0 ; for ( int begin = pos ; begin < pos + length ; begin ++ ) { byte b = buf [ begin ] ; if ( b == '-' ) { partIdx ++ ; continue ; } if ( b < '0' || b > '9' ) { throw new SQLException ( "cannot parse data in date string '" + new String ( buf , pos , length , StandardCharsets . UTF_8 ) + "'" ) ; } datePart [ partIdx ] = datePart [ partIdx ] * 10 + b - 48 ; } if ( datePart [ 0 ] == 0 && datePart [ 1 ] == 0 && datePart [ 2 ] == 0 ) { lastValueNull |= BIT_LAST_ZERO_DATE ; return null ; } return new Date ( datePart [ 0 ] - 1900 , datePart [ 1 ] - 1 , datePart [ 2 ] ) ; case TIMESTAMP : case DATETIME : Timestamp timestamp = getInternalTimestamp ( columnInfo , cal , timeZone ) ; if ( timestamp == null ) { return null ; } return new Date ( timestamp . getTime ( ) ) ; case TIME : throw new SQLException ( "Cannot read DATE using a Types.TIME field" ) ; case YEAR : int year = 0 ; for ( int begin = pos ; begin < pos + length ; begin ++ ) { year = year * 10 + buf [ begin ] - 48 ; } if ( length == 2 && columnInfo . getLength ( ) == 2 ) { if ( year <= 69 ) { year += 2000 ; } else { year += 1900 ; } } return new Date ( year - 1900 , 0 , 1 ) ; default : try { DateFormat sdf = new SimpleDateFormat ( "yyyy-MM-dd" ) ; sdf . setTimeZone ( timeZone ) ; java . util . Date utilDate = sdf . parse ( new String ( buf , pos , length , StandardCharsets . UTF_8 ) ) ; return new Date ( utilDate . getTime ( ) ) ; } catch ( ParseException e ) { throw ExceptionMapper . getSqlException ( "Could not get object as Date : " + e . getMessage ( ) , "S1009" , e ) ; } } } | Get date from raw text format . |
29,545 | public Time getInternalTime ( ColumnInformation columnInfo , Calendar cal , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } if ( columnInfo . getColumnType ( ) == ColumnType . TIMESTAMP || columnInfo . getColumnType ( ) == ColumnType . DATETIME ) { Timestamp timestamp = getInternalTimestamp ( columnInfo , cal , timeZone ) ; return ( timestamp == null ) ? null : new Time ( timestamp . getTime ( ) ) ; } else if ( columnInfo . getColumnType ( ) == ColumnType . DATE ) { throw new SQLException ( "Cannot read Time using a Types.DATE field" ) ; } else { String raw = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; if ( ! options . useLegacyDatetimeCode && ( raw . startsWith ( "-" ) || raw . split ( ":" ) . length != 3 || raw . indexOf ( ":" ) > 3 ) ) { throw new SQLException ( "Time format \"" + raw + "\" incorrect, must be HH:mm:ss" ) ; } boolean negate = raw . startsWith ( "-" ) ; if ( negate ) { raw = raw . substring ( 1 ) ; } String [ ] rawPart = raw . split ( ":" ) ; if ( rawPart . length == 3 ) { int hour = Integer . parseInt ( rawPart [ 0 ] ) ; int minutes = Integer . parseInt ( rawPart [ 1 ] ) ; int seconds = Integer . parseInt ( rawPart [ 2 ] . substring ( 0 , 2 ) ) ; Calendar calendar = Calendar . getInstance ( ) ; if ( options . useLegacyDatetimeCode ) { calendar . setLenient ( true ) ; } calendar . clear ( ) ; calendar . set ( 1970 , Calendar . JANUARY , 1 , ( negate ? - 1 : 1 ) * hour , minutes , seconds ) ; int nanoseconds = extractNanos ( raw ) ; calendar . set ( Calendar . MILLISECOND , nanoseconds / 1000000 ) ; return new Time ( calendar . getTimeInMillis ( ) ) ; } else { throw new SQLException ( raw + " cannot be parse as time. time must have \"99:99:99\" format" ) ; } } } | Get time from raw text format . |
29,546 | public boolean getInternalBoolean ( ColumnInformation columnInfo ) { if ( lastValueWasNull ( ) ) { return false ; } if ( columnInfo . getColumnType ( ) == ColumnType . BIT ) { return parseBit ( ) != 0 ; } final String rawVal = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; return ! ( "false" . equals ( rawVal ) || "0" . equals ( rawVal ) ) ; } | Get boolean from raw text format . |
29,547 | public byte getInternalByte ( ColumnInformation columnInfo ) throws SQLException { if ( lastValueWasNull ( ) ) { return 0 ; } long value = getInternalLong ( columnInfo ) ; rangeCheck ( Byte . class , Byte . MIN_VALUE , Byte . MAX_VALUE , value , columnInfo ) ; return ( byte ) value ; } | Get byte from raw text format . |
29,548 | public short getInternalShort ( ColumnInformation columnInfo ) throws SQLException { if ( lastValueWasNull ( ) ) { return 0 ; } long value = getInternalLong ( columnInfo ) ; rangeCheck ( Short . class , Short . MIN_VALUE , Short . MAX_VALUE , value , columnInfo ) ; return ( short ) value ; } | Get short from raw text format . |
29,549 | public String getInternalTimeString ( ColumnInformation columnInfo ) { if ( lastValueWasNull ( ) ) { return null ; } String rawValue = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; if ( "0000-00-00" . equals ( rawValue ) ) { return null ; } if ( options . maximizeMysqlCompatibility && options . useLegacyDatetimeCode && rawValue . indexOf ( "." ) > 0 ) { return rawValue . substring ( 0 , rawValue . indexOf ( "." ) ) ; } return rawValue ; } | Get Time in string format from raw text format . |
29,550 | public BigInteger getInternalBigInteger ( ColumnInformation columnInfo ) { if ( lastValueWasNull ( ) ) { return null ; } return new BigInteger ( new String ( buf , pos , length , StandardCharsets . UTF_8 ) ) ; } | Get BigInteger format from raw text format . |
29,551 | public ZonedDateTime getInternalZonedDateTime ( ColumnInformation columnInfo , Class clazz , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } if ( length == 0 ) { lastValueNull |= BIT_LAST_FIELD_NULL ; return null ; } String raw = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; switch ( columnInfo . getColumnType ( ) . getSqlType ( ) ) { case Types . TIMESTAMP : if ( raw . startsWith ( "0000-00-00 00:00:00" ) ) { return null ; } try { LocalDateTime localDateTime = LocalDateTime . parse ( raw , TEXT_LOCAL_DATE_TIME . withZone ( timeZone . toZoneId ( ) ) ) ; return ZonedDateTime . of ( localDateTime , timeZone . toZoneId ( ) ) ; } catch ( DateTimeParseException dateParserEx ) { throw new SQLException ( raw + " cannot be parse as LocalDateTime. time must have \"yyyy-MM-dd HH:mm:ss[.S]\" format" ) ; } case Types . VARCHAR : case Types . LONGVARCHAR : case Types . CHAR : if ( raw . startsWith ( "0000-00-00 00:00:00" ) ) { return null ; } try { return ZonedDateTime . parse ( raw , TEXT_ZONED_DATE_TIME ) ; } catch ( DateTimeParseException dateParserEx ) { throw new SQLException ( raw + " cannot be parse as ZonedDateTime. time must have \"yyyy-MM-dd[T/ ]HH:mm:ss[.S]\" " + "with offset and timezone format (example : '2011-12-03 10:15:30+01:00[Europe/Paris]')" ) ; } default : throw new SQLException ( "Cannot read " + clazz . getName ( ) + " using a " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) + " field" ) ; } } | Get ZonedDateTime format from raw text format . |
29,552 | public OffsetTime getInternalOffsetTime ( ColumnInformation columnInfo , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } if ( length == 0 ) { lastValueNull |= BIT_LAST_FIELD_NULL ; return null ; } ZoneId zoneId = timeZone . toZoneId ( ) . normalized ( ) ; if ( zoneId instanceof ZoneOffset ) { ZoneOffset zoneOffset = ( ZoneOffset ) zoneId ; String raw = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; switch ( columnInfo . getColumnType ( ) . getSqlType ( ) ) { case Types . TIMESTAMP : if ( raw . startsWith ( "0000-00-00 00:00:00" ) ) { return null ; } try { return ZonedDateTime . parse ( raw , TEXT_LOCAL_DATE_TIME . withZone ( zoneOffset ) ) . toOffsetDateTime ( ) . toOffsetTime ( ) ; } catch ( DateTimeParseException dateParserEx ) { throw new SQLException ( raw + " cannot be parse as OffsetTime. time must have \"yyyy-MM-dd HH:mm:ss[.S]\" format" ) ; } case Types . TIME : try { LocalTime localTime = LocalTime . parse ( raw , DateTimeFormatter . ISO_LOCAL_TIME . withZone ( zoneOffset ) ) ; return OffsetTime . of ( localTime , zoneOffset ) ; } catch ( DateTimeParseException dateParserEx ) { throw new SQLException ( raw + " cannot be parse as OffsetTime (format is \"HH:mm:ss[.S]\" for data type \"" + columnInfo . getColumnType ( ) + "\")" ) ; } case Types . VARCHAR : case Types . LONGVARCHAR : case Types . CHAR : try { return OffsetTime . parse ( raw , DateTimeFormatter . ISO_OFFSET_TIME ) ; } catch ( DateTimeParseException dateParserEx ) { throw new SQLException ( raw + " cannot be parse as OffsetTime (format is \"HH:mm:ss[.S]\" with offset for data type \"" + columnInfo . getColumnType ( ) + "\")" ) ; } default : throw new SQLException ( "Cannot read " + OffsetTime . class . getName ( ) + " using a " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) + " field" ) ; } } if ( options . useLegacyDatetimeCode ) { throw new SQLException ( "Cannot return an OffsetTime for a TIME field when default timezone is '" + zoneId + "' (only possible for time-zone offset from Greenwich/UTC, such as +02:00)" ) ; } throw new SQLException ( "Cannot return an OffsetTime for a TIME field when server timezone '" + zoneId + "' (only possible for time-zone offset from Greenwich/UTC, such as +02:00)" ) ; } | Get OffsetTime format from raw text format . |
29,553 | public LocalTime getInternalLocalTime ( ColumnInformation columnInfo , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } if ( length == 0 ) { lastValueNull |= BIT_LAST_FIELD_NULL ; return null ; } String raw = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; switch ( columnInfo . getColumnType ( ) . getSqlType ( ) ) { case Types . TIME : case Types . VARCHAR : case Types . LONGVARCHAR : case Types . CHAR : try { return LocalTime . parse ( raw , DateTimeFormatter . ISO_LOCAL_TIME . withZone ( timeZone . toZoneId ( ) ) ) ; } catch ( DateTimeParseException dateParserEx ) { throw new SQLException ( raw + " cannot be parse as LocalTime (format is \"HH:mm:ss[.S]\" for data type \"" + columnInfo . getColumnType ( ) + "\")" ) ; } case Types . TIMESTAMP : ZonedDateTime zonedDateTime = getInternalZonedDateTime ( columnInfo , LocalTime . class , timeZone ) ; return zonedDateTime == null ? null : zonedDateTime . withZoneSameInstant ( ZoneId . systemDefault ( ) ) . toLocalTime ( ) ; default : throw new SQLException ( "Cannot read LocalTime using a " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) + " field" ) ; } } | Get LocalTime format from raw text format . |
29,554 | public LocalDate getInternalLocalDate ( ColumnInformation columnInfo , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } if ( length == 0 ) { lastValueNull |= BIT_LAST_FIELD_NULL ; return null ; } String raw = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; switch ( columnInfo . getColumnType ( ) . getSqlType ( ) ) { case Types . DATE : case Types . VARCHAR : case Types . LONGVARCHAR : case Types . CHAR : if ( raw . startsWith ( "0000-00-00" ) ) { return null ; } try { return LocalDate . parse ( raw , DateTimeFormatter . ISO_LOCAL_DATE . withZone ( timeZone . toZoneId ( ) ) ) ; } catch ( DateTimeParseException dateParserEx ) { throw new SQLException ( raw + " cannot be parse as LocalDate (format is \"yyyy-MM-dd\" for data type \"" + columnInfo . getColumnType ( ) + "\")" ) ; } case Types . TIMESTAMP : ZonedDateTime zonedDateTime = getInternalZonedDateTime ( columnInfo , LocalDate . class , timeZone ) ; return zonedDateTime == null ? null : zonedDateTime . withZoneSameInstant ( ZoneId . systemDefault ( ) ) . toLocalDate ( ) ; default : throw new SQLException ( "Cannot read LocalDate using a " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) + " field" ) ; } } | Get LocalDate format from raw text format . |
29,555 | public void connect ( ) throws SQLException { if ( ! isClosed ( ) ) { close ( ) ; } try { connect ( ( currentHost != null ) ? currentHost . host : null , ( currentHost != null ) ? currentHost . port : 3306 ) ; } catch ( IOException ioException ) { throw ExceptionMapper . connException ( "Could not connect to " + currentHost + ". " + ioException . getMessage ( ) + getTraces ( ) , ioException ) ; } } | Connect to currentHost . |
29,556 | private void connect ( String host , int port ) throws SQLException , IOException { try { socket = Utils . createSocket ( urlParser , host ) ; if ( options . socketTimeout != null ) { socket . setSoTimeout ( options . socketTimeout ) ; } initializeSocketOption ( ) ; if ( options . localSocketAddress != null ) { InetSocketAddress localAddress = new InetSocketAddress ( options . localSocketAddress , 0 ) ; socket . bind ( localAddress ) ; } if ( ! socket . isConnected ( ) ) { InetSocketAddress sockAddr = urlParser . getOptions ( ) . pipe == null ? new InetSocketAddress ( host , port ) : null ; if ( options . connectTimeout != 0 ) { socket . connect ( sockAddr , options . connectTimeout ) ; } else { socket . connect ( sockAddr ) ; } } handleConnectionPhases ( host ) ; connected = true ; if ( options . useCompression ) { writer = new CompressPacketOutputStream ( writer . getOutputStream ( ) , options . maxQuerySizeToLog ) ; reader = new DecompressPacketInputStream ( ( ( StandardPacketInputStream ) reader ) . getInputStream ( ) , options . maxQuerySizeToLog ) ; if ( options . enablePacketDebug ) { writer . setTraceCache ( traceCache ) ; reader . setTraceCache ( traceCache ) ; } } boolean mustLoadAdditionalInfo = true ; if ( globalInfo != null ) { if ( globalInfo . isAutocommit ( ) == options . autocommit ) { mustLoadAdditionalInfo = false ; } } if ( mustLoadAdditionalInfo ) { Map < String , String > serverData = new TreeMap < > ( ) ; if ( options . usePipelineAuth && ! options . createDatabaseIfNotExist ) { try { sendPipelineAdditionalData ( ) ; readPipelineAdditionalData ( serverData ) ; } catch ( SQLException sqle ) { if ( "08" . equals ( sqle . getSQLState ( ) ) ) { throw sqle ; } additionalData ( serverData ) ; } } else { additionalData ( serverData ) ; } writer . setMaxAllowedPacket ( Integer . parseInt ( serverData . get ( "max_allowed_packet" ) ) ) ; autoIncrementIncrement = Integer . parseInt ( serverData . get ( "auto_increment_increment" ) ) ; loadCalendar ( serverData . get ( "time_zone" ) , serverData . get ( "system_time_zone" ) ) ; } else { writer . setMaxAllowedPacket ( ( int ) globalInfo . getMaxAllowedPacket ( ) ) ; autoIncrementIncrement = globalInfo . getAutoIncrementIncrement ( ) ; loadCalendar ( globalInfo . getTimeZone ( ) , globalInfo . getSystemTimeZone ( ) ) ; } reader . setServerThreadId ( this . serverThreadId , isMasterConnection ( ) ) ; writer . setServerThreadId ( this . serverThreadId , isMasterConnection ( ) ) ; activeStreamingResult = null ; hostFailed = false ; } catch ( IOException | SQLException ioException ) { ensureClosingSocketOnException ( ) ; throw ioException ; } } | Connect the client and perform handshake . |
29,557 | private void sendPipelineCheckMaster ( ) throws IOException { if ( urlParser . getHaMode ( ) == HaMode . AURORA ) { writer . startPacket ( 0 ) ; writer . write ( COM_QUERY ) ; writer . write ( IS_MASTER_QUERY ) ; writer . flush ( ) ; } } | Send query to identify if server is master . |
29,558 | private void enabledSslCipherSuites ( SSLSocket sslSocket ) throws SQLException { if ( options . enabledSslCipherSuites != null ) { List < String > possibleCiphers = Arrays . asList ( sslSocket . getSupportedCipherSuites ( ) ) ; String [ ] ciphers = options . enabledSslCipherSuites . split ( "[,;\\s]+" ) ; for ( String cipher : ciphers ) { if ( ! possibleCiphers . contains ( cipher ) ) { throw new SQLException ( "Unsupported SSL cipher '" + cipher + "'. Supported ciphers : " + possibleCiphers . toString ( ) . replace ( "[" , "" ) . replace ( "]" , "" ) ) ; } } sslSocket . setEnabledCipherSuites ( ciphers ) ; } } | Set ssl socket cipher according to options . |
29,559 | public boolean versionGreaterOrEqual ( int major , int minor , int patch ) { if ( this . majorVersion > major ) { return true ; } if ( this . majorVersion < major ) { return false ; } if ( this . minorVersion > minor ) { return true ; } if ( this . minorVersion < minor ) { return false ; } return this . patchVersion >= patch ; } | Utility method to check if database version is greater than parameters . |
29,560 | public Buffer process ( PacketOutputStream out , PacketInputStream in , AtomicInteger sequence ) throws IOException { if ( password == null || password . isEmpty ( ) ) { out . writeEmptyPacket ( sequence . incrementAndGet ( ) ) ; } else { out . startPacket ( sequence . incrementAndGet ( ) ) ; byte [ ] bytePwd ; if ( passwordCharacterEncoding != null && ! passwordCharacterEncoding . isEmpty ( ) ) { bytePwd = password . getBytes ( passwordCharacterEncoding ) ; } else { bytePwd = password . getBytes ( ) ; } out . write ( bytePwd ) ; out . write ( 0 ) ; out . flush ( ) ; } Buffer buffer = in . getPacket ( true ) ; sequence . set ( in . getLastPacketSeq ( ) ) ; return buffer ; } | Send password in clear text to server . |
29,561 | public static byte [ ] create ( byte [ ] [ ] rowDatas , ColumnType [ ] columnTypes ) { int totalLength = 0 ; for ( byte [ ] rowData : rowDatas ) { if ( rowData == null ) { totalLength ++ ; } else { int length = rowData . length ; if ( length < 251 ) { totalLength += length + 1 ; } else if ( length < 65536 ) { totalLength += length + 3 ; } else if ( length < 16777216 ) { totalLength += length + 4 ; } else { totalLength += length + 9 ; } } } byte [ ] buf = new byte [ totalLength ] ; int pos = 0 ; for ( byte [ ] arr : rowDatas ) { if ( arr == null ) { buf [ pos ++ ] = ( byte ) 251 ; } else { int length = arr . length ; if ( length < 251 ) { buf [ pos ++ ] = ( byte ) length ; } else if ( length < 65536 ) { buf [ pos ++ ] = ( byte ) 0xfc ; buf [ pos ++ ] = ( byte ) length ; buf [ pos ++ ] = ( byte ) ( length >>> 8 ) ; } else if ( length < 16777216 ) { buf [ pos ++ ] = ( byte ) 0xfd ; buf [ pos ++ ] = ( byte ) length ; buf [ pos ++ ] = ( byte ) ( length >>> 8 ) ; buf [ pos ++ ] = ( byte ) ( length >>> 16 ) ; } else { buf [ pos ++ ] = ( byte ) 0xfe ; buf [ pos ++ ] = ( byte ) length ; buf [ pos ++ ] = ( byte ) ( length >>> 8 ) ; buf [ pos ++ ] = ( byte ) ( length >>> 16 ) ; buf [ pos ++ ] = ( byte ) ( length >>> 24 ) ; pos += 4 ; } System . arraycopy ( arr , 0 , buf , pos , length ) ; pos += length ; } } return buf ; } | Create Buffer with Text protocol values . |
29,562 | public static UrlParser parse ( final String url , Properties prop ) throws SQLException { if ( url != null && ( url . startsWith ( "jdbc:mariadb:" ) || url . startsWith ( "jdbc:mysql:" ) && ! url . contains ( DISABLE_MYSQL_URL ) ) ) { UrlParser urlParser = new UrlParser ( ) ; parseInternal ( urlParser , url , ( prop == null ) ? new Properties ( ) : prop ) ; return urlParser ; } return null ; } | Parse url connection string with additional properties . |
29,563 | private static void parseInternal ( UrlParser urlParser , String url , Properties properties ) throws SQLException { try { urlParser . initialUrl = url ; int separator = url . indexOf ( "//" ) ; if ( separator == - 1 ) { throw new IllegalArgumentException ( "url parsing error : '//' is not present in the url " + url ) ; } urlParser . haMode = parseHaMode ( url , separator ) ; String urlSecondPart = url . substring ( separator + 2 ) ; int dbIndex = urlSecondPart . indexOf ( "/" ) ; int paramIndex = urlSecondPart . indexOf ( "?" ) ; String hostAddressesString ; String additionalParameters ; if ( ( dbIndex < paramIndex && dbIndex < 0 ) || ( dbIndex > paramIndex && paramIndex > - 1 ) ) { hostAddressesString = urlSecondPart . substring ( 0 , paramIndex ) ; additionalParameters = urlSecondPart . substring ( paramIndex ) ; } else if ( ( dbIndex < paramIndex && dbIndex > - 1 ) || ( dbIndex > paramIndex && paramIndex < 0 ) ) { hostAddressesString = urlSecondPart . substring ( 0 , dbIndex ) ; additionalParameters = urlSecondPart . substring ( dbIndex ) ; } else { hostAddressesString = urlSecondPart ; additionalParameters = null ; } defineUrlParserParameters ( urlParser , properties , hostAddressesString , additionalParameters ) ; setDefaultHostAddressType ( urlParser ) ; urlParser . loadMultiMasterValue ( ) ; } catch ( IllegalArgumentException i ) { throw new SQLException ( "error parsing url : " + i . getMessage ( ) , i ) ; } } | Parses the connection URL in order to set the UrlParser instance with all the information provided through the URL . |
29,564 | public UrlParser auroraPipelineQuirks ( ) { boolean disablePipeline = isAurora ( ) ; if ( options . useBatchMultiSend == null ) { options . useBatchMultiSend = disablePipeline ? Boolean . FALSE : Boolean . TRUE ; } if ( options . usePipelineAuth == null ) { options . usePipelineAuth = disablePipeline ? Boolean . FALSE : Boolean . TRUE ; } return this ; } | Permit to set parameters not forced . if options useBatchMultiSend and usePipelineAuth are not explicitly set in connection string value will default to true or false according if aurora detection . |
29,565 | public boolean removeEldestEntry ( Map . Entry eldest ) { boolean mustBeRemoved = this . size ( ) > maxSize ; if ( mustBeRemoved ) { ServerPrepareResult serverPrepareResult = ( ( ServerPrepareResult ) eldest . getValue ( ) ) ; serverPrepareResult . setRemoveFromCache ( ) ; if ( serverPrepareResult . canBeDeallocate ( ) ) { try { protocol . forceReleasePrepareStatement ( serverPrepareResult . getStatementId ( ) ) ; } catch ( SQLException e ) { } } } return mustBeRemoved ; } | Remove eldestEntry . |
29,566 | public synchronized ServerPrepareResult put ( String key , ServerPrepareResult result ) { ServerPrepareResult cachedServerPrepareResult = super . get ( key ) ; if ( cachedServerPrepareResult != null && cachedServerPrepareResult . incrementShareCounter ( ) ) { return cachedServerPrepareResult ; } result . setAddToCache ( ) ; super . put ( key , result ) ; return null ; } | Associates the specified value with the specified key in this map . If the map previously contained a mapping for the key the existing cached prepared result shared counter will be incremented . |
29,567 | public void authenticate ( final PacketOutputStream out , final PacketInputStream in , final AtomicInteger sequence , final String servicePrincipalName , final String mechanisms ) throws IOException { IWindowsSecurityContext clientContext = WindowsSecurityContextImpl . getCurrent ( mechanisms , servicePrincipalName ) ; do { byte [ ] tokenForTheServerOnTheClient = clientContext . getToken ( ) ; out . startPacket ( sequence . incrementAndGet ( ) ) ; out . write ( tokenForTheServerOnTheClient ) ; out . flush ( ) ; if ( clientContext . isContinue ( ) ) { Buffer buffer = in . getPacket ( true ) ; sequence . set ( in . getLastPacketSeq ( ) ) ; byte [ ] tokenForTheClientOnTheServer = buffer . readRawBytes ( buffer . remaining ( ) ) ; Sspi . SecBufferDesc continueToken = new Sspi . SecBufferDesc ( Sspi . SECBUFFER_TOKEN , tokenForTheClientOnTheServer ) ; clientContext . initialize ( clientContext . getHandle ( ) , continueToken , servicePrincipalName ) ; } } while ( clientContext . isContinue ( ) ) ; clientContext . dispose ( ) ; } | Process native windows GSS plugin authentication . |
29,568 | public static void send ( final PacketOutputStream pos ) { try { pos . startPacket ( 0 ) ; pos . write ( Packet . COM_QUIT ) ; pos . flush ( ) ; } catch ( IOException ioe ) { } } | Send close stream to server . |
29,569 | public void flush ( ) throws IOException { flushBuffer ( true ) ; out . flush ( ) ; if ( buf . length > SMALL_BUFFER_SIZE && cmdLength * 2 < buf . length ) { buf = new byte [ SMALL_BUFFER_SIZE ] ; } if ( cmdLength >= maxAllowedPacket ) { throw new MaxAllowedPacketException ( "query size (" + cmdLength + ") is >= to max_allowed_packet (" + maxAllowedPacket + ")" , true ) ; } } | Send packet to socket . |
29,570 | public void checkMaxAllowedLength ( int length ) throws MaxAllowedPacketException { if ( cmdLength + length >= maxAllowedPacket && cmdLength == 0 ) { throw new MaxAllowedPacketException ( "query size (" + ( cmdLength + length ) + ") is >= to max_allowed_packet (" + maxAllowedPacket + ")" , false ) ; } } | Count query size . If query size is greater than max_allowed_packet and nothing has been already send throw an exception to avoid having the connection closed . |
29,571 | public void writeShort ( short value ) throws IOException { if ( 2 > buf . length - pos ) { byte [ ] arr = new byte [ 2 ] ; arr [ 0 ] = ( byte ) value ; arr [ 1 ] = ( byte ) ( value >> 8 ) ; write ( arr , 0 , 2 ) ; return ; } buf [ pos ] = ( byte ) value ; buf [ pos + 1 ] = ( byte ) ( value >> 8 ) ; pos += 2 ; } | Write short value into buffer . flush buffer if too small . |
29,572 | public void writeInt ( int value ) throws IOException { if ( 4 > buf . length - pos ) { byte [ ] arr = new byte [ 4 ] ; arr [ 0 ] = ( byte ) value ; arr [ 1 ] = ( byte ) ( value >> 8 ) ; arr [ 2 ] = ( byte ) ( value >> 16 ) ; arr [ 3 ] = ( byte ) ( value >> 24 ) ; write ( arr , 0 , 4 ) ; return ; } buf [ pos ] = ( byte ) value ; buf [ pos + 1 ] = ( byte ) ( value >> 8 ) ; buf [ pos + 2 ] = ( byte ) ( value >> 16 ) ; buf [ pos + 3 ] = ( byte ) ( value >> 24 ) ; pos += 4 ; } | Write int value into buffer . flush buffer if too small . |
29,573 | public void writeLong ( long value ) throws IOException { if ( 8 > buf . length - pos ) { byte [ ] arr = new byte [ 8 ] ; arr [ 0 ] = ( byte ) value ; arr [ 1 ] = ( byte ) ( value >> 8 ) ; arr [ 2 ] = ( byte ) ( value >> 16 ) ; arr [ 3 ] = ( byte ) ( value >> 24 ) ; arr [ 4 ] = ( byte ) ( value >> 32 ) ; arr [ 5 ] = ( byte ) ( value >> 40 ) ; arr [ 6 ] = ( byte ) ( value >> 48 ) ; arr [ 7 ] = ( byte ) ( value >> 56 ) ; write ( arr , 0 , 8 ) ; return ; } buf [ pos ] = ( byte ) value ; buf [ pos + 1 ] = ( byte ) ( value >> 8 ) ; buf [ pos + 2 ] = ( byte ) ( value >> 16 ) ; buf [ pos + 3 ] = ( byte ) ( value >> 24 ) ; buf [ pos + 4 ] = ( byte ) ( value >> 32 ) ; buf [ pos + 5 ] = ( byte ) ( value >> 40 ) ; buf [ pos + 6 ] = ( byte ) ( value >> 48 ) ; buf [ pos + 7 ] = ( byte ) ( value >> 56 ) ; pos += 8 ; } | Write long value into buffer . flush buffer if too small . |
29,574 | public void writeBytes ( byte value , int len ) throws IOException { if ( len > buf . length - pos ) { byte [ ] arr = new byte [ len ] ; Arrays . fill ( arr , value ) ; write ( arr , 0 , len ) ; return ; } for ( int i = pos ; i < pos + len ; i ++ ) { buf [ i ] = value ; } pos += len ; } | Write byte value len times into buffer . flush buffer if too small . |
29,575 | public void write ( int value ) throws IOException { if ( pos >= buf . length ) { if ( pos >= getMaxPacketLength ( ) && ! bufferContainDataAfterMark ) { flushBuffer ( false ) ; } else { growBuffer ( 1 ) ; } } buf [ pos ++ ] = ( byte ) value ; } | Write byte into buffer flush buffer to socket if needed . |
29,576 | public void write ( byte [ ] arr , int off , int len ) throws IOException { if ( len > buf . length - pos ) { if ( buf . length != getMaxPacketLength ( ) ) { growBuffer ( len ) ; } if ( len > buf . length - pos ) { if ( mark != - 1 ) { growBuffer ( len ) ; if ( mark != - 1 ) { flushBufferStopAtMark ( ) ; } } else { int remainingLen = len ; do { int lenToFillBuffer = Math . min ( getMaxPacketLength ( ) - pos , remainingLen ) ; System . arraycopy ( arr , off , buf , pos , lenToFillBuffer ) ; remainingLen -= lenToFillBuffer ; off += lenToFillBuffer ; pos += lenToFillBuffer ; if ( remainingLen > 0 ) { flushBuffer ( false ) ; } else { break ; } } while ( true ) ; return ; } } } System . arraycopy ( arr , off , buf , pos , len ) ; pos += len ; } | Write byte array to buffer . If buffer is full flush socket . |
29,577 | public void write ( Reader reader , boolean escape , boolean noBackslashEscapes ) throws IOException { char [ ] buffer = new char [ 4096 ] ; int len ; while ( ( len = reader . read ( buffer ) ) >= 0 ) { byte [ ] data = new String ( buffer , 0 , len ) . getBytes ( "UTF-8" ) ; if ( escape ) { writeBytesEscaped ( data , data . length , noBackslashEscapes ) ; } else { write ( data ) ; } } } | Write reader into socket . |
29,578 | public void writeBytesEscaped ( byte [ ] bytes , int len , boolean noBackslashEscapes ) throws IOException { if ( len * 2 > buf . length - pos ) { if ( buf . length != getMaxPacketLength ( ) ) { growBuffer ( len * 2 ) ; } if ( len * 2 > buf . length - pos ) { if ( mark != - 1 ) { growBuffer ( len * 2 ) ; if ( mark != - 1 ) { flushBufferStopAtMark ( ) ; } } else { if ( noBackslashEscapes ) { for ( int i = 0 ; i < len ; i ++ ) { if ( QUOTE == bytes [ i ] ) { buf [ pos ++ ] = QUOTE ; if ( buf . length <= pos ) { flushBuffer ( false ) ; } } buf [ pos ++ ] = bytes [ i ] ; if ( buf . length <= pos ) { flushBuffer ( false ) ; } } } else { for ( int i = 0 ; i < len ; i ++ ) { if ( bytes [ i ] == QUOTE || bytes [ i ] == BACKSLASH || bytes [ i ] == DBL_QUOTE || bytes [ i ] == ZERO_BYTE ) { buf [ pos ++ ] = '\\' ; if ( buf . length <= pos ) { flushBuffer ( false ) ; } } buf [ pos ++ ] = bytes [ i ] ; if ( buf . length <= pos ) { flushBuffer ( false ) ; } } } return ; } } } if ( noBackslashEscapes ) { for ( int i = 0 ; i < len ; i ++ ) { if ( QUOTE == bytes [ i ] ) { buf [ pos ++ ] = QUOTE ; } buf [ pos ++ ] = bytes [ i ] ; } } else { for ( int i = 0 ; i < len ; i ++ ) { if ( bytes [ i ] == QUOTE || bytes [ i ] == BACKSLASH || bytes [ i ] == '"' || bytes [ i ] == ZERO_BYTE ) { buf [ pos ++ ] = BACKSLASH ; } buf [ pos ++ ] = bytes [ i ] ; } } } | Write escape bytes to socket . |
29,579 | public void flushBufferStopAtMark ( ) throws IOException { final int end = pos ; pos = mark ; flushBuffer ( true ) ; out . flush ( ) ; startPacket ( 0 ) ; System . arraycopy ( buf , mark , buf , pos , end - mark ) ; pos += end - mark ; mark = - 1 ; bufferContainDataAfterMark = true ; } | Flush to last mark . |
29,580 | public byte [ ] resetMark ( ) { mark = - 1 ; if ( bufferContainDataAfterMark ) { byte [ ] data = Arrays . copyOfRange ( buf , initialPacketPos ( ) , pos ) ; startPacket ( 0 ) ; bufferContainDataAfterMark = false ; return data ; } return null ; } | Reset mark flag and send bytes after mark flag . |
29,581 | public static DynamicSizedSchedulerInterface getScheduler ( int initialThreadCount , String poolName , int maximumPoolSize ) { return getSchedulerProvider ( ) . getScheduler ( initialThreadCount , poolName , maximumPoolSize ) ; } | Get a Dynamic sized scheduler directly with the current set provider . |
29,582 | public void connect ( SocketAddress endpoint , int timeout ) throws IOException { String filename ; if ( host == null || host . equals ( "localhost" ) ) { filename = "\\\\.\\pipe\\" + name ; } else { filename = "\\\\" + host + "\\pipe\\" + name ; } int usedTimeout = timeout == 0 ? 100 : timeout ; long initialNano = System . nanoTime ( ) ; do { try { file = new RandomAccessFile ( filename , "rw" ) ; break ; } catch ( FileNotFoundException fileNotFoundException ) { try { Kernel32 . INSTANCE . WaitNamedPipe ( filename , timeout ) ; file = new RandomAccessFile ( filename , "rw" ) ; } catch ( Throwable cle ) { if ( System . nanoTime ( ) - initialNano > TimeUnit . MILLISECONDS . toNanos ( usedTimeout ) ) { if ( timeout == 0 ) { throw new FileNotFoundException ( fileNotFoundException . getMessage ( ) + "\nplease consider set connectTimeout option, so connection can retry having access to named pipe. " + "\n(Named pipe can throw ERROR_PIPE_BUSY error)" ) ; } throw fileNotFoundException ; } try { TimeUnit . MILLISECONDS . sleep ( 5 ) ; } catch ( InterruptedException interrupted ) { IOException ioException = new IOException ( "Interruption during connection to named pipe" ) ; ioException . initCause ( interrupted ) ; throw ioException ; } } } } while ( true ) ; is = new InputStream ( ) { public int read ( byte [ ] bytes , int off , int len ) throws IOException { return file . read ( bytes , off , len ) ; } public int read ( ) throws IOException { return file . read ( ) ; } public int read ( byte [ ] bytes ) throws IOException { return file . read ( bytes ) ; } } ; os = new OutputStream ( ) { public void write ( byte [ ] bytes , int off , int len ) throws IOException { file . write ( bytes , off , len ) ; } public void write ( int value ) throws IOException { file . write ( value ) ; } public void write ( byte [ ] bytes ) throws IOException { file . write ( bytes ) ; } } ; } | Name pipe connection . |
29,583 | public void writeTo ( final PacketOutputStream pos ) throws IOException { if ( loadedStream == null ) { writeObjectToBytes ( ) ; } pos . write ( BINARY_INTRODUCER ) ; pos . writeBytesEscaped ( loadedStream , loadedStream . length , noBackSlashEscapes ) ; pos . write ( QUOTE ) ; } | Write object to buffer for text protocol . |
29,584 | public void failover ( int statementId , Protocol unProxiedProtocol ) { this . statementId = statementId ; this . unProxiedProtocol = unProxiedProtocol ; this . parameterTypeHeader = new ColumnType [ parameters . length ] ; this . shareCounter = 1 ; this . isBeingDeallocate = false ; } | Update information after a failover . |
29,585 | public int isNullable ( final int column ) throws SQLException { if ( ( getColumnInformation ( column ) . getFlags ( ) & ColumnFlags . NOT_NULL ) == 0 ) { return ResultSetMetaData . columnNullable ; } else { return ResultSetMetaData . columnNoNulls ; } } | Indicates the nullability of values in the designated column . |
29,586 | public String getTableName ( final int column ) throws SQLException { if ( returnTableAlias ) { return getColumnInformation ( column ) . getTable ( ) ; } else { return getColumnInformation ( column ) . getOriginalTable ( ) ; } } | Gets the designated column s table name . |
29,587 | public int getColumnType ( final int column ) throws SQLException { ColumnInformation ci = getColumnInformation ( column ) ; switch ( ci . getColumnType ( ) ) { case BIT : if ( ci . getLength ( ) == 1 ) { return Types . BIT ; } return Types . VARBINARY ; case TINYINT : if ( ci . getLength ( ) == 1 && options . tinyInt1isBit ) { return Types . BIT ; } return Types . TINYINT ; case YEAR : if ( options . yearIsDateType ) { return Types . DATE ; } return Types . SMALLINT ; case BLOB : if ( ci . getLength ( ) < 0 || ci . getLength ( ) > 16777215 ) { return Types . LONGVARBINARY ; } return Types . VARBINARY ; case VARCHAR : case VARSTRING : if ( ci . isBinary ( ) ) { return Types . VARBINARY ; } if ( ci . getLength ( ) < 0 ) { return Types . LONGVARCHAR ; } return Types . VARCHAR ; case STRING : if ( ci . isBinary ( ) ) { return Types . BINARY ; } return Types . CHAR ; default : return ci . getColumnType ( ) . getSqlType ( ) ; } } | Retrieves the designated column s SQL type . |
29,588 | private static int skipWhite ( char [ ] part , int startPos ) { for ( int i = startPos ; i < part . length ; i ++ ) { if ( ! Character . isWhitespace ( part [ i ] ) ) { return i ; } } return part . length ; } | Return new position or - 1 on error |
29,589 | private String catalogCond ( String columnName , String catalog ) { if ( catalog == null ) { if ( connection . nullCatalogMeansCurrent ) { return "(ISNULL(database()) OR (" + columnName + " = database()))" ; } return "(1 = 1)" ; } if ( catalog . isEmpty ( ) ) { return "(ISNULL(database()) OR (" + columnName + " = database()))" ; } return "(" + columnName + " = " + escapeQuote ( catalog ) + ")" ; } | Generate part of the information schema query that restricts catalog names In the driver catalogs is the equivalent to MariaDB schemas . |
29,590 | public ResultSet getPseudoColumns ( String catalog , String schemaPattern , String tableNamePattern , String columnNamePattern ) throws SQLException { return connection . createStatement ( ) . executeQuery ( "SELECT ' ' TABLE_CAT, ' ' TABLE_SCHEM," + "' ' TABLE_NAME, ' ' COLUMN_NAME, 0 DATA_TYPE, 0 COLUMN_SIZE, 0 DECIMAL_DIGITS," + "10 NUM_PREC_RADIX, ' ' COLUMN_USAGE, ' ' REMARKS, 0 CHAR_OCTET_LENGTH, 'YES' IS_NULLABLE FROM DUAL " + "WHERE 1=0" ) ; } | Retrieves a description of the pseudo or hidden columns available in a given table within the specified catalog and schema . Pseudo or hidden columns may not always be stored within a table and are not visible in a ResultSet unless they are specified in the query s outermost SELECT list . Pseudo or hidden columns may not necessarily be able to be modified . If there are no pseudo or hidden columns an empty ResultSet is returned . |
29,591 | public String getDatabaseProductName ( ) throws SQLException { if ( urlParser . getOptions ( ) . useMysqlMetadata ) { return "MySQL" ; } if ( connection . getProtocol ( ) . isServerMariaDb ( ) && connection . getProtocol ( ) . getServerVersion ( ) . toLowerCase ( Locale . ROOT ) . contains ( "mariadb" ) ) { return "MariaDB" ; } return "MySQL" ; } | Return Server type . MySQL or MariaDB . MySQL can be forced for compatibility with option useMysqlMetadata |
29,592 | public ResultSet getVersionColumns ( String catalog , String schema , String table ) throws SQLException { String sql = "SELECT 0 SCOPE, ' ' COLUMN_NAME, 0 DATA_TYPE," + " ' ' TYPE_NAME, 0 COLUMN_SIZE, 0 BUFFER_LENGTH," + " 0 DECIMAL_DIGITS, 0 PSEUDO_COLUMN " + " FROM DUAL WHERE 1 = 0" ; return executeQuery ( sql ) ; } | Retrieves a description of a table s columns that are automatically updated when any value in a row is updated . They are unordered . |
29,593 | public static SSLSocketFactory getSslSocketFactory ( Options options ) throws SQLException { TrustManager [ ] trustManager = null ; KeyManager [ ] keyManager = null ; if ( options . trustServerCertificate || options . serverSslCert != null || options . trustStore != null ) { trustManager = new X509TrustManager [ ] { new MariaDbX509TrustManager ( options ) } ; } if ( options . keyStore != null ) { keyManager = new KeyManager [ ] { loadClientCerts ( options . keyStore , options . keyStorePassword , options . keyPassword , options . keyStoreType ) } ; } else { String keyStore = System . getProperty ( "javax.net.ssl.keyStore" ) ; String keyStorePassword = System . getProperty ( "javax.net.ssl.keyStorePassword" ) ; if ( keyStore != null ) { try { keyManager = new KeyManager [ ] { loadClientCerts ( keyStore , keyStorePassword , keyStorePassword , options . keyStoreType ) } ; } catch ( SQLException queryException ) { keyManager = null ; logger . error ( "Error loading keymanager from system properties" , queryException ) ; } } } try { SSLContext sslContext = SSLContext . getInstance ( "TLS" ) ; sslContext . init ( keyManager , trustManager , null ) ; return sslContext . getSocketFactory ( ) ; } catch ( KeyManagementException keyManagementEx ) { throw ExceptionMapper . connException ( "Could not initialize SSL context" , keyManagementEx ) ; } catch ( NoSuchAlgorithmException noSuchAlgorithmEx ) { throw ExceptionMapper . connException ( "SSLContext TLS Algorithm not unknown" , noSuchAlgorithmEx ) ; } } | Create an SSL factory according to connection string options . |
29,594 | public void clearBatch ( ) { parameterList . clear ( ) ; hasLongData = false ; this . parameters = new ParameterHolder [ prepareResult . getParamCount ( ) ] ; } | Clear batch . |
29,595 | private void executeInternalBatch ( int size ) throws SQLException { executeQueryPrologue ( true ) ; results = new Results ( this , 0 , true , size , false , resultSetScrollType , resultSetConcurrency , autoGeneratedKeys , protocol . getAutoIncrementIncrement ( ) ) ; if ( protocol . executeBatchClient ( protocol . isMasterConnection ( ) , results , prepareResult , parameterList , hasLongData ) ) { return ; } SQLException exception = null ; if ( queryTimeout > 0 ) { for ( int batchQueriesCount = 0 ; batchQueriesCount < size ; batchQueriesCount ++ ) { protocol . stopIfInterrupted ( ) ; try { protocol . executeQuery ( protocol . isMasterConnection ( ) , results , prepareResult , parameterList . get ( batchQueriesCount ) ) ; } catch ( SQLException e ) { if ( options . continueBatchOnError ) { exception = e ; } else { throw e ; } } } } else { for ( int batchQueriesCount = 0 ; batchQueriesCount < size ; batchQueriesCount ++ ) { try { protocol . executeQuery ( protocol . isMasterConnection ( ) , results , prepareResult , parameterList . get ( batchQueriesCount ) ) ; } catch ( SQLException e ) { if ( options . continueBatchOnError ) { exception = e ; } else { throw e ; } } } } if ( exception != null ) { throw exception ; } } | Choose better way to execute queries according to query and options . |
29,596 | public void setParameter ( final int parameterIndex , final ParameterHolder holder ) throws SQLException { if ( parameterIndex >= 1 && parameterIndex < prepareResult . getParamCount ( ) + 1 ) { parameters [ parameterIndex - 1 ] = holder ; } else { String error = "Could not set parameter at position " + parameterIndex + " (values was " + holder . toString ( ) + ")\n" + "Query - conn:" + protocol . getServerThreadId ( ) + "(" + ( protocol . isMasterConnection ( ) ? "M" : "S" ) + ") " ; if ( options . maxQuerySizeToLog > 0 ) { error += " - \"" ; if ( sqlQuery . length ( ) < options . maxQuerySizeToLog ) { error += sqlQuery ; } else { error += sqlQuery . substring ( 0 , options . maxQuerySizeToLog ) + "..." ; } error += "\"" ; } else { error += " - \"" + sqlQuery + "\"" ; } logger . error ( error ) ; throw ExceptionMapper . getSqlException ( error ) ; } } | Set parameter . |
29,597 | public void close ( ) throws SQLException { super . close ( ) ; if ( connection == null || connection . pooledConnection == null || connection . pooledConnection . noStmtEventListeners ( ) ) { return ; } connection . pooledConnection . fireStatementClosed ( this ) ; connection = null ; } | Close prepared statement maybe fire closed - statement events |
29,598 | public void writeEmptyPacket ( ) throws IOException { buf [ 0 ] = ( byte ) 4 ; buf [ 1 ] = ( byte ) 0x00 ; buf [ 2 ] = ( byte ) 0x00 ; buf [ 3 ] = ( byte ) this . compressSeqNo ++ ; buf [ 4 ] = ( byte ) 0x00 ; buf [ 5 ] = ( byte ) 0x00 ; buf [ 6 ] = ( byte ) 0x00 ; buf [ 7 ] = ( byte ) 0x00 ; buf [ 8 ] = ( byte ) 0x00 ; buf [ 9 ] = ( byte ) 0x00 ; buf [ 10 ] = ( byte ) this . seqNo ++ ; out . write ( buf , 0 , 11 ) ; if ( traceCache != null ) { traceCache . put ( new TraceObject ( true , COMPRESSED_PROTOCOL_NOT_COMPRESSED_PACKET , Arrays . copyOfRange ( buf , 0 , 11 ) ) ) ; } if ( logger . isTraceEnabled ( ) ) { logger . trace ( "send uncompress:{}{}" , serverThreadLog , Utils . hexdump ( maxQuerySizeToLog , 0 , 11 , buf ) ) ; } } | Write an empty packet . |
29,599 | public static AuthenticationPlugin processAuthPlugin ( String plugin , String password , byte [ ] authData , Options options ) throws SQLException { switch ( plugin ) { case MYSQL_NATIVE_PASSWORD : return new NativePasswordPlugin ( password , authData , options . passwordCharacterEncoding ) ; case MYSQL_OLD_PASSWORD : return new OldPasswordPlugin ( password , authData ) ; case MYSQL_CLEAR_PASSWORD : return new ClearPasswordPlugin ( password , options . passwordCharacterEncoding ) ; case DIALOG : return new SendPamAuthPacket ( password , authData , options . passwordCharacterEncoding ) ; case GSSAPI_CLIENT : return new SendGssApiAuthPacket ( authData , options . servicePrincipalName ) ; case MYSQL_ED25519_PASSWORD : return new Ed25519PasswordPlugin ( password , authData , options . passwordCharacterEncoding ) ; default : throw new SQLException ( "Client does not support authentication protocol requested by server. " + "Consider upgrading MariaDB client. plugin was = " + plugin , "08004" , 1251 ) ; } } | Process AuthenticationSwitch . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.