signature:
public class StringUtil { /** * Delimiters like " / / " may span multiple tokens . Look for them and combine them */
private static List < Object > mergeTokens ( List < Object > parsedArray , String endDelimiter ) { } }

implementation: if ( endDelimiter == null ) { return parsedArray ; } List < Object > returnList = new ArrayList < > ( ) ; List < String > possibleMerge = new ArrayList < > ( ) ; for ( Object obj : parsedArray ) { if ( possibleMerge . size ( ) == 0 ) { if ( ( obj instanceof String ) && endDelimiter . startsWith ( ( String ) obj ) ) { possibleMerge . add ( ( String ) obj ) ; } else { returnList . add ( obj ) ; } } else { String possibleMergeString = StringUtil . join ( possibleMerge , "" ) + obj . toString ( ) ; if ( endDelimiter . equals ( possibleMergeString ) ) { returnList . add ( possibleMergeString ) ; possibleMerge . clear ( ) ; } else if ( endDelimiter . startsWith ( possibleMergeString ) ) { possibleMerge . add ( obj . toString ( ) ) ; } else { returnList . addAll ( possibleMerge ) ; returnList . add ( obj ) ; possibleMerge . clear ( ) ; } } } return returnList ;


signature:
public class StringUtil { /** * Returns true if the input is a delimiter in one of the popular RDBMSs . Recognized delimiters are : semicolon ( ; ) ,
 * a slash ( as the only content ) or the word GO ( as the only content ) .
 * @ param piece the input line to test
 * @ param previousPiece the characters in the input stream that came before piece
 * @ param endDelimiter ? ? ? ( need to see this in a debugger to find out ) */
protected static boolean isDelimiter ( String piece , String previousPiece , String endDelimiter ) { } }

implementation: if ( endDelimiter == null ) { return ";" . equals ( piece ) || ( ( "go" . equalsIgnoreCase ( piece ) || "/" . equals ( piece ) ) && ( ( previousPiece == null ) || previousPiece . endsWith ( "\n" ) ) ) ; } else { if ( endDelimiter . length ( ) == 1 ) { return piece . toLowerCase ( ) . equalsIgnoreCase ( endDelimiter . toLowerCase ( ) ) ; } else { return piece . toLowerCase ( ) . matches ( endDelimiter . toLowerCase ( ) ) || ( previousPiece + piece ) . toLowerCase ( ) . matches ( "[\\s\n\r]*" + endDelimiter . toLowerCase ( ) ) ; } }


signature:
public class StringUtil { /** * Splits a candidate multi - line SQL statement along ; ' s and " go " ' s . */
public static String [ ] splitSQL ( String multiLineSQL , String endDelimiter ) { } }

implementation: return processMutliLineSQL ( multiLineSQL , false , true , endDelimiter ) ;


signature:
public class StringUtil { /** * Searches through a String which contains SQL code and strips out
 * any comments that are between \ / * * \ / or anything that matches
 * SP - - SP < text > \ n ( to support the ANSI standard commenting of - -
 * at the end of a line ) .
 * @ return The String without the comments in */
public static String stripComments ( String multiLineSQL ) { } }

implementation: return SqlParser . parse ( multiLineSQL , true , false ) . toString ( ) . trim ( ) ;


signature:
public class StringUtil { /** * Adds spaces to the right of the input value until the string has reached the given length . Nothing is done
 * if the string already has the given length or if the string is even longer .
 * @ param value The string to pad ( if necessary )
 * @ param length the desired length
 * @ return the input string , padded if necessary . */
public static String pad ( String value , int length ) { } }

implementation: value = StringUtil . trimToEmpty ( value ) ; if ( value . length ( ) >= length ) { return value ; } return value + StringUtil . repeat ( " " , length - value . length ( ) ) ;


signature:
public class StringUtil { /** * Adds spaces to the left of the input value until the string has reached the given length . Nothing is done
 * if the string already has the given length or if the string is even longer .
 * @ param value The string to pad ( if necessary )
 * @ param length the desired length
 * @ return the input string , padded if necessary . */
public static String leftPad ( String value , int length ) { } }

implementation: value = StringUtil . trimToEmpty ( value ) ; if ( value . length ( ) >= length ) { return value ; } return StringUtil . repeat ( " " , length - value . length ( ) ) + value ;


signature:
public class StringUtil { /** * Checks if < code > value < / code > starts with < code > startsWith < / code > .
 * @ param value
 * @ param startsWith
 * @ return true if < code > value < / code > starts with < code > startsWith < / code > , otherwise false . If any of arguments is null returns false */
public static boolean startsWith ( String value , String startsWith ) { } }

implementation: if ( ( value == null ) || ( startsWith == null ) ) { return false ; } return value . startsWith ( startsWith ) ;


signature:
public class StringUtil { /** * Returns true if the given string only consists of whitespace characters ( null - safe )
 * @ param string the string to test
 * @ return true if the string is null or only consists of whitespaces . */
public static boolean isWhitespace ( CharSequence string ) { } }

implementation: if ( string == null ) { return true ; } return StringUtil . trimToNull ( string . toString ( ) ) == null ;


signature:
public class StringUtil { /** * Compares a minimum version number given in string form ( only the first three parts are considered ) with a
 * candidate version given as the three ints major , minor and patch .
 * @ param minimumVersion The minimum version that is required , given as a string with up to 3 parts , e . g . " 7.4 " or " 9.6.3"
 * @ param candidateMajor the version number to be tested , major part
 * @ param candidateMinor the version number to be tested , minor part
 * @ param candidatePatch the version number to be tested , patch part
 * @ return true if candidateMajor . candidateMinor . candidatePatch > = minimumVersion or false if not */
public static boolean isMinimumVersion ( String minimumVersion , int candidateMajor , int candidateMinor , int candidatePatch ) { } }

implementation: String [ ] parts = minimumVersion . split ( "\\." , 3 ) ; int minMajor = Integer . parseInt ( parts [ 0 ] ) ; int minMinor = ( parts . length > 1 ) ? Integer . parseInt ( parts [ 1 ] ) : 0 ; int minPatch = ( parts . length > 2 ) ? Integer . parseInt ( parts [ 2 ] ) : 0 ; if ( minMajor > candidateMajor ) { return false ; } if ( ( minMajor == candidateMajor ) && ( minMinor > candidateMinor ) ) { return false ; } return ! ( ( minMajor == candidateMajor ) && ( minMinor == candidateMinor ) && ( minPatch > candidatePatch ) ) ;


signature:
public class StringUtil { /** * Produce a random identifer of the given length , consisting only of uppercase letters .
 * @ param len desired length of the string
 * @ return an identifier of the desired length */
public static String randomIdentifer ( int len ) { } }

implementation: final String AB = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ; StringBuilder sb = new StringBuilder ( len ) ; for ( int i = 0 ; i < len ; i ++ ) sb . append ( AB . charAt ( rnd . nextInt ( AB . length ( ) ) ) ) ; return sb . toString ( ) ;


signature:
public class StringUtil { /** * Returns if two strings are equal , ignoring :
 * < ul >
 * < li > case ( uppercase / lowercase ) < / li >
 * < li > difference between null , and empty string , and a string that only has spaces < / li >
 * < / ul >
 * @ param s1 the first String to compare ( or null )
 * @ param s2 the second String to compare ( or null )
 * @ return true if the Strings are equal by the above criteria , false in all other cases */
public static boolean equalsIgnoreCaseAndEmpty ( String s1 , String s2 ) { } }

implementation:
String clean1 = trimToNull ( s1 ) ; String clean2 = trimToNull ( s2 ) ; if ( clean1 == null && clean2 == null ) { return true ; } else { // Both cannot be null at this point
if ( clean1 == null || clean2 == null ) { return false ; } } return clean1 . equalsIgnoreCase ( clean2 ) ;


signature:
public class StringUtil { /** * Trims { @ link Character # isWhitespace ( char ) whitespace } characters from the
 * end of specified < code > string < / code >
 * @ param string String to trim
 * @ return new String without the whitespace at the end */
public static String trimRight ( String string ) { } }

implementation: int i = string . length ( ) - 1 ; while ( i >= 0 && Character . isWhitespace ( string . charAt ( i ) ) ) { i -- ; } return string . substring ( 0 , i + 1 ) ;


signature:
public class StringUtil { /** * Strips the comments and whitespaces from the end of given sql string .
 * @ param sqlString
 * @ return */
public static String stripSqlCommentsAndWhitespacesFromTheEnd ( String sqlString ) { } }

implementation:
if ( isEmpty ( sqlString ) ) { return sqlString ; } StringBuilder str = new StringBuilder ( sqlString ) ; boolean strModified = true ; while ( strModified ) { strModified = false ; // first check for last block comment
// since line comments could be inside block comments , we want to
// remove them first .
String lastBlockComment = getLastBlockComment ( str . toString ( ) ) ; if ( isNotEmpty ( lastBlockComment ) ) { str . setLength ( str . length ( ) - lastBlockComment . length ( ) ) ; // we just modified the end of the string ,
// do another loop to check for next block or line comments
strModified = true ; } // now check for the line comments
String lastLineComment = getLastLineComment ( str . toString ( ) ) ; if ( isNotEmpty ( lastLineComment ) ) { str . setLength ( str . length ( ) - lastLineComment . length ( ) ) ; // we just modified the end of the string ,
// do another loop to check for next block or line comments
strModified = true ; } } return trimRight ( str . toString ( ) ) ;


signature:
public class StringUtil { /** * Concatenates the addition string to the baseString string , adjusting the case of " addition " to match the base string .
 * If the string is all caps , append addition in all caps . If all lower case , append in all lower case . If baseString is mixed case , make no changes to addition . */
public static String concatConsistentCase ( String baseString , String addition ) { } }

implementation:
boolean hasLowerCase = hasLowerCase ( baseString ) ; boolean hasUpperCase = hasUpperCase ( baseString ) ; if ( ( hasLowerCase && hasUpperCase ) || ( ! hasLowerCase && ! hasUpperCase ) ) { // mixed case | | no letters
return baseString + addition ; } else if ( hasLowerCase ) { return baseString + addition . toLowerCase ( ) ; } else { return baseString + addition . toUpperCase ( ) ; }


signature:
public class DatabaseSnapshot { /** * Include the object described by the passed example object in this snapshot . Returns the object snapshot or null
 * if the object does not exist in the database . If the same object was returned by an earlier include ( ) call ,
 * the same object instance will be returned . */
protected < T extends DatabaseObject > T include ( T example ) throws DatabaseException , InvalidExampleException { } }

implementation: if ( example == null ) { return null ; } if ( database . isSystemObject ( example ) ) { return null ; } if ( ( example instanceof Schema ) && ( example . getName ( ) == null ) && ( ( ( ( Schema ) example ) . getCatalog ( ) == null ) || ( ( ( Schema ) example ) . getCatalogName ( ) == null ) ) ) { CatalogAndSchema catalogAndSchema = ( ( Schema ) example ) . toCatalogAndSchema ( ) . customize ( database ) ; example = ( T ) new Schema ( catalogAndSchema . getCatalogName ( ) , catalogAndSchema . getSchemaName ( ) ) ; } if ( ! snapshotControl . shouldInclude ( example ) ) { LOGGER . fine ( LogType . LOG , "Excluding " + example ) ; return example ; } T existing = get ( example ) ; if ( existing != null ) { return existing ; } if ( isKnownNull ( example ) ) { return null ; } SnapshotListener snapshotListener = snapshotControl . getSnapshotListener ( ) ; SnapshotGeneratorChain chain = createGeneratorChain ( example . getClass ( ) , database ) ; if ( snapshotListener != null ) { snapshotListener . willSnapshot ( example , database ) ; } T object = chain . snapshot ( example , this ) ; if ( object == null ) { Set < DatabaseObject > collection = knownNull . get ( example . getClass ( ) ) ; if ( collection == null ) { collection = new HashSet < > ( ) ; knownNull . put ( example . getClass ( ) , collection ) ; } collection . add ( example ) ; if ( example instanceof Schema ) { if ( snapshotControl . isWarnIfObjectNotFound ( ) ) Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . warning ( LogType . LOG , "Did not find schema '" + example + "' to snapshot" ) ; } if ( example instanceof Catalog ) { if ( snapshotControl . isWarnIfObjectNotFound ( ) ) Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . warning ( LogType . LOG , "Did not find catalog '" + example + "' to snapshot" ) ; } } else { allFound . add ( object ) ; try { includeNestedObjects ( object ) ; } catch ( ReflectiveOperationException e ) { throw new UnexpectedLiquibaseException ( e ) ; } } if ( snapshotListener != null ) { snapshotListener . finishedSnapshot ( example , object , database ) ; } return object ;


signature:
public class DatabaseSnapshot { /** * Returns the object described by the passed example if it is already included in this snapshot . */
public < DatabaseObjectType extends DatabaseObject > DatabaseObjectType get ( DatabaseObjectType example ) { } }

implementation: return allFound . get ( example , schemaComparisons ) ;


signature:
public class DatabaseSnapshot { /** * Returns all objects of the given type that are already included in this snapshot . */
public < DatabaseObjectType extends DatabaseObject > Set < DatabaseObjectType > get ( Class < DatabaseObjectType > type ) { } }

implementation: return allFound . get ( type ) ;


signature:
public class TimestampType { /** * Returns a DBMS - specific String representation of this TimestampType for use in SQL statements .
 * @ param database the database for which the String must be generated
 * @ return a String with the DBMS - specific type specification */
@ Override public DatabaseDataType toDatabaseDataType ( Database database ) { } }

implementation:
String originalDefinition = StringUtil . trimToEmpty ( getRawDefinition ( ) ) ; // If a fractional precision is given , check is the DBMS supports the length
if ( getParameters ( ) . length > 0 ) { Integer desiredLength = null ; try { desiredLength = Integer . parseInt ( String . valueOf ( getParameters ( ) [ 0 ] ) ) ; } catch ( NumberFormatException e ) { // That is ok , we won ' t touch the parameter in this case .
} if ( desiredLength != null ) { int maxFractionalDigits = database . getMaxFractionalDigitsForTimestamp ( ) ; if ( maxFractionalDigits < desiredLength ) { throw new DatabaseIncapableOfOperation ( String . format ( "Using a TIMESTAMP data type with a fractional precision of %d" , desiredLength ) , String . format ( "A timestamp datatype with %d fractional digits was requested, but %s " + "only supports %d digits." , desiredLength , database . getDatabaseProductName ( ) , maxFractionalDigits ) , database ) ; } } } if ( database instanceof MySQLDatabase ) { if ( originalDefinition . contains ( " " ) || originalDefinition . contains ( "(" ) ) { return new DatabaseDataType ( getRawDefinition ( ) ) ; } return super . toDatabaseDataType ( database ) ; } if ( database instanceof MSSQLDatabase ) { if ( ! LiquibaseConfiguration . getInstance ( ) . getProperty ( GlobalConfiguration . class , GlobalConfiguration . CONVERT_DATA_TYPES ) . getValue ( Boolean . class ) && originalDefinition . toLowerCase ( Locale . US ) . startsWith ( "timestamp" ) ) { return new DatabaseDataType ( database . escapeDataTypeName ( "timestamp" ) ) ; } return new DatabaseDataType ( database . escapeDataTypeName ( "datetime" ) ) ; } if ( database instanceof SybaseDatabase ) { return new DatabaseDataType ( database . escapeDataTypeName ( "datetime" ) ) ; } if ( database instanceof AbstractDb2Database ) { Object [ ] parameters = getParameters ( ) ; if ( ( parameters != null ) && ( parameters . length > 1 ) ) { parameters = new Object [ ] { parameters [ 1 ] } ; } return new DatabaseDataType ( database . escapeDataTypeName ( "timestamp" ) , parameters ) ; } /* * From here on , we assume that we have a SQL standard compliant database that supports the
 * TIMESTAMP [ ( p ) ] [ WITH TIME ZONE | WITHOUT TIME ZONE ] syntax . p is the number of fractional digits ,
 * i . e . if " 2017-06-02 23:59:45.123456 " is supported by the DBMS , p would be 6. */
DatabaseDataType type ; if ( getParameters ( ) . length > 0 ) { int fractionalDigits = 0 ; String fractionalDigitsInput = getParameters ( ) [ 0 ] . toString ( ) ; try { fractionalDigits = Integer . parseInt ( fractionalDigitsInput ) ; } catch ( NumberFormatException e ) { throw new RuntimeException ( new ParseException ( String . format ( "A timestamp with '%s' fractional digits was requested, but '%s' does not " + "seem to be an integer." , fractionalDigitsInput , fractionalDigitsInput ) ) ) ; } int maxFractionalDigits = database . getMaxFractionalDigitsForTimestamp ( ) ; if ( maxFractionalDigits < fractionalDigits ) { Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . warning ( LogType . LOG , String . format ( "A timestamp datatype with %d fractional digits was requested, but the DBMS %s only supports " + "%d digits. Because of this, the number of digits was reduced to %d." , fractionalDigits , database . getDatabaseProductName ( ) , maxFractionalDigits , maxFractionalDigits ) ) ; fractionalDigits = maxFractionalDigits ; } type = new DatabaseDataType ( "TIMESTAMP" , fractionalDigits ) ; } else { type = new DatabaseDataType ( "TIMESTAMP" ) ; } if ( getAdditionalInformation ( ) != null && ( database instanceof PostgresDatabase || database instanceof OracleDatabase ) || database instanceof H2Database || database instanceof HsqlDatabase ) { String additionalInformation = this . getAdditionalInformation ( ) ; if ( additionalInformation != null ) { String additionInformation = additionalInformation . toUpperCase ( Locale . US ) ; if ( ( database instanceof PostgresDatabase ) && additionInformation . toUpperCase ( Locale . US ) . contains ( "TIMEZONE" ) ) { additionalInformation = additionInformation . toUpperCase ( Locale . US ) . replace ( "TIMEZONE" , "TIME ZONE" ) ; } // CORE - 3229 Oracle 11g doesn ' t support WITHOUT clause in TIMESTAMP data type
if ( ( database instanceof OracleDatabase ) && additionInformation . startsWith ( "WITHOUT" ) ) { // https : / / docs . oracle . com / cd / B19306_01 / server . 102 / b14225 / ch4datetime . htm # sthref389
additionalInformation = null ; } if ( ( database instanceof H2Database ) && additionInformation . startsWith ( "WITHOUT" ) ) { // http : / / www . h2database . com / html / datatypes . html
additionalInformation = null ; } } type . addAdditionalInformation ( additionalInformation ) ; return type ; } return super . toDatabaseDataType ( database ) ;


signature:
public class MySQLDatabase { /** * Tests if this MySQL / MariaDB database has a bug where the JDBC driver returns constraints as
 * DEFERRABLE INITIAL IMMEDIATE even though neither MySQL nor MariaDB support DEFERRABLE CONSTRAINTs at all .
 * We need to know about this because this could lead to errors in database snapshots .
 * @ return true if this database is affected , false if not , null if we cannot tell ( e . g . OfflineConnection ) */
@ SuppressWarnings ( "squid:S2447" ) // null is explicitly documented as a possible return value .
// TODO : MariaDB connector 2.0.2 appearantly fixes this problem , and MySQL - ConnectorJ 6.0.6 did not have it in
// the first place . . Replace this crude workaround with a proper JDBC driver version check
public Boolean hasBugJdbcConstraintsDeferrable ( ) throws DatabaseException { } }

implementation:
if ( getConnection ( ) instanceof OfflineConnection ) return null ; if ( getHasJdbcConstraintDeferrableBug ( ) != null ) // cached value
return getHasJdbcConstraintDeferrableBug ( ) ; String randomIdentifier = "TMP_" + StringUtil . randomIdentifer ( 16 ) ; try { // Get the real connection and metadata reference
java . sql . Connection conn = ( ( JdbcConnection ) getConnection ( ) ) . getUnderlyingConnection ( ) ; java . sql . DatabaseMetaData metaData = conn . getMetaData ( ) ; String sql = "CREATE TABLE " + randomIdentifier + " (\n" + "  id INT PRIMARY KEY,\n" + "  self_ref INT NOT NULL,\n" + "  CONSTRAINT c_self_ref FOREIGN KEY(self_ref) REFERENCES " + randomIdentifier + "(id)\n" + ")" ; ExecutorService . getInstance ( ) . getExecutor ( this ) . execute ( new RawSqlStatement ( sql ) ) ; try ( ResultSet rs = metaData . getImportedKeys ( getDefaultCatalogName ( ) , getDefaultSchemaName ( ) , randomIdentifier ) ) { if ( ! rs . next ( ) ) { throw new UnexpectedLiquibaseException ( "Error during testing for MySQL/MariaDB JDBC driver bug: " + "could not retrieve JDBC metadata information for temporary table '" + randomIdentifier + "'" ) ; } if ( rs . getShort ( "DEFERRABILITY" ) != DatabaseMetaData . importedKeyNotDeferrable ) { setHasJdbcConstraintDeferrableBug ( true ) ; Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . warning ( LogType . LOG , "Your MySQL/MariaDB database JDBC driver might have " + "a bug where constraints are reported as DEFERRABLE, even though MySQL/MariaDB do not " + "support this feature. A workaround for this problem will be used. Please check with " + "MySQL/MariaDB for availability of fixed JDBC drivers to avoid this warning." ) ; } else { setHasJdbcConstraintDeferrableBug ( false ) ; } } } catch ( DatabaseException | SQLException e ) { throw new UnexpectedLiquibaseException ( "Error during testing for MySQL/MariaDB JDBC driver bug." , e ) ; } finally { ExecutorService . getInstance ( ) . reset ( ) ; ExecutorService . getInstance ( ) . getExecutor ( this ) . execute ( new RawSqlStatement ( "DROP TABLE " + randomIdentifier ) ) ; } return getHasJdbcConstraintDeferrableBug ( ) ;


signature:
public class JdbcSnapshotGenerator { /** * Fetches an array of Strings with the catalog names in the database .
 * @ param database The database from which to get the schema names
 * @ return An array of catalog name Strings ( May be an empty array )
 * @ throws SQLException propagated java . sql . SQLException
 * @ throws DatabaseException if a different problem occurs during the DBMS - specific code */
protected String [ ] getDatabaseCatalogNames ( Database database ) throws SQLException , DatabaseException { } }

implementation: List < String > returnList = new ArrayList < > ( ) ; ResultSet catalogs = null ; try { if ( ( ( AbstractJdbcDatabase ) database ) . jdbcCallsCatalogsSchemas ( ) ) { catalogs = ( ( JdbcConnection ) database . getConnection ( ) ) . getMetaData ( ) . getSchemas ( ) ; } else { catalogs = ( ( JdbcConnection ) database . getConnection ( ) ) . getMetaData ( ) . getCatalogs ( ) ; } while ( catalogs . next ( ) ) { if ( ( ( AbstractJdbcDatabase ) database ) . jdbcCallsCatalogsSchemas ( ) ) { returnList . add ( catalogs . getString ( "TABLE_SCHEM" ) ) ; } else { returnList . add ( catalogs . getString ( "TABLE_CAT" ) ) ; } } } finally { if ( catalogs != null ) { try { catalogs . close ( ) ; } catch ( SQLException ignore ) { } } } return returnList . toArray ( new String [ returnList . size ( ) ] ) ;


signature:
public class AbstractDb2Database { /** * Return an DB2 date literal with the same value as a string formatted using ISO 8601.
 * Convert an ISO8601 date string to one of the following results :
 * to _ date ( ' 1995-05-23 ' , ' YYYY - MM - DD ' )
 * to _ date ( ' 1995-05-23 09:23:59 ' , ' YYYY - MM - DD HH24 : MI : SS ' )
 * Implementation restriction :
 * Currently , only the following subsets of ISO8601 are supported :
 * YYYY - MM - DD
 * hh : mm : ss
 * YYYY - MM - DDThh : mm : ss */
@ Override public String getDateLiteral ( String isoDate ) { } }

implementation: String normalLiteral = super . getDateLiteral ( isoDate ) ; if ( isDateOnly ( isoDate ) ) { StringBuffer val = new StringBuffer ( ) ; val . append ( "DATE(" ) ; val . append ( normalLiteral ) ; val . append ( ')' ) ; return val . toString ( ) ; } else if ( isTimeOnly ( isoDate ) ) { StringBuffer val = new StringBuffer ( ) ; val . append ( "TIME(" ) ; val . append ( normalLiteral ) ; val . append ( ')' ) ; return val . toString ( ) ; } else if ( isDateTime ( isoDate ) ) { StringBuffer val = new StringBuffer ( ) ; val . append ( "TIMESTAMP(" ) ; val . append ( normalLiteral ) ; val . append ( ')' ) ; return val . toString ( ) ; } else { return "UNSUPPORTED:" + isoDate ; }


signature:
public class CatalogAndSchema { /** * This method returns a new CatalogAndSchema adjusted based on the configuration of the passed database .
 * If the database does not support schemas , the returned object will have a null schema .
 * If the database does not support catalogs , the returned object will have a null catalog .
 * If either the schema or catalog matches the database default catalog or schema , they will be nulled out .
 * Catalog and / or schema names will be upper case unless the database violates the SQL standard by being
 * case - sensitive about some or all unquoted identifiers .
 * @ see CatalogAndSchema # customize ( liquibase . database . Database ) */
public CatalogAndSchema standardize ( Database accordingTo ) { } }

implementation:
String workCatalogName = StringUtil . trimToNull ( getCatalogName ( ) ) ; String workSchemaName = StringUtil . trimToNull ( getSchemaName ( ) ) ; if ( ! accordingTo . supportsCatalogs ( ) ) { return new CatalogAndSchema ( null , null ) ; } if ( accordingTo . supportsSchemas ( ) ) { if ( ( workSchemaName != null ) && workSchemaName . equalsIgnoreCase ( accordingTo . getDefaultSchemaName ( ) ) ) { workSchemaName = null ; } } else { if ( ( workCatalogName == null ) && ( workSchemaName != null ) ) { // had names in the wrong order
workCatalogName = workSchemaName ; } workSchemaName = workCatalogName ; } if ( workCatalogName != null && equals ( accordingTo , workCatalogName , accordingTo . getDefaultCatalogName ( ) ) ) { workCatalogName = null ; } if ( workSchemaName != null && equals ( accordingTo , workSchemaName , accordingTo . getDefaultSchemaName ( ) ) ) { workSchemaName = null ; } if ( ! accordingTo . supportsSchemas ( ) && ( workCatalogName != null ) && ( workSchemaName != null ) && ! workCatalogName . equals ( workSchemaName ) ) { workSchemaName = null ; } if ( CatalogAndSchemaCase . LOWER_CASE . equals ( accordingTo . getSchemaAndCatalogCase ( ) ) ) { if ( workCatalogName != null ) { workCatalogName = workCatalogName . toLowerCase ( Locale . US ) ; } if ( workSchemaName != null ) { workSchemaName = workSchemaName . toLowerCase ( Locale . US ) ; } } else if ( CatalogAndSchemaCase . UPPER_CASE . equals ( accordingTo . getSchemaAndCatalogCase ( ) ) ) { if ( ! accordingTo . isCaseSensitive ( ) ) { if ( workCatalogName != null ) { workCatalogName = workCatalogName . toUpperCase ( Locale . US ) ; } if ( workSchemaName != null ) { workSchemaName = workSchemaName . toUpperCase ( Locale . US ) ; } } } return new CatalogAndSchema ( workCatalogName , workSchemaName ) ;


signature:
public class CatalogAndSchema { /** * Returns a new CatalogAndSchema object with null / default catalog and schema names set to the
 * correct default catalog and schema . If the database does not support catalogs or schemas they will
 * retain a null value .
 * Catalog and schema capitalization will match what the database expects .
 * @ see CatalogAndSchema # standardize ( liquibase . database . Database ) */
public CatalogAndSchema customize ( Database accordingTo ) { } }

implementation: CatalogAndSchema standard = standardize ( accordingTo ) ; String workCatalogName = standard . getCatalogName ( ) ; String workSchemaName = standard . getSchemaName ( ) ; if ( workCatalogName == null ) { if ( ! accordingTo . supportsSchemas ( ) && ( workSchemaName != null ) ) { return new CatalogAndSchema ( accordingTo . correctObjectName ( workSchemaName , Catalog . class ) , null ) ; } workCatalogName = accordingTo . getDefaultCatalogName ( ) ; } if ( workSchemaName == null ) { workSchemaName = accordingTo . getDefaultSchemaName ( ) ; } if ( workCatalogName != null ) { workCatalogName = accordingTo . correctObjectName ( workCatalogName , Catalog . class ) ; } if ( workSchemaName != null ) { workSchemaName = accordingTo . correctObjectName ( workSchemaName , Schema . class ) ; } return new CatalogAndSchema ( workCatalogName , workSchemaName ) ;


signature:
public class SmartMap { /** * Return the value for the given key converted to the passed type . If the value associated with the key is null , null is returned .
 * If the stored value is different than the passed type , a conversion is attempted using { @ link ObjectUtil # convert ( Object , Class ) } .
 * Any conversion is done only on the return value . The stored value is unchanged . */
public < T > T get ( String key , Class < T > type ) { } }

implementation: return ( T ) ObjectUtil . convert ( values . get ( key ) , type ) ;


signature:
public class SmartMap { /** * Return the value for the given key converted to the type of the default value .
 * If the value is null , defaultValue is returned .
 * Conversion is done using { @ link # get ( String , Class ) } */
public < T > T get ( String key , T defaultValue ) { } }

implementation: Class type ; if ( defaultValue == null ) { type = Object . class ; } else { type = defaultValue . getClass ( ) ; } Object value = get ( key , type ) ; if ( value == null ) { return defaultValue ; } return ( T ) value ;


signature:
public class SmartMap { /** * Like normal { @ link Map # put ( Object , Object ) } operation , but if null is passed as " value " it removes the key / value from the map . */
@ Override public Object put ( String key , Object value ) { } }

implementation: if ( value == null ) { return values . remove ( key ) ; } else { return values . put ( key , value ) ; }


signature:
public class WebSpherePackageScanClassResolver { /** * Overloaded to handle specific problem with getting resources on the IBM WebSphere platform .
 * WebSphere can < b > not < / b > load resources if the resource to load is a folder name , such as a
 * packagename , you have to explicit name a resource that is a file .
 * @ param loader the classloader
 * @ param packageName the packagename for the package to load
 * @ return URL ' s for the given package
 * @ throws java . io . IOException is thrown by the classloader */
@ Override protected Enumeration < URL > getResources ( ClassLoader loader , String packageName ) throws IOException { } }

implementation:
// try super first , just in vase
Enumeration < URL > enumeration = super . getResources ( loader , packageName ) ; if ( ! enumeration . hasMoreElements ( ) ) { log . fine ( LogType . LOG , "Using WebSphere workaround to load the camel jars with the annotated converters." ) ; // Special WebSphere trick to load a file that exists in the JAR and then let it go from there .
// The trick is that we just need the URL ' s for the . jars that contains the type
// converters that is annotated . So by searching for this resource WebSphere is able to find
// it and return the URL to the . jar file with the resource . Then the DefaultPackageScanClassResolver
// can take it from there and find the classes that are annotated .
enumeration = loader . getResources ( resourcePath ) ; } return enumeration ;


signature:
public class StringClauses { /** * Returns the key if it is not empty and / or not already used . If it is already used , it generates a random value for the key . */
private String uniqueKey ( String key ) { } }

implementation: boolean generateOne = false ; key = StringUtil . trimToNull ( key ) ; if ( key == null ) { generateOne = true ; } else if ( clauses . containsKey ( key . toLowerCase ( ) ) ) { generateOne = true ; } while ( generateOne ) { key = StringUtil . leftPad ( new BigInteger ( 50 , random ) . toString ( 32 ) , 6 ) . replace ( " " , "0" ) . substring ( 0 , 6 ) ; generateOne = clauses . containsKey ( key ) ; } return key ;


signature:
public class StringClauses { /** * Adds a new clause at the end of the list with the given key . */
public StringClauses append ( String key , String clause ) { } }

implementation: Validate . notNull ( StringUtil . trimToNull ( key ) , "key must be a non-null, non-empty value" ) ; key = StringUtil . trimToEmpty ( key ) . toLowerCase ( ) ; clause = StringUtil . trimToEmpty ( clause ) ; if ( clauses . containsKey ( key ) ) { throw new IllegalArgumentException ( "Cannot add clause with key '" + key + "' because it is already defined" ) ; } clauses . put ( key , clause . trim ( ) ) ; return this ;


signature:
public class StringClauses { /** * Adds a new sub - clause at the end of the list with the given key . */
public StringClauses append ( String key , StringClauses subclauses ) { } }

implementation: Validate . notNull ( StringUtil . trimToNull ( key ) , "key must be a non-null, non-empty value" ) ; key = StringUtil . trimToEmpty ( key ) . toLowerCase ( ) ; if ( clauses . containsKey ( key ) ) { throw new IllegalArgumentException ( "Cannot add clause with key '" + key + "' because it is already defined" ) ; } clauses . put ( key , subclauses ) ; return this ;


signature:
public class StringClauses { /** * Convenience method for { @ link # append ( String , StringClauses ) } when using enums . */
public StringClauses append ( Enum name , StringClauses subclauses ) { } }

implementation: return this . append ( name . name ( ) , subclauses ) ;


signature:
public class StringClauses { /** * Convenience method for { @ link # append ( String , String ) } when using enums . */
public StringClauses append ( Enum name , String clause ) { } }

implementation: return this . append ( name . name ( ) , clause ) ;


signature:
public class StringClauses { /** * Adds a clause with the given key to the beginning of the list . */
public StringClauses prepend ( String key , String clause ) { } }

implementation: return prependImpl ( key , StringUtil . trimToEmpty ( clause ) ) ;


signature:
public class StringClauses { /** * Convenience method for { @ link # prepend ( String , String ) } that uses the clause as the key . */
public StringClauses prepend ( String clause ) { } }

implementation: if ( StringUtil . trimToNull ( clause ) == null ) { return prepend ( new Whitespace ( clause ) ) ; } return prepend ( uniqueKey ( clause ) , clause ) ;


signature:
public class StringClauses { /** * Convenience method for { @ link # prepend ( String , String ) } when using enums */
public StringClauses prepend ( Enum key , String clause ) { } }

implementation: return prepend ( key . name ( ) , clause ) ;


signature:
public class StringClauses { /** * Replaces the given key with a new string . If the existing key does not exist , throws IllegalArgumentException */
public StringClauses replace ( String key , String newValue ) throws IllegalArgumentException { } }

implementation: return replaceImpl ( key , StringUtil . trimToEmpty ( newValue ) ) ;


signature:
public class StringClauses { /** * Replaces the given key with a new string . If the existing key does not exist , throws IllegalArgumentException */
public StringClauses replaceIfExists ( String key , String newValue ) throws IllegalArgumentException { } }

implementation: if ( contains ( key ) ) { return replaceImpl ( key , StringUtil . trimToEmpty ( newValue ) ) ; } else { return this ; }


signature:
public class StringClauses { /** * Convenience method for { @ link # replace ( String , liquibase . util . StringClauses ) } when using enums . */
public StringClauses replace ( Enum key , StringClauses newValue ) { } }

implementation: return replace ( key . name ( ) , newValue ) ;


signature:
public class StringClauses { /** * Inserts a new clause before the given key . Throws IllegalArgumentException if the existingKey does not exist . */
public StringClauses insertBefore ( String existingKey , String newKey , String newValue ) throws IllegalArgumentException { } }

implementation: return insertBeforeImpl ( existingKey , newKey , newValue ) ;


signature:
public class StringClauses { /** * Convenience method for { @ link # insertBefore ( String , String , String ) } where the new clause key is equal to the newValue . */
public StringClauses insertBefore ( String existingKey , String newValue ) { } }

implementation: return insertBefore ( existingKey , newValue , StringUtil . trimToNull ( newValue ) ) ;


signature:
public class StringClauses { /** * Convenience method for { @ link # insertBefore ( String , String ) } when using enums . */
public StringClauses insertBefore ( Enum existingKey , Enum newKey , String newValue ) { } }

implementation: return insertBefore ( existingKey . name ( ) , newKey . name ( ) , newValue ) ;


signature:
public class StringClauses { /** * Inserts a new clause after the given key . Throws IllegalArgumentException if the existingKey does not exist . */
public StringClauses insertAfter ( String existingKey , String newKey , String newValue ) { } }

implementation: return insertAfterImpl ( existingKey , newKey , newValue ) ;


signature:
public class StringClauses { /** * Convenience method for { @ link # insertAfter ( String , String ) } when using enums */
public StringClauses insertAfter ( Enum existingKey , String newValue ) { } }

implementation: return insertAfter ( existingKey . name ( ) , newValue ) ;


signature:
public class StringClauses { /** * Convenience method for { @ link # insertAfter ( String , String , String ) } using the newValue as the newKey . */
public StringClauses insertAfter ( String existingKey , String newValue ) { } }

implementation: return insertAfter ( existingKey , newValue , StringUtil . trimToEmpty ( newValue ) ) ;


signature:
public class StringClauses { /** * Retrieves the given key . Returns null if not set .
 * If clause at key is a StringClause , return the string version of it .
 * Will traverse sub - clauses to find the key . */
public String get ( String exitingKey ) { } }

implementation: exitingKey = StringUtil . trimToEmpty ( exitingKey ) . toLowerCase ( ) ; Object clauses = getImpl ( exitingKey ) ; if ( clauses == null ) { return null ; } return clauses . toString ( ) ;


signature:
public class StringClauses { /** * Retrieves the given key . Returns null if not set . If clause at key is a String , return a new StringClause version of it . Will traverse sub - clauses to find the key . */
public StringClauses getSubclause ( String exitingKey ) { } }

implementation: exitingKey = StringUtil . trimToEmpty ( exitingKey ) . toLowerCase ( ) ; Object clauses = getImpl ( exitingKey ) ; if ( clauses == null ) { return null ; } if ( clauses instanceof String ) { return new StringClauses ( ) . append ( ( String ) clauses ) ; } return ( StringClauses ) clauses ;


signature:
public class DiffToChangeLog { /** * Prints changeLog that would bring the target database to be the same as
 * the reference database */
public void print ( PrintStream out , ChangeLogSerializer changeLogSerializer ) throws ParserConfigurationException , IOException , DatabaseException { } }

implementation: List < ChangeSet > changeSets = generateChangeSets ( ) ; changeLogSerializer . write ( changeSets , out ) ; out . flush ( ) ;


signature:
public class DiffToChangeLog { /** * Adds dependencies to the graph as schema . object _ name . */
protected void addDependencies ( DependencyUtil . DependencyGraph < String > graph , List < String > schemas , Database database ) throws DatabaseException { } }

implementation:
if ( database instanceof DB2Database ) { Executor executor = ExecutorService . getInstance ( ) . getExecutor ( database ) ; List < Map < String , ? > > rs = executor . queryForList ( new RawSqlStatement ( "select TABSCHEMA, TABNAME, BSCHEMA, BNAME from syscat.tabdep where (" + StringUtil . join ( schemas , " OR " , new StringUtil . StringUtilFormatter < String > ( ) { @ Override public String toString ( String obj ) { return "TABSCHEMA='" + obj + "'" ; } } ) + ")" ) ) ; for ( Map < String , ? > row : rs ) { String tabName = StringUtil . trimToNull ( ( String ) row . get ( "TABSCHEMA" ) ) + "." + StringUtil . trimToNull ( ( String ) row . get ( "TABNAME" ) ) ; String bName = StringUtil . trimToNull ( ( String ) row . get ( "BSCHEMA" ) ) + "." + StringUtil . trimToNull ( ( String ) row . get ( "BNAME" ) ) ; graph . add ( bName , tabName ) ; } } else if ( database instanceof Db2zDatabase ) { Executor executor = ExecutorService . getInstance ( ) . getExecutor ( database ) ; String db2ZosSql = "SELECT DSCHEMA AS TABSCHEMA, DNAME AS TABNAME, BSCHEMA, BNAME FROM SYSIBM.SYSDEPENDENCIES WHERE (" + StringUtil . join ( schemas , " OR " , new StringUtil . StringUtilFormatter < String > ( ) { @ Override public String toString ( String obj ) { return "DSCHEMA='" + obj + "'" ; } } ) + ")" ; List < Map < String , ? > > rs = executor . queryForList ( new RawSqlStatement ( db2ZosSql ) ) ; for ( Map < String , ? > row : rs ) { String tabName = StringUtil . trimToNull ( ( String ) row . get ( "TABSCHEMA" ) ) + "." + StringUtil . trimToNull ( ( String ) row . get ( "TABNAME" ) ) ; String bName = StringUtil . trimToNull ( ( String ) row . get ( "BSCHEMA" ) ) + "." + StringUtil . trimToNull ( ( String ) row . get ( "BNAME" ) ) ; graph . add ( bName , tabName ) ; } } else if ( database instanceof OracleDatabase ) { Executor executor = ExecutorService . getInstance ( ) . getExecutor ( database ) ; List < Map < String , ? > > rs = queryForDependencies ( executor , schemas ) ; for ( Map < String , ? > row : rs ) { String tabName = null ; if ( tryDbaDependencies ) { tabName = StringUtil . trimToNull ( ( String ) row . get ( "OWNER" ) ) + "." + StringUtil . trimToNull ( ( String ) row . get ( "NAME" ) ) ; } else { tabName = StringUtil . trimToNull ( ( String ) row . get ( "REFERENCED_OWNER" ) ) + "." + StringUtil . trimToNull ( ( String ) row . get ( "NAME" ) ) ; } String bName = StringUtil . trimToNull ( ( String ) row . get ( "REFERENCED_OWNER" ) ) + "." + StringUtil . trimToNull ( ( String ) row . get ( "REFERENCED_NAME" ) ) ; graph . add ( bName , tabName ) ; } } else if ( database instanceof MSSQLDatabase ) { Executor executor = ExecutorService . getInstance ( ) . getExecutor ( database ) ; String sql = "select object_schema_name(referencing_id) as referencing_schema_name, object_name(referencing_id) as referencing_name, object_name(referenced_id) as referenced_name, object_schema_name(referenced_id) as referenced_schema_name  from sys.sql_expression_dependencies depz where (" + StringUtil . join ( schemas , " OR " , new StringUtil . StringUtilFormatter < String > ( ) { @ Override public String toString ( String obj ) { return "object_schema_name(referenced_id)='" + obj + "'" ; } } ) + ")" ; sql += " UNION select object_schema_name(object_id) as referencing_schema_name, object_name(object_id) as referencing_name, object_name(parent_object_id) as referenced_name, object_schema_name(parent_object_id) as referenced_schema_name " + "from sys.objects " + "where parent_object_id > 0 " + "and is_ms_shipped=0 " + "and (" + StringUtil . join ( schemas , " OR " , new StringUtil . StringUtilFormatter < String > ( ) { @ Override public String toString ( String obj ) { return "object_schema_name(object_id)='" + obj + "'" ; } } ) + ")" ; sql += " UNION select object_schema_name(fk.object_id) as referencing_schema_name, fk.name as referencing_name, i.name as referenced_name, object_schema_name(i.object_id) as referenced_schema_name " + "from sys.foreign_keys fk " + "join sys.indexes i on fk.referenced_object_id=i.object_id and fk.key_index_id=i.index_id " + "where fk.is_ms_shipped=0 " + "and (" + StringUtil . join ( schemas , " OR " , new StringUtil . StringUtilFormatter < String > ( ) { @ Override public String toString ( String obj ) { return "object_schema_name(fk.object_id)='" + obj + "'" ; } } ) + ")" ; sql += " UNION select object_schema_name(i.object_id) as referencing_schema_name, object_name(i.object_id) as referencing_name, s.name as referenced_name, null as referenced_schema_name " + "from sys.indexes i " + "join sys.partition_schemes s on i.data_space_id = s.data_space_id" ; sql += " UNION select null as referencing_schema_name, s.name as referencing_name, f.name as referenced_name, null as referenced_schema_name from sys.partition_functions f " + "join sys.partition_schemes s on s.function_id=f.function_id" ; sql += " UNION select null as referencing_schema_name, s.name as referencing_name, fg.name as referenced_name, null as referenced_schema_name from sys.partition_schemes s " + "join sys.destination_data_spaces ds on s.data_space_id=ds.partition_scheme_id " + "join sys.filegroups fg on ds.data_space_id=fg.data_space_id" ; // get data file - > filegroup dependencies
sql += " UNION select distinct null as referencing_schema_name, f.name as referencing_name, ds.name as referenced_name, null as referenced_schema_name from sys.database_files f " + "join sys.data_spaces ds on f.data_space_id=ds.data_space_id " + "where f.data_space_id > 1" ; // get table - > filestream dependencies
sql += " UNION select object_schema_name(t.object_id) as referencing_schema_name, t.name as referencing_name, ds.name as referenced_name, null as referenced_schema_name from sys.tables t " + "join sys.data_spaces ds on t.filestream_data_space_id=ds.data_space_id " + "where t.filestream_data_space_id > 1" ; // get table - > filestream dependencies
sql += " UNION select object_schema_name(t.object_id) as referencing_schema_name, t.name as referencing_name, ds.name as referenced_name, null as referenced_schema_name from sys.tables t " + "join sys.data_spaces ds on t.lob_data_space_id=ds.data_space_id " + "where t.lob_data_space_id > 1" ; // get index - > filegroup dependencies
sql += " UNION select object_schema_name(i.object_id) as referencing_schema_name, i.name as referencing_name, ds.name as referenced_name, null as referenced_schema_name from sys.indexes i " + "join sys.data_spaces ds on i.data_space_id=ds.data_space_id " + "where i.data_space_id > 1" ; // get index - > table dependencies
sql += " UNION select object_schema_name(i.object_id) as referencing_schema_name, i.name as referencing_name, object_name(i.object_id) as referenced_name, object_schema_name(i.object_id) as referenced_schema_name from sys.indexes i " + "where " + StringUtil . join ( schemas , " OR " , new StringUtil . StringUtilFormatter < String > ( ) { @ Override public String toString ( String obj ) { return "object_schema_name(i.object_id)='" + obj + "'" ; } } ) ; // get schema - > base object dependencies
sql += " UNION SELECT SCHEMA_NAME(SCHEMA_ID) as referencing_schema_name, name as referencing_name, PARSENAME(BASE_OBJECT_NAME,1) AS referenced_name, (CASE WHEN PARSENAME(BASE_OBJECT_NAME,2) IS NULL THEN schema_name(schema_id) else PARSENAME(BASE_OBJECT_NAME,2) END) AS referenced_schema_name FROM SYS.SYNONYMS WHERE is_ms_shipped='false' AND " + StringUtil . join ( schemas , " OR " , new StringUtil . StringUtilFormatter < String > ( ) { @ Override public String toString ( String obj ) { return "SCHEMA_NAME(SCHEMA_ID)='" + obj + "'" ; } } ) ; // get non - clustered indexes - > unique clustered indexes on views dependencies
sql += " UNION select object_schema_name(c.object_id) as referencing_schema_name, c.name as referencing_name, object_schema_name(nc.object_id) as referenced_schema_name, nc.name as referenced_name from sys.indexes c join sys.indexes nc on c.object_id=nc.object_id JOIN sys.objects o ON c.object_id = o.object_id where  c.index_id != nc.index_id and c.type_desc='CLUSTERED' and c.is_unique='true' and (not(nc.type_desc='CLUSTERED') OR nc.is_unique='false') AND o.type_desc='VIEW' AND o.name='AR_DETAIL_OPEN'" ; List < Map < String , ? > > rs = executor . queryForList ( new RawSqlStatement ( sql ) ) ; if ( ! rs . isEmpty ( ) ) { for ( Map < String , ? > row : rs ) { String bName = StringUtil . trimToNull ( ( String ) row . get ( "REFERENCED_SCHEMA_NAME" ) ) + "." + StringUtil . trimToNull ( ( String ) row . get ( "REFERENCED_NAME" ) ) ; String tabName = StringUtil . trimToNull ( ( String ) row . get ( "REFERENCING_SCHEMA_NAME" ) ) + "." + StringUtil . trimToNull ( ( String ) row . get ( "REFERENCING_NAME" ) ) ; if ( ! bName . equals ( tabName ) ) { graph . add ( bName , tabName ) ; } } } }


signature:
public class DatabaseFactory { /** * Returns instances of all implemented database types . */
public List < Database > getImplementedDatabases ( ) { } }

implementation: List < Database > returnList = new ArrayList < > ( ) ; for ( SortedSet < Database > set : implementedDatabases . values ( ) ) { returnList . add ( set . iterator ( ) . next ( ) ) ; } return returnList ;


signature:
public class DatabaseFactory { /** * Returns instances of all " internal " database types . */
public List < Database > getInternalDatabases ( ) { } }

implementation: List < Database > returnList = new ArrayList < > ( ) ; for ( SortedSet < Database > set : internalDatabases . values ( ) ) { returnList . add ( set . iterator ( ) . next ( ) ) ; } return returnList ;


signature:
public class DatabaseFactory { /** * Returns the Java class name of the JDBC driver class ( e . g . " org . mariadb . jdbc . Driver " )
 * for the specified JDBC URL , if any Database class supports that URL .
 * @ param url the JDBC URL to analyse
 * @ return a Database object supporting the URL . May also return null if the JDBC URL is unknown to all handlers . */
public String findDefaultDriver ( String url ) { } }

implementation: for ( Database database : this . getImplementedDatabases ( ) ) { String defaultDriver = database . getDefaultDriver ( url ) ; if ( defaultDriver != null ) { return defaultDriver ; } } return null ;


signature:
public class LiquibaseDataType { /** * Validates the correct state of this data type against a given database .
 * @ param database the database to validate against
 * @ return true if the current settings for this data type can be implemented on the given database , false otherwise */
public boolean validate ( Database database ) { } }

implementation: int maxParameters = this . getMaxParameters ( database ) ; int minParameters = this . getMinParameters ( database ) ; if ( parameters . size ( ) > maxParameters ) { throw new UnexpectedLiquibaseException ( "Type " + getClass ( ) + " doesn't support " + maxParameters + " parameters" ) ; } if ( parameters . size ( ) < minParameters ) { throw new UnexpectedLiquibaseException ( "Type " + getClass ( ) + " requires " + minParameters + " parameters" ) ; } return true ;


signature:
public class LiquibaseDataType { /** * Transforms this data type into the native data type of the target DBMS .
 * @ param database the { @ link Database } for which the native data type is to be constructed
 * @ return the new , native data type */
public DatabaseDataType toDatabaseDataType ( Database database ) { } }

implementation: if ( database instanceof MSSQLDatabase ) { String name = database . escapeDataTypeName ( getName ( ) ) ; int dataTypeMaxParameters = database . getDataTypeMaxParameters ( getName ( ) ) ; Object [ ] parameters = getParameters ( ) ; if ( dataTypeMaxParameters < parameters . length ) { parameters = Arrays . copyOfRange ( parameters , 0 , dataTypeMaxParameters ) ; } return new DatabaseDataType ( name , parameters ) ; } DatabaseDataType type = new DatabaseDataType ( name . toUpperCase ( Locale . US ) , getParameters ( ) ) ; type . addAdditionalInformation ( additionalInformation ) ; return type ;


signature:
public class LiquibaseDataType { /** * Returns the value object in a format to include in SQL . Quote if necessary . */
public String objectToSql ( Object value , Database database ) { } }

implementation: if ( ( value == null ) || "null" . equals ( value . toString ( ) . toLowerCase ( Locale . US ) ) ) { return null ; } else if ( value instanceof DatabaseFunction ) { return functionToSql ( ( DatabaseFunction ) value , database ) ; } else if ( value instanceof Number ) { return numberToSql ( ( Number ) value , database ) ; } return otherToSql ( value , database ) ;


signature:
public class LiquibaseDataType { /** * Determines if the given function name refers to the function that returns the current
 * time and date for a specific DBMS . Also returns true if the name returns the Liquibase wildcard
 * CURRENT _ DATE _ TIME _ PLACE _ HOLDER , which will later be translated into the appropriate function .
 * @ param string The database function name to test
 * @ param database A database object to test against
 * @ return see above */
protected boolean isCurrentDateTimeFunction ( String string , Database database ) { } }

implementation: return string . toLowerCase ( Locale . US ) . startsWith ( "current_timestamp" ) || string . toLowerCase ( Locale . US ) . startsWith ( DatabaseFunction . CURRENT_DATE_TIME_PLACE_HOLDER ) || database . getCurrentDateTimeFunction ( ) . toLowerCase ( Locale . US ) . equals ( string . toLowerCase ( Locale . US ) ) ;


signature:
public class DB2Database { /** * boolean data type column are allowed for versions > = 11.1.1.1
 * @ return */
public boolean supportsBooleanDataType ( ) { } }

implementation:
if ( getConnection ( ) == null ) return false ; // / assume not ;
try { final Integer fixPack = getDb2FixPack ( ) ; if ( fixPack == null ) throw new DatabaseException ( "Error getting fix pack number" ) ; return getDatabaseMajorVersion ( ) > 11 || getDatabaseMajorVersion ( ) == 11 && getDatabaseMinorVersion ( ) >= 1 && fixPack . intValue ( ) >= 1 ; } catch ( final DatabaseException e ) { return false ; // assume not
}


signature:
public class H2Database { /** * Recursive way of building CONCAT instruction
 * @ param values a non null List of String
 * @ return a String containing the CONCAT instruction with all elements , or only a value if there is only one element in the list */
private String getConcatSql ( List < String > values ) { } }

implementation: if ( values . size ( ) == 1 ) { return values . get ( 0 ) ; } else { return START_CONCAT + values . get ( 0 ) + SEP_CONCAT + getConcatSql ( values . subList ( 1 , values . size ( ) ) ) + END_CONCAT ; }


signature:
public class ColumnMapRowMapper { /** * Retrieve a JDBC object value for the specified column .
 * < p > The default implementation uses the < code > getObject < / code > method .
 * Additionally , this implementation includes a " hack " to get around Oracle
 * returning a non standard object for their TIMESTAMP datatype .
 * @ param rs is the ResultSet holding the data
 * @ param index is the column index
 * @ return the Object returned */
protected Object getColumnValue ( ResultSet rs , int index ) throws SQLException { } }

implementation: return JdbcUtils . getResultSetValue ( rs , index ) ;


signature:
public class SqlGeneratorFactory { /** * Return true if the SqlStatement class queries the database in any way to determine Statements to execute .
 * If the statement queries the database , it cannot be used in updateSql type operations */
public boolean generateStatementsVolatile ( SqlStatement statement , Database database ) { } }

implementation: for ( SqlGenerator generator : getGenerators ( statement , database ) ) { if ( generator . generateStatementsIsVolatile ( database ) ) { return true ; } } return false ;


signature:
public class MavenUtils { /** * Obtains a { @ link ClassLoader } that can load from the Maven project dependencies . If
 * the dependencies have not be resolved ( or there are none ) then this will just end up
 * delegating to the parent { @ link ClassLoader } of this class .
 * @ return The ClassLoader that can load the resolved dependencies for the Maven
 * project .
 * @ throws java . net . MalformedURLException If any of the dependencies cannot be resolved
 * into a URL . */
public static ClassLoader getArtifactClassloader ( MavenProject project , boolean includeArtifact , boolean includeTestOutputDirectory , Class clazz , Log log , boolean verbose ) throws MalformedURLException { } }

implementation:
if ( verbose ) { log . info ( "Loading artifacts into URLClassLoader" ) ; } Set < URI > uris = new HashSet < > ( ) ; // Find project dependencies , including the transitive ones .
Set dependencies = project . getArtifacts ( ) ; if ( ( dependencies != null ) && ! dependencies . isEmpty ( ) ) { for ( Iterator it = dependencies . iterator ( ) ; it . hasNext ( ) ; ) { addArtifact ( uris , ( Artifact ) it . next ( ) , log , verbose ) ; } } else { log . info ( "there are no resolved artifacts for the Maven project." ) ; } // Include the artifact for the actual maven project if requested
if ( includeArtifact ) { // If the actual artifact can be resolved , then use that , otherwise use the build
// directory as that should contain the files for this project that we will need to
// run against . It is possible that the build directly could be empty , but we cannot
// directly include the source and resources as the resources may require filtering
// to replace any placeholders in the resource files .
Artifact a = project . getArtifact ( ) ; if ( a . getFile ( ) != null ) { addArtifact ( uris , a , log , verbose ) ; } else { addFile ( uris , new File ( project . getBuild ( ) . getOutputDirectory ( ) ) , log , verbose ) ; } } if ( includeTestOutputDirectory ) { addFile ( uris , new File ( project . getBuild ( ) . getTestOutputDirectory ( ) ) , log , verbose ) ; } if ( verbose ) { log . info ( LOG_SEPARATOR ) ; } List < URI > uriList = new ArrayList < > ( uris ) ; URL [ ] urlArray = new URL [ uris . size ( ) ] ; for ( int i = 0 ; i < uris . size ( ) ; i ++ ) { urlArray [ i ] = uriList . get ( i ) . toURL ( ) ; } return new URLClassLoader ( urlArray , clazz . getClassLoader ( ) ) ;


signature:
public class MavenUtils { /** * Adds the artifact file into the set of URLs so it can be used in a URLClassLoader .
 * @ param urls The set to add the artifact file URL to .
 * @ param artifact The Artifact to resolve the file for .
 * @ throws MalformedURLException If there is a problem creating the URL for the file . */
private static void addArtifact ( Set < URI > urls , Artifact artifact , Log log , boolean verbose ) throws MalformedURLException { } }

implementation:
File f = artifact . getFile ( ) ; if ( f == null ) { log . warn ( "Artifact with no actual file, '" + artifact . getGroupId ( ) + ":" + artifact . getArtifactId ( ) + "'" ) ; } else { addFile ( urls , f , log , verbose ) ; } // if ( f ! = null ) {
// URL fileURL = f . toURI ( ) . toURL ( ) ;
// if ( verbose ) {
// log . info ( " artifact : " + fileURL ) ;
// urls . add ( fileURL ) ;
// } else {
// log . warning ( " Artifact with no actual file , ' " + artifact . getGroupId ( )
// + " : " + artifact . getArtifactId ( ) + " ' " ) ;


signature:
public class MavenUtils { /** * Recursively searches for the field specified by the fieldName in the class and all
 * the super classes until it either finds it , or runs out of parents .
 * @ param clazz The Class to start searching from .
 * @ param fieldName The name of the field to retrieve .
 * @ return The { @ link Field } identified by the field name .
 * @ throws NoSuchFieldException If the field was not found in the class or any of its
 * super classes . */
public static Field getDeclaredField ( Class clazz , String fieldName ) throws NoSuchFieldException { } }

implementation:
Field f = getField ( clazz , fieldName ) ; if ( f == null ) { // Try the parent class
Class parent = clazz . getSuperclass ( ) ; if ( parent != null ) { return getDeclaredField ( parent , fieldName ) ; } else { throw new NoSuchFieldException ( "The field '" + fieldName + "' could not be " + "found in the class of any of its parent " + "classes." ) ; } } else { return f ; }


signature:
public class CommandLineResourceAccessor { /** * Return alternate options for the given path that the user maybe meant . Return in order of likelihood . */
protected List < String > getAlternatePaths ( String path ) { } }

implementation:
List < String > alternatePaths = new ArrayList < > ( ) ; if ( path . startsWith ( "/" ) ) { // People are often confused about leading slashes in resource paths . . .
alternatePaths . add ( path . substring ( 1 ) ) ; } return alternatePaths ;


signature:
public class ContextExpression { /** * Returns true if the passed runtime contexts match this context expression */
public boolean matches ( Contexts runtimeContexts ) { } }

implementation: if ( ( runtimeContexts == null ) || runtimeContexts . isEmpty ( ) ) { return true ; } if ( this . contexts . isEmpty ( ) ) { return true ; } for ( String expression : this . contexts ) { if ( matches ( expression , runtimeContexts ) ) { return true ; } } return false ;


signature:
public class BaseLiquibaseTask { /** * Creates a suitable ResourceAccessor for use in an Ant task . .
 * @ param classLoader The ClassLoader to use in the ResourceAccessor . It is preferable that it is an AntClassLoader .
 * @ return A ResourceAccessor . */
private ResourceAccessor createResourceAccessor ( ClassLoader classLoader ) { } }

implementation:
List < ResourceAccessor > resourceAccessors = new ArrayList < ResourceAccessor > ( ) ; resourceAccessors . add ( new FileSystemResourceAccessor ( Paths . get ( "." ) . toAbsolutePath ( ) . getRoot ( ) . toFile ( ) ) ) ; resourceAccessors . add ( new ClassLoaderResourceAccessor ( classLoader ) ) ; String changeLogDirectory = getChangeLogDirectory ( ) ; if ( changeLogDirectory != null ) { changeLogDirectory = changeLogDirectory . trim ( ) . replace ( '\\' , '/' ) ; // convert to standard / if using absolute path on windows
resourceAccessors . add ( new FileSystemResourceAccessor ( new File ( changeLogDirectory ) ) ) ; } return new CompositeResourceAccessor ( resourceAccessors . toArray ( new ResourceAccessor [ 0 ] ) ) ;


signature:
public class BaseLiquibaseTask { /** * Convenience method to safely close the database connection .
 * @ param database The database to close . */
protected void closeDatabase ( Database database ) { } }

implementation: try { if ( database != null ) { database . close ( ) ; } } catch ( DatabaseException e ) { log ( "Error closing the database connection." , e , Project . MSG_WARN ) ; }


signature:
public class CSVParser { /** * Appends the next character in the line to the stringbuffer .
 * @ param line - line to process
 * @ param sb - contains the processed character
 * @ param i - current position in the line .
 * @ return new position in the line . */
private int appendNextCharacterAndAdvanceLoop ( String line , StringBuilder sb , int i ) { } }

implementation: sb . append ( line . charAt ( i + 1 ) ) ; i ++ ; return i ;


signature:
public class CSVParser { /** * Checks to see if the character after the index is a quotation character .
 * precondition : the current character is a quote or an escape
 * @ param nextLine the current line
 * @ param inQuotes true if the current context is quoted
 * @ param i current index in line
 * @ return true if the following character is a quote */
private boolean isNextCharacterEscapedQuote ( String nextLine , boolean inQuotes , int i ) { } }

implementation:
return inQuotes // we are in quotes , therefore there can be escaped quotes in here .
&& ( nextLine . length ( ) > ( i + 1 ) ) // there is indeed another character to check .
&& isCharacterQuoteCharacter ( nextLine . charAt ( i + 1 ) ) ;


signature:
public class CSVParser { /** * Checks to see if the character after the current index in a String is an escapable character .
 * Meaning the next character is either a quotation character or the escape char and you are inside
 * quotes .
 * precondition : the current character is an escape
 * @ param nextLine the current line
 * @ param inQuotes true if the current context is quoted
 * @ param i current index in line
 * @ return true if the following character is a quote */
protected boolean isNextCharacterEscapable ( String nextLine , boolean inQuotes , int i ) { } }

implementation:
return inQuotes // we are in quotes , therefore there can be escaped quotes in here .
&& ( nextLine . length ( ) > ( i + 1 ) ) // there is indeed another character to check .
&& isCharacterEscapable ( nextLine . charAt ( i + 1 ) ) ;


signature:
public class ParsedNode { /** * Returns all child nodes with the given namespace and name .
 * If none match , an empty list is returned .
 * Returned list is unmodifiableList . */
public List < ParsedNode > getChildren ( String namespace , String nodename ) { } }

implementation: List < ParsedNode > returnList = new ArrayList < > ( ) ; for ( ParsedNode node : children ) { if ( nodeMatches ( node , namespace , nodename ) ) { returnList . add ( node ) ; } } return Collections . unmodifiableList ( returnList ) ;


signature:
public class ParsedNode { /** * Sets the value of this ParsedNode .
 * If the passed value is a ParsedNode , it is added as a child , not as the value .
 * If the passed value is a Map , it is converted to a ParsedNode and added as a child , not as the value .
 * If the passed value is a Collection , each object is added as a child if it is a ParsedNode or a Map .
 * If there are multiple simple values in a passed collection , value is set to a List . If there is a single value in a collection , value is set to the single value . */
public ParsedNode setValue ( Object value ) throws ParsedNodeException { } }

implementation:
if ( value instanceof ParsedNode ) { this . addChild ( ( ParsedNode ) value ) ; } else if ( value instanceof Collection ) { List newValue = new ArrayList ( ) ; for ( Object obj : ( ( Collection ) value ) ) { if ( obj instanceof Map ) { addChildren ( ( Map ) obj ) ; } else if ( obj instanceof ParsedNode ) { addChild ( ( ( ParsedNode ) obj ) ) ; } else { newValue . add ( obj ) ; } } if ( newValue . isEmpty ( ) ) { // do nothing
} else if ( newValue . size ( ) == 1 ) { this . value = newValue . get ( 0 ) ; } else { this . value = newValue ; } } else if ( value instanceof Map ) { addChildren ( ( ( Map ) value ) ) ; } else { this . value = value ; } return this ;


signature:
public class ParsedNode { /** * Return the value associated with this node converted to the given type .
 * @ throws ParsedNodeException if the current value type cannot be converted */
public < T > T getValue ( Class < T > type ) throws ParsedNodeException { } }

implementation: return convertObject ( value , type ) ;


signature:
public class ParsedNode { /** * Convenience method to add a new ParsedNode with the passed namespace / name and value */
public ParsedNode addChild ( String namespace , String nodeName , Object value ) throws ParsedNodeException { } }

implementation: addChild ( createNode ( namespace , nodeName ) . setValue ( value ) ) ; return this ;


signature:
public class ParsedNode { /** * Adds the given map as children of this node .
 * If the passed map is empty , it is a no - op
 * For each key in the map , a new child is added with the key as the name and the value ( with all { @ link # setValue ( Object ) } ) logic ) is the value . */
public ParsedNode addChildren ( Map < String , Object > child ) throws ParsedNodeException { } }

implementation:
if ( ( child == null ) || child . isEmpty ( ) ) { return this ; // do nothing
} for ( Map . Entry < String , Object > entry : child . entrySet ( ) ) { this . addChild ( null , entry . getKey ( ) , entry . getValue ( ) ) ; } return this ;


signature:
public class ParsedNode { /** * Returns the ParsedNode defined by the given namespace and name .
 * @ throws liquibase . parser . core . ParsedNodeException if multiple nodes match . */
public ParsedNode getChild ( String namespace , String name ) throws ParsedNodeException { } }

implementation: ParsedNode returnNode = null ; for ( ParsedNode node : children ) { if ( nodeMatches ( node , namespace , name ) ) { if ( returnNode != null ) { throw new ParsedNodeException ( "Multiple nodes match " + namespace + "/" + name ) ; } returnNode = node ; } } return returnNode ;


signature:
public class ParsedNode { /** * Convenience method for { @ link # getChildValue ( String , String , Class ) } but returns the passed defaultValue if the given node is null or not defined . */
public < T > T getChildValue ( String namespace , String nodename , T defaultValue ) throws ParsedNodeException { } }

implementation: T value = ( T ) getChildValue ( namespace , nodename , defaultValue . getClass ( ) ) ; if ( value == null ) { return defaultValue ; } return value ;


signature:
public class ParsedNode { /** * Returns the value of the given node , converted to the passed type .
 * @ throws liquibase . parser . core . ParsedNodeException if there is an error converting the value */
public < T > T getChildValue ( String namespace , String nodename , Class < T > type ) throws ParsedNodeException { } }

implementation: Object rawValue = getChildValue ( namespace , nodename ) ; if ( rawValue == null ) { return null ; } return convertObject ( rawValue , type ) ;


signature:
public class ParsedNode { /** * Returns the value of the given node with no conversion attempted . */
public Object getChildValue ( String namespace , String nodename ) throws ParsedNodeException { } }

implementation: ParsedNode child = getChild ( namespace , nodename ) ; if ( child == null ) { return null ; } return child . getValue ( ) ;


signature:
public class InputStreamList { /** * Close the streams in this collection . */
@ Override public void close ( ) throws IOException { } }

implementation: for ( InputStream stream : this ) { try { stream . close ( ) ; } catch ( IOException e ) { Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . severe ( "Error closing stream. Logging error and continuing" , e ) ; } }


signature:
public class DatabaseDataType { /** * Mainly for postgres , check if the column is a serial data type .
 * @ return Whether the type is serial */
public boolean isAutoIncrement ( ) { } }

implementation: return "serial" . equals ( type . toLowerCase ( Locale . US ) ) || "bigserial" . equals ( type . toLowerCase ( Locale . US ) ) || "smallserial" . equals ( type . toLowerCase ( Locale . US ) ) ;


signature:
public class JdbcExecutor { /** * the query is composed . */
@ SuppressWarnings ( "squid:S2077" ) public Object execute ( CallableStatementCallback action , List < SqlVisitor > sqlVisitors ) throws DatabaseException { } }

implementation:
DatabaseConnection con = database . getConnection ( ) ; if ( con instanceof OfflineConnection ) { throw new DatabaseException ( "Cannot execute commands against an offline database" ) ; } CallableStatement stmt = null ; try { String sql = applyVisitors ( action . getStatement ( ) , sqlVisitors ) [ 0 ] ; stmt = ( ( JdbcConnection ) con ) . getUnderlyingConnection ( ) . prepareCall ( sql ) ; return action . doInCallableStatement ( stmt ) ; } catch ( SQLException ex ) { // Release Connection early , to avoid potential connection pool deadlock
// in the case when the exception translator hasn ' t been initialized yet .
JdbcUtils . closeStatement ( stmt ) ; stmt = null ; throw new DatabaseException ( "Error executing SQL " + StringUtil . join ( applyVisitors ( action . getStatement ( ) , sqlVisitors ) , "; on " + con . getURL ( ) ) + ": " + ex . getMessage ( ) , ex ) ; } finally { JdbcUtils . closeStatement ( stmt ) ; }


signature:
public class JdbcExecutor { /** * the query is composed . */
@ SuppressWarnings ( "squid:S2077" ) @ Override public int update ( final SqlStatement sql , final List < SqlVisitor > sqlVisitors ) throws DatabaseException { } }

implementation: if ( sql instanceof CallableSqlStatement ) { throw new DatabaseException ( "Direct update using CallableSqlStatement not currently implemented" ) ; } class UpdateStatementCallback implements StatementCallback { @ Override public Object doInStatement ( Statement stmt ) throws SQLException , DatabaseException { String [ ] sqlToExecute = applyVisitors ( sql , sqlVisitors ) ; if ( sqlToExecute . length != 1 ) { throw new DatabaseException ( "Cannot call update on Statement that returns back multiple Sql objects" ) ; } Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . fine ( LogType . WRITE_SQL , sqlToExecute [ 0 ] ) ; return stmt . executeUpdate ( sqlToExecute [ 0 ] ) ; } @ Override public SqlStatement getStatement ( ) { return sql ; } } return ( Integer ) execute ( new UpdateStatementCallback ( ) , sqlVisitors ) ;


signature:
public class SingleColumnRowMapper { /** * Extract a value for the single column in the current row .
 * < p > Validates that there is only one column selected ,
 * then delegates to < code > getColumnValue ( ) < / code > and also
 * < code > convertValueToRequiredType < / code > , if necessary .
 * @ see java . sql . ResultSetMetaData # getColumnCount ( )
 * @ see # getColumnValue ( java . sql . ResultSet , int , Class )
 * @ see # convertValueToRequiredType ( Object , Class ) */
@ Override public Object mapRow ( ResultSet rs , int rowNum ) throws SQLException { } }

implementation:
// Validate column count .
ResultSetMetaData rsmd = rs . getMetaData ( ) ; int nrOfColumns = rsmd . getColumnCount ( ) ; if ( nrOfColumns == 0 ) { throw new SQLException ( "Returned no columns!" ) ; } else if ( nrOfColumns != 1 ) { throw new SQLException ( "Returned too many columns: " + nrOfColumns ) ; } // Extract column value from JDBC ResultSet
Object result = getColumnValue ( rs , 1 , this . requiredType ) ; if ( ( result != null ) && ( this . requiredType != null ) && ! this . requiredType . isInstance ( result ) ) { // Extracted value does not match already : try to convert it .
try { return convertValueToRequiredType ( result , this . requiredType ) ; } catch ( IllegalArgumentException ex ) { throw new SQLException ( "Type mismatch affecting row number " + rowNum + " and column type '" + rsmd . getColumnTypeName ( 1 ) + "': " + ex . getMessage ( ) ) ; } } return result ;


signature:
public class SingleColumnRowMapper { /** * Convert the given column value to the specified required type .
 * Only called if the extracted column value does not match already .
 * < p > If the required type is String , the value will simply get stringified
 * via < code > toString ( ) < / code > . In case of a Number , the value will be
 * converted into a Number , either through number conversion or through
 * String parsing ( depending on the value type ) .
 * @ param value the column value as extracted from < code > getColumnValue ( ) < / code >
 * ( never < code > null < / code > )
 * @ param requiredType the type that each result object is expected to match
 * ( never < code > null < / code > )
 * @ return the converted value
 * @ see # getColumnValue ( java . sql . ResultSet , int , Class ) */
protected Object convertValueToRequiredType ( Object value , Class requiredType ) { } }

implementation:
if ( String . class . equals ( this . requiredType ) ) { return value . toString ( ) ; } else if ( Number . class . isAssignableFrom ( this . requiredType ) ) { if ( value instanceof Number ) { // Convert original Number to target Number class .
return NumberUtils . convertNumberToTargetClass ( ( ( Number ) value ) , this . requiredType ) ; } else { // Convert stringified value to target Number class .
return NumberUtils . parseNumber ( value . toString ( ) , this . requiredType ) ; } } else { throw new IllegalArgumentException ( "Value [" + value + "] is of type [" + value . getClass ( ) . getName ( ) + "] and cannot be converted to required type [" + this . requiredType . getName ( ) + "]" ) ; }


signature:
public class FileSystemResourceAccessor { /** * Returns true if the given path is a compressed file . */
protected boolean isCompressedFile ( Path path ) { } }

implementation: return path != null && ( path . toString ( ) . startsWith ( "jar:" ) || path . toString ( ) . toLowerCase ( ) . endsWith ( ".jar" ) || path . toString ( ) . toLowerCase ( ) . endsWith ( ".zip" ) ) ;


signature:
public class Relation { /** * Returns the column object for the given columnName . If the column does not exist in this table ,
 * return null . */
public Column getColumn ( String columnName ) { } }

implementation: for ( Column column : getColumns ( ) ) { if ( column . getName ( ) . equalsIgnoreCase ( columnName ) ) { return column ; } } return null ;


signature:
public class Scope { /** * Creates a new scope that is a child of this scope . */
public static void child ( Map < String , Object > scopeValues , ScopedRunner runner ) throws Exception { } }

implementation: child ( ( LiquibaseListener ) null , scopeValues , runner ) ;


signature:
public class Scope { /** * Creates a new child scope that includes the given { @ link LiquibaseListener } .
 * You cannot unassign a listener , they simply fall out of scope when the Scope does .
 * @ see # getListeners ( Class ) */
public static void child ( LiquibaseListener listener , ScopedRunner runner ) throws Exception { } }

implementation: child ( listener , null , runner ) ;


signature:
public class Scope { /** * Creates a new scope that is a child of this scope . */
public static void child ( String newValueKey , Object newValue , ScopedRunner runner ) throws Exception { } }

implementation: Map < String , Object > scopeValues = new HashMap < String , Object > ( ) ; scopeValues . put ( newValueKey , newValue ) ; child ( scopeValues , runner ) ;


signature:
public class Scope { /** * Return the value associated with the given key in this scope or any parent scope .
 * The value is converted to the given type if necessary using { @ link liquibase . util . ObjectUtil # convert ( Object , Class ) } .
 * Returns null if key is not defined in this or any parent scopes . */
public < T > T get ( String key , Class < T > type ) { } }

implementation: T value = values . get ( key , type ) ; if ( value == null && parent != null ) { value = parent . get ( key , type ) ; } return value ;


signature:
public class Scope { /** * Looks up the singleton object of the given type . If the singleton has not been created yet , it will be instantiated .
 * The singleton is a singleton based on the root scope and the same object will be returned for all child scopes of the root . */
public < T extends SingletonObject > T getSingleton ( Class < T > type ) { } }

implementation:
if ( getParent ( ) != null ) { return getParent ( ) . getSingleton ( type ) ; } String key = type . getName ( ) ; T singleton = get ( key , type ) ; if ( singleton == null ) { try { try { Constructor < T > constructor = type . getDeclaredConstructor ( Scope . class ) ; constructor . setAccessible ( true ) ; singleton = constructor . newInstance ( this ) ; } catch ( NoSuchMethodException e ) { // try without scope
Constructor < T > constructor = type . getDeclaredConstructor ( ) ; constructor . setAccessible ( true ) ; singleton = constructor . newInstance ( ) ; } } catch ( Exception e ) { throw new UnexpectedLiquibaseException ( e ) ; } values . put ( key , singleton ) ; } return singleton ;


signature:
public class Scope { /** * Returns { @ link LiquibaseListener } s defined in this scope and / or all its parents that are of the given type . */
public < T extends LiquibaseListener > Collection < T > getListeners ( Class < T > type ) { } }

implementation: List < T > returnList = new ArrayList < > ( ) ; Scope scopeToCheck = this ; while ( scopeToCheck != null ) { if ( scopeToCheck . listener != null && type . isAssignableFrom ( scopeToCheck . listener . getClass ( ) ) ) { returnList . add ( ( T ) scopeToCheck . listener ) ; } scopeToCheck = scopeToCheck . getParent ( ) ; } return returnList ;


signature:
public class StandardChangeLogHistoryService { /** * Returns the ChangeSets that have been run against the current getDatabase ( ) . */
public List < RanChangeSet > getRanChangeSets ( ) throws DatabaseException { } }

implementation:
if ( this . ranChangeSetList == null ) { Database database = getDatabase ( ) ; String databaseChangeLogTableName = getDatabase ( ) . escapeTableName ( getLiquibaseCatalogName ( ) , getLiquibaseSchemaName ( ) , getDatabaseChangeLogTableName ( ) ) ; List < RanChangeSet > ranChangeSets = new ArrayList < > ( ) ; if ( hasDatabaseChangeLogTable ( ) ) { Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . info ( LogType . LOG , "Reading from " + databaseChangeLogTableName ) ; List < Map < String , ? > > results = queryDatabaseChangeLogTable ( database ) ; for ( Map rs : results ) { String fileName = rs . get ( "FILENAME" ) . toString ( ) ; String author = rs . get ( "AUTHOR" ) . toString ( ) ; String id = rs . get ( "ID" ) . toString ( ) ; String md5sum = ( ( rs . get ( "MD5SUM" ) == null ) || ! databaseChecksumsCompatible ) ? null : rs . get ( "MD5SUM" ) . toString ( ) ; String description = ( rs . get ( "DESCRIPTION" ) == null ) ? null : rs . get ( "DESCRIPTION" ) . toString ( ) ; String comments = ( rs . get ( "COMMENTS" ) == null ) ? null : rs . get ( "COMMENTS" ) . toString ( ) ; Object tmpDateExecuted = rs . get ( "DATEEXECUTED" ) ; Date dateExecuted = null ; if ( tmpDateExecuted instanceof Date ) { dateExecuted = ( Date ) tmpDateExecuted ; } else { DateFormat df = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss" ) ; try { dateExecuted = df . parse ( ( String ) tmpDateExecuted ) ; } catch ( ParseException e ) { // Ignore ParseException and assume dateExecuted = = null instead of aborting .
} } String tmpOrderExecuted = rs . get ( "ORDEREXECUTED" ) . toString ( ) ; Integer orderExecuted = ( ( tmpOrderExecuted == null ) ? null : Integer . valueOf ( tmpOrderExecuted ) ) ; String tag = ( rs . get ( "TAG" ) == null ) ? null : rs . get ( "TAG" ) . toString ( ) ; String execType = ( rs . get ( "EXECTYPE" ) == null ) ? null : rs . get ( "EXECTYPE" ) . toString ( ) ; ContextExpression contexts = new ContextExpression ( ( String ) rs . get ( "CONTEXTS" ) ) ; Labels labels = new Labels ( ( String ) rs . get ( "LABELS" ) ) ; String deploymentId = ( String ) rs . get ( "DEPLOYMENT_ID" ) ; try { RanChangeSet ranChangeSet = new RanChangeSet ( fileName , id , author , CheckSum . parse ( md5sum ) , dateExecuted , tag , ChangeSet . ExecType . valueOf ( execType ) , description , comments , contexts , labels , deploymentId ) ; ranChangeSet . setOrderExecuted ( orderExecuted ) ; ranChangeSets . add ( ranChangeSet ) ; } catch ( IllegalArgumentException e ) { Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . severe ( LogType . LOG , "Unknown EXECTYPE from database: " + execType ) ; throw e ; } } } this . ranChangeSetList = ranChangeSets ; } return Collections . unmodifiableList ( ranChangeSetList ) ;


signature:
public class StandardChangeLogHistoryService { /** * Tags the database changelog with the given string . */
@ Override public void tag ( final String tagString ) throws DatabaseException { } }

implementation: Database database = getDatabase ( ) ; Executor executor = ExecutorService . getInstance ( ) . getExecutor ( database ) ; int totalRows = ExecutorService . getInstance ( ) . getExecutor ( database ) . queryForInt ( new SelectFromDatabaseChangeLogStatement ( new ColumnConfig ( ) . setName ( "COUNT(*)" , true ) ) ) ; if ( totalRows == 0 ) { ChangeSet emptyChangeSet = new ChangeSet ( String . valueOf ( new Date ( ) . getTime ( ) ) , "liquibase" , false , false , "liquibase-internal" , null , null , getDatabase ( ) . getObjectQuotingStrategy ( ) , null ) ; this . setExecType ( emptyChangeSet , ChangeSet . ExecType . EXECUTED ) ; } executor . execute ( new TagDatabaseStatement ( tagString ) ) ; getDatabase ( ) . commit ( ) ; if ( this . ranChangeSetList != null ) { ranChangeSetList . get ( ranChangeSetList . size ( ) - 1 ) . setTag ( tagString ) ; }


signature:
public class PreconditionFactory { /** * Create a new Precondition subclass based on the given tag name . */
public Precondition create ( String tagName ) { } }

implementation: Class < ? > aClass = preconditions . get ( tagName ) ; if ( aClass == null ) { return null ; } try { return ( Precondition ) aClass . getConstructor ( ) . newInstance ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class StatementCreatorUtils { /** * Set the value for a parameter . The method used is based on the SQL type
 * of the parameter and we can handle complex types like arrays and LOBs .
 * @ param ps the prepared statement or callable statement
 * @ param paramIndex index of the parameter we are setting
 * @ param param the parameter as it is declared including type
 * @ param inValue the value to set
 * @ throws SQLException if thrown by PreparedStatement methods */
public static void setParameterValue ( PreparedStatement ps , int paramIndex , SqlParameter param , Object inValue ) throws SQLException { } }

implementation: setParameterValueInternal ( ps , paramIndex , param . getSqlType ( ) , param . getTypeName ( ) , param . getScale ( ) , inValue ) ;


signature:
public class StatementCreatorUtils { /** * Set the value for a parameter . The method used is based on the SQL type
 * of the parameter and we can handle complex types like arrays and LOBs .
 * @ param ps the prepared statement or callable statement
 * @ param paramIndex index of the parameter we are setting
 * @ param sqlType the SQL type of the parameter
 * @ param inValue the value to set ( plain value or a SqlTypeValue )
 * @ throws SQLException if thrown by PreparedStatement methods */
public static void setParameterValue ( PreparedStatement ps , int paramIndex , int sqlType , Object inValue ) throws SQLException { } }

implementation: setParameterValueInternal ( ps , paramIndex , sqlType , null , null , inValue ) ;


signature:
public class StatementCreatorUtils { /** * Set the value for a parameter . The method used is based on the SQL type
 * of the parameter and we can handle complex types like arrays and LOBs .
 * @ param ps the prepared statement or callable statement
 * @ param paramIndex index of the parameter we are setting
 * @ param sqlType the SQL type of the parameter
 * @ param typeName the type name of the parameter
 * ( optional , only used for SQL NULL and SqlTypeValue )
 * @ param scale the number of digits after the decimal point
 * ( for DECIMAL and NUMERIC types )
 * @ param inValue the value to set ( plain value or a SqlTypeValue )
 * @ throws SQLException if thrown by PreparedStatement methods */
private static void setParameterValueInternal ( PreparedStatement ps , int paramIndex , int sqlType , String typeName , Integer scale , Object inValue ) throws SQLException { } }

implementation:
if ( inValue == null ) { if ( sqlType == SqlTypeValue . TYPE_UNKNOWN ) { boolean useSetObject = false ; try { useSetObject = ( ps . getConnection ( ) . getMetaData ( ) . getDatabaseProductName ( ) . indexOf ( "Informix" ) != - 1 ) ; } catch ( Throwable ex ) { // logger . debug ( " Could not check database product name " , ex ) ;
} if ( useSetObject ) { ps . setObject ( paramIndex , null ) ; } else { ps . setNull ( paramIndex , Types . NULL ) ; } } else if ( typeName != null ) { ps . setNull ( paramIndex , sqlType , typeName ) ; } else { ps . setNull ( paramIndex , sqlType ) ; } } else { // inValue ! = null
if ( inValue instanceof SqlTypeValue ) { ( ( SqlTypeValue ) inValue ) . setTypeValue ( ps , paramIndex , sqlType , typeName ) ; } else if ( ( sqlType == Types . VARCHAR ) || ( sqlType == - 9 ) ) { // -9 is Types . NVARCHAR in java 1.6
ps . setString ( paramIndex , inValue . toString ( ) ) ; } else if ( ( sqlType == Types . DECIMAL ) || ( sqlType == Types . NUMERIC ) ) { if ( inValue instanceof BigDecimal ) { ps . setBigDecimal ( paramIndex , ( BigDecimal ) inValue ) ; } else if ( scale != null ) { ps . setObject ( paramIndex , inValue , sqlType , scale ) ; } else { ps . setObject ( paramIndex , inValue , sqlType ) ; } } else if ( sqlType == Types . DATE ) { if ( inValue instanceof java . util . Date ) { if ( inValue instanceof java . sql . Date ) { ps . setDate ( paramIndex , ( java . sql . Date ) inValue ) ; } else { ps . setDate ( paramIndex , new java . sql . Date ( ( ( java . util . Date ) inValue ) . getTime ( ) ) ) ; } } else if ( inValue instanceof Calendar ) { Calendar cal = ( Calendar ) inValue ; ps . setDate ( paramIndex , new java . sql . Date ( cal . getTime ( ) . getTime ( ) ) , cal ) ; } else { ps . setObject ( paramIndex , inValue , Types . DATE ) ; } } else if ( sqlType == Types . TIME ) { if ( inValue instanceof java . util . Date ) { if ( inValue instanceof java . sql . Time ) { ps . setTime ( paramIndex , ( java . sql . Time ) inValue ) ; } else { ps . setTime ( paramIndex , new java . sql . Time ( ( ( java . util . Date ) inValue ) . getTime ( ) ) ) ; } } else if ( inValue instanceof Calendar ) { Calendar cal = ( Calendar ) inValue ; ps . setTime ( paramIndex , new java . sql . Time ( cal . getTime ( ) . getTime ( ) ) , cal ) ; } else { ps . setObject ( paramIndex , inValue , Types . TIME ) ; } } else if ( sqlType == Types . TIMESTAMP ) { if ( inValue instanceof java . util . Date ) { if ( inValue instanceof java . sql . Timestamp ) { ps . setTimestamp ( paramIndex , ( java . sql . Timestamp ) inValue ) ; } else { ps . setTimestamp ( paramIndex , new java . sql . Timestamp ( ( ( java . util . Date ) inValue ) . getTime ( ) ) ) ; } } else if ( inValue instanceof Calendar ) { Calendar cal = ( Calendar ) inValue ; ps . setTimestamp ( paramIndex , new java . sql . Timestamp ( cal . getTime ( ) . getTime ( ) ) , cal ) ; } else { ps . setObject ( paramIndex , inValue , Types . TIMESTAMP ) ; } } else if ( sqlType == SqlTypeValue . TYPE_UNKNOWN ) { if ( isStringValue ( inValue ) ) { ps . setString ( paramIndex , inValue . toString ( ) ) ; } else if ( isDateValue ( inValue ) ) { ps . setTimestamp ( paramIndex , new java . sql . Timestamp ( ( ( java . util . Date ) inValue ) . getTime ( ) ) ) ; } else if ( inValue instanceof Calendar ) { Calendar cal = ( Calendar ) inValue ; ps . setTimestamp ( paramIndex , new java . sql . Timestamp ( cal . getTime ( ) . getTime ( ) ) ) ; } else { // Fall back to generic setObject call without SQL type specified .
ps . setObject ( paramIndex , inValue ) ; } } else { // Fall back to generic setObject call with SQL type specified .
ps . setObject ( paramIndex , inValue , sqlType ) ; } }


signature:
public class StatementCreatorUtils { /** * Check whether the given value is a < code > java . util . Date < / code >
 * ( but not one of the JDBC - specific subclasses ) . */
private static boolean isDateValue ( Object inValue ) { } }

implementation: return ( ( inValue instanceof java . util . Date ) && ! ( ( inValue instanceof java . sql . Date ) || ( inValue instanceof java . sql . Time ) || ( inValue instanceof java . sql . Timestamp ) ) ) ;


signature:
public class NowAndTodayUtil { /** * Checks if date starts with " NOW " or " TODAY " .
 * @ param value value to test
 * @ return true if value starts with " NOW " or " TODAY " ( case insensitive ) , false otherwise . */
public static boolean isNowOrTodayFormat ( String value ) { } }

implementation: boolean ret = false ; if ( value != null ) { String lowerValue = value . toLowerCase ( ) ; if ( lowerValue . length ( ) >= NOW_LENGTH && lowerValue . startsWith ( NOW ) ) { ret = true ; } else if ( lowerValue . length ( ) >= TODAY_LENGTH && lowerValue . startsWith ( TODAY ) ) { ret = true ; } } return ret ;


signature:
public class NowAndTodayUtil { /** * CHECKSTYLE : OFF Cyclomatic Complexity */
public static Date doNowOrToday ( String value , String colType ) throws DateParseException { } }

implementation:
if ( ! isNowOrTodayFormat ( value ) ) { return null ; } Calendar c = Calendar . getInstance ( ) ; String lowerValue = value . toLowerCase ( ) ; if ( lowerValue . startsWith ( NOW ) ) { parseNow ( value , lowerValue , c ) ; } else if ( lowerValue . startsWith ( TODAY ) ) { parseToday ( value , lowerValue , c ) ; } else { throw new DateParseException ( "Programmer error: " + value + " does not start with 'NOW' or 'TODAY'" ) ; } Date today = c . getTime ( ) ; if ( colType == null || colType . length ( ) == 0 ) { throw new DateParseException ( "Must supply non-null column type when using 'NOW' or 'TODAY' value." ) ; } else if ( colType . equalsIgnoreCase ( "timestamp" ) ) { return new java . sql . Timestamp ( today . getTime ( ) ) ; } else if ( colType . equalsIgnoreCase ( "time" ) ) { // A little odd using TODAY format with a TIME type column , but we ' ll do it - will get current time . . .
return new java . sql . Time ( today . getTime ( ) ) ; } else if ( colType . equalsIgnoreCase ( "date" ) || colType . equalsIgnoreCase ( "datetime" ) ) { return new java . sql . Date ( today . getTime ( ) ) ; } else { throw new DateParseException ( "Unrecognized colType " + colType + " when using 'NOW' or 'TODAY' value; expected one of date, time, datetime, or timestamp" ) ; }


signature:
public class NowAndTodayUtil { /** * CHECKSTYLE : OFF Cyclomatic Complexity */
private static void parseNow ( String value , String lowerValue , Calendar c ) throws DateParseException { } }

implementation: if ( lowerValue . length ( ) > NOW_LENGTH ) { Matcher matcher = NOW_OFFSET_PATTERN . matcher ( lowerValue ) ; if ( ! matcher . find ( ) ) { throw new DateParseException ( "Improper value in 'NOW' value: " + value + ". 'NOW' must be followed by + or -, then numeric offset, then units (h{our{s}}, " + "m{inute{s}}, d{ay{s}}, or y{ears}" ) ; } if ( matcher . groupCount ( ) != 4 ) { throw new DateParseException ( "Improper value in 'NOW' value: " + value + ". Pattern match returned " + matcher . groupCount ( ) + " instead of 4" ) ; } char sign = matcher . group ( 2 ) . charAt ( 0 ) ; if ( sign != '+' && sign != '-' ) { throw new DateParseException ( "Improper sign in 'NOW' value '" + lowerValue + "'" ) ; } String offsetStr = matcher . group ( 3 ) ; int offset ; try { offset = Integer . parseInt ( offsetStr ) ; } catch ( NumberFormatException e ) { throw new DateParseException ( "Improper offset in 'NOW' value '" + value + "'" ) ; } if ( sign == '-' ) { offset = - offset ; } int calendarField ; String units = matcher . group ( 4 ) ; if ( "years" . startsWith ( units ) ) { calendarField = Calendar . YEAR ; } else if ( "days" . startsWith ( units ) ) { calendarField = Calendar . DATE ; } else if ( "hours" . startsWith ( units ) ) { calendarField = Calendar . HOUR ; } else if ( "minutes" . startsWith ( units ) ) { calendarField = Calendar . MINUTE ; } else { throw new DateParseException ( "Improper units in 'NOW' value: '" + units + "', must be y{ear{s}}, " + "d{ay{s}}, h{our{s}}, or m{inute{s}}" ) ; } c . add ( calendarField , offset ) ; }


signature:
public class NowAndTodayUtil { /** * Parses " TODAY " type specification , and applies offset ( if any ) to calendar value .
 * @ param value original value
 * @ param lowerValue lower cased value .
 * @ param c Calendar with appropriate offset applied .
 * @ throws DateParseException if anything is wrong with the TODAY specification . */
private static void parseToday ( String value , String lowerValue , Calendar c ) throws DateParseException { } }

implementation: if ( lowerValue . length ( ) > TODAY_LENGTH ) { Matcher matcher = TODAY_OFFSET_PATTERN . matcher ( lowerValue ) ; if ( ! matcher . find ( ) ) { throw new DateParseException ( "Improper value in 'TODAY' value: " + value + ". 'TODAY' must be followed by + or -, then numeric offset" ) ; } if ( matcher . groupCount ( ) != 3 ) { throw new DateParseException ( "Improper value in 'TODAY' value: " + value + ". Pattern match returned " + matcher . groupCount ( ) + " instead of 3" ) ; } char sign = matcher . group ( 2 ) . charAt ( 0 ) ; if ( sign != '+' && sign != '-' ) { throw new DateParseException ( "Improper sign in 'TODAY' value '" + lowerValue + "'" ) ; } String offsetStr = matcher . group ( 3 ) ; int offset ; try { offset = Integer . parseInt ( offsetStr ) ; } catch ( NumberFormatException e ) { throw new DateParseException ( "Improper offset in 'TODAY' value '" + value + "'" ) ; } if ( sign == '-' ) { offset = - offset ; } c . add ( Calendar . DATE , offset ) ; }


signature:
public class ChangeLogParameters { /** * Return the value of a parameter
 * @ param key Name of the parameter
 * @ return The parameter value or null if not found . ( Note that null can also be return if it is the parameter
 * value . For strict parameter existence use { @ link # hasValue ( String , DatabaseChangeLog ) } */
public Object getValue ( String key , DatabaseChangeLog changeLog ) { } }

implementation: ChangeLogParameter parameter = findParameter ( key , changeLog ) ; return ( parameter != null ) ? parameter . getValue ( ) : null ;


signature:
public class DatabaseList { /** * Compares a given database to a database definition string .
 * < p > < / p >
 * Definition syntax : Comma separated list of database shortNames . Doesn ' t matter if it includes spaces .
 * Can exclude a database by prepending its name with a ' ! ' .
 * The string " all " will match all databases . The string " none " will match no databases , even if others are listed .
 * If an empty or null definition or null is passed , it will return the passed returnValueIfEmpty value . */
public static boolean definitionMatches ( String definition , String databaseShortName , boolean returnValueIfEmpty ) { } }

implementation: return definitionMatches ( StringUtil . splitAndTrim ( StringUtil . trimToNull ( definition ) , "," ) , databaseShortName , returnValueIfEmpty ) ;


signature:
public class DatabaseList { /** * Same logic as { @ link # definitionMatches ( String , liquibase . database . Database , boolean ) } but with a collection of definitions rather than a comma separated list . */
public static boolean definitionMatches ( Collection < String > definition , String databaseShortName , boolean returnValueIfEmptyList ) { } }

implementation:
if ( ( definition == null ) || definition . isEmpty ( ) ) { return returnValueIfEmptyList ; } if ( definition . contains ( "all" ) ) { return true ; } if ( definition . contains ( "none" ) ) { return false ; } // ! h2 would mean that the h2 database should be excluded
if ( definition . contains ( "!" + databaseShortName ) ) { return false ; } Set < String > dbmsSupported = new HashSet < > ( ) ; // add all dbms that do not start with ! to a list
for ( String dbms : definition ) { if ( ! dbms . startsWith ( "!" ) ) { dbmsSupported . add ( dbms ) ; } } if ( dbmsSupported . isEmpty ( ) || dbmsSupported . contains ( databaseShortName ) ) { return true ; } return false ;