signature:
public class SchemesCDIConfigBuilder { /** * Synchronization among multiple JVM ' s . */
CDILiquibaseConfig fileLocked ( final String id , Callable < CDILiquibaseConfig > action ) throws Exception { } }

implementation: log . info ( LogType . LOG , String . format ( "[id = %s] JVM lock acquired, acquiring file lock" , id ) ) ; String lockPath = String . format ( "%s/schema.liquibase.lock" , ROOT_PATH ) ; File lockFile = new File ( lockPath ) ; if ( ! lockFile . exists ( ) && lockFile . createNewFile ( ) ) { log . info ( LogType . LOG , String . format ( "[id = %s] Created lock file [path='%s']." , id , lockPath ) ) ; } log . info ( LogType . LOG , String . format ( "[id = %s] Trying to acquire the file lock [file='%s']..." , id , lockPath ) ) ; CDILiquibaseConfig actionResult = null ; FileLock lock = null ; try ( FileOutputStream fileStream = new FileOutputStream ( lockPath ) ; FileChannel fileChannel = fileStream . getChannel ( ) ; ) { while ( null == lock ) { try { lock = fileChannel . tryLock ( ) ; } catch ( OverlappingFileLockException e ) { log . fine ( LogType . LOG , String . format ( "[id = %s] Lock already acquired, waiting for the lock..." , id ) ) ; } if ( null == lock ) { log . fine ( LogType . LOG , String . format ( "[id = %s] Waiting for the lock..." , id ) ) ; Thread . sleep ( FILE_LOCK_TIMEOUT ) ; } } log . info ( LogType . LOG , String . format ( "[id = %s] File lock acquired, running liquibase..." , id ) ) ; actionResult = action . call ( ) ; lock . release ( ) ; } catch ( Exception e ) { log . warning ( LogType . LOG , e . getMessage ( ) , e ) ; } return actionResult ;


signature:
public class Main { /** * Result result = junit . run ( new Computer ( ) , StandardChangeTests . class ) ; */
public File getSdkRoot ( ) { } }

implementation: File dir = new File ( "." ) . getAbsoluteFile ( ) ; while ( dir != null ) { if ( dir . listFiles ( new FilenameFilter ( ) { @ Override public boolean accept ( File dir , String name ) { return "liquibase-sdk.bat" . equals ( name ) ; } } ) . length > 0 ) { return dir ; } dir = dir . getParentFile ( ) ; } throw new UnexpectedLiquibaseException ( "Could not find Liquibase SDK home. Please run liquibase-sdk from the " + "liquibase/sdk directory or one of it's sub directories" ) ;


signature:
public class SpringBootFatJar { /** * Method used to simplify an entryName
 * Ex : with path jar : / some / jar . jar ! / BOOT - INF / classes ! / db / changelog and entryName / BOOT - INF / classes / db / changelog
 * The simple entry name for Spring is db / changelog
 * ( / BOOT - INF / classes / is not needed and break the liquibase alphabetical sort order )
 * @ param entryName the entryName to simplify
 * @ param path file path
 * @ return the simple path */
public static String getSimplePathForResources ( String entryName , String path ) { } }

implementation: String [ ] components = path . split ( "!" ) ; if ( components . length == 3 ) { if ( components [ 1 ] . endsWith ( ".jar" ) ) { return components [ 2 ] . substring ( 1 ) ; } else { return entryName . replaceFirst ( components [ 1 ] , "" ) . substring ( 1 ) ; } } return entryName ;


signature:
public class ChangeSetStatus { /** * Convenience method to check wither a given ChangeSetFilter type is a reason for running the change set or not . */
public boolean isFilteredBy ( Class < ? extends ChangeSetFilter > filterType ) { } }

implementation: if ( ! willRun ) { return false ; } if ( filterResults == null ) { return false ; } for ( ChangeSetFilterResult result : filterResults ) { if ( result . getFilter ( ) . equals ( filterType ) ) { return true ; } } return false ;


signature:
public class JdbcUtils { /** * Return a single result object from the given Collection .
 * < p > Throws an exception if 0 or more than 1 element found .
 * @ param results the result Collection ( can be < code > null < / code > )
 * @ return the single result object */
public static Object requiredSingleResult ( Collection results ) throws DatabaseException { } }

implementation: int size = ( ( results != null ) ? results . size ( ) : 0 ) ; if ( size == 0 ) { throw new DatabaseException ( "Empty result set, expected one row" ) ; } if ( results . size ( ) > 1 ) { throw new DatabaseException ( "Result set larger than one row" ) ; } return results . iterator ( ) . next ( ) ;


signature:
public class JdbcUtils { /** * Checks whether a result set has a column matching the specified column name .
 * The column name is first changed to match the database format .
 * E . g . an unquoted columnName in h2 will be converted to uppercase so the column name that is
 * being checked for is really the uppercase version of the column name ,
 * @ param rs result set to check
 * @ param columnNameToCheck column name to check
 * @ return The value if found , null if not found */
public static String getValueForColumn ( ResultSet rs , String columnNameToCheck , Database database ) throws SQLException { } }

implementation:
ResultSetMetaData metadata = rs . getMetaData ( ) ; int numberOfColumns = metadata . getColumnCount ( ) ; String correctedColumnName = database . correctObjectName ( columnNameToCheck , Column . class ) ; // get the column names ; column indexes start from 1
for ( int i = 1 ; i < ( numberOfColumns + 1 ) ; i ++ ) { String columnName = metadata . getColumnLabel ( i ) ; // Get the name of the column ' s table name
if ( correctedColumnName . equalsIgnoreCase ( columnName ) ) { return rs . getString ( columnName ) ; } } return null ;


signature:
public class LiquibaseConfiguration { /** * Returns the singleton instance , creating it if necessary . On creation , the configuration is initialized with { @ link liquibase . configuration . SystemPropertyProvider } */
public static synchronized LiquibaseConfiguration getInstance ( ) { } }

implementation: if ( instance == null ) { instance = new LiquibaseConfiguration ( ) ; instance . init ( new SystemPropertyProvider ( ) ) ; } return instance ;


signature:
public class LiquibaseConfiguration { /** * Re - initialize the configuration with the given ConfigurationProviders . Any existing
 * AbstractConfigurationContainer instances are reset to defaults . */
public void init ( ConfigurationValueProvider ... configurationValueProviders ) { } }

implementation: if ( configurationValueProviders == null ) { configurationValueProviders = new ConfigurationValueProvider [ 0 ] ; } this . configurationValueProviders = configurationValueProviders ; this . reset ( ) ;


signature:
public class LiquibaseConfiguration { /** * Return an instance of the passed AbstractConfigurationContainer type .
 * The same instance is returned from every call to getConfiguration ( ) */
public < T extends ConfigurationContainer > T getConfiguration ( Class < T > type ) { } }

implementation: if ( ! configurations . containsKey ( type ) ) { configurations . put ( type , createConfiguration ( type ) ) ; } return ( T ) configurations . get ( type ) ;


signature:
public class LiquibaseConfiguration { /** * Convenience method for liquibaseConfiguration . getConfiguration ( type ) . getProperty ( property ) */
public ConfigurationProperty getProperty ( Class < ? extends ConfigurationContainer > type , String property ) { } }

implementation: ConfigurationContainer configuration = getConfiguration ( type ) ; return configuration . getProperty ( property ) ;


signature:
public class LiquibaseConfiguration { /** * Convenience method for { @ link # describeValueLookupLogic ( ConfigurationProperty ) } */
public String describeValueLookupLogic ( Class < ? extends ConfigurationContainer > config , String property ) { } }

implementation: return describeValueLookupLogic ( getProperty ( config , property ) ) ;


signature:
public class LiquibaseConfiguration { /** * Generates a human consumable description of how the configured ConfigurationValueProvider ( s ) will
 * attempt to set a default value . */
public String describeValueLookupLogic ( ConfigurationProperty property ) { } }

implementation: List < String > reasons = new ArrayList < > ( ) ; for ( ConfigurationValueProvider container : configurationValueProviders ) { reasons . add ( container . describeValueLookupLogic ( property ) ) ; } return StringUtil . join ( reasons , " AND " ) ;


signature:
public class CommandLineUtils { /** * Executes RawSqlStatements particular to each database engine to set the default schema for the given Database
 * @ param username The username used for the connection . Used with MSSQL databases
 * @ param defaultCatalogName Catalog name and schema name are similar concepts .
 * Used if defaultCatalogName is null .
 * @ param defaultSchemaName Catalog name and schema name are similar concepts .
 * Catalog is used with Oracle , DB2 and MySQL , and takes
 * precedence over the schema name .
 * @ param database Which Database object is affected by the initialization .
 * @ throws DatabaseException */
public static void initializeDatabase ( String username , String defaultCatalogName , String defaultSchemaName , Database database ) throws DatabaseException { } }

implementation: if ( ( ( defaultCatalogName != null ) || ( defaultSchemaName != null ) ) && ! ( database . getConnection ( ) instanceof OfflineConnection ) ) { if ( database instanceof OracleDatabase ) { String schema = defaultCatalogName ; if ( schema == null ) { schema = defaultSchemaName ; } ExecutorService . getInstance ( ) . getExecutor ( database ) . execute ( new RawSqlStatement ( "ALTER SESSION SET CURRENT_SCHEMA=" + database . escapeObjectName ( schema , Schema . class ) ) ) ; } else if ( database instanceof PostgresDatabase && defaultSchemaName != null ) { ExecutorService . getInstance ( ) . getExecutor ( database ) . execute ( new RawSqlStatement ( "SET SEARCH_PATH TO " + database . escapeObjectName ( defaultSchemaName , Schema . class ) ) ) ; } else if ( database instanceof AbstractDb2Database ) { String schema = defaultCatalogName ; if ( schema == null ) { schema = defaultSchemaName ; } ExecutorService . getInstance ( ) . getExecutor ( database ) . execute ( new RawSqlStatement ( "SET CURRENT SCHEMA " + schema ) ) ; } else if ( database instanceof MySQLDatabase ) { String schema = defaultCatalogName ; if ( schema == null ) { schema = defaultSchemaName ; } ExecutorService . getInstance ( ) . getExecutor ( database ) . execute ( new RawSqlStatement ( "USE " + schema ) ) ; } }


signature:
public class DefaultDatabaseObjectComparator { /** * Static so it can be used in other comparators if needed */
public static boolean nameMatches ( DatabaseObject databaseObject1 , DatabaseObject databaseObject2 , Database accordingTo ) { } }

implementation: String object1Name = accordingTo . correctObjectName ( databaseObject1 . getName ( ) , databaseObject1 . getClass ( ) ) ; String object2Name = accordingTo . correctObjectName ( databaseObject2 . getName ( ) , databaseObject2 . getClass ( ) ) ; if ( ( object1Name == null ) && ( object2Name == null ) ) { return true ; } if ( ( object1Name == null ) || ( object2Name == null ) ) { return false ; } if ( accordingTo . isCaseSensitive ( ) ) { return object1Name . equals ( object2Name ) ; } else { return object1Name . equalsIgnoreCase ( object2Name ) ; }


signature:
public class ClassLoaderResourceAccessor { /** * Called by constructor to create all the root paths from the given classloader .
 * Works best if the passed classLoader is a { @ link URLClassLoader } because it can get the root file / dirs directly .
 * If it is not a URLClassLoader , it still attempts to find files by looking up base packages and MANIFEST . MF files .
 * This may miss some roots , however , and so if you are not using a URLClassLoader consider using a custom subclass . */
protected List < Path > findRootPaths ( ClassLoader classLoader ) throws Exception { } }

implementation:
if ( classLoader == null ) { return new ArrayList < > ( ) ; } Logger logger = Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) ; List < URL > returnUrls = new ArrayList < > ( ) ; if ( classLoader instanceof URLClassLoader ) { returnUrls . addAll ( CollectionUtil . createIfNull ( Arrays . asList ( ( ( URLClassLoader ) classLoader ) . getURLs ( ) ) ) ) ; } else { logger . info ( "Found non-URL ClassLoader classloader " + classLoader . toString ( ) + ". Liquibase will try to figure out now to load resources from it, some may be missed. Consider using a custom ClassLoaderResourceAccessor subclass." ) ; Set < String > seenUrls = new HashSet < > ( ) ; // need to track externalForm as a string to avoid java problem with URL . equals making a network call
Enumeration < URL > emptyPathUrls = classLoader . getResources ( "" ) ; while ( emptyPathUrls . hasMoreElements ( ) ) { URL url = emptyPathUrls . nextElement ( ) ; if ( seenUrls . add ( url . toExternalForm ( ) ) ) { returnUrls . add ( url ) ; } } Enumeration < URL > metaInfoPathUrls = classLoader . getResources ( "META-INF" ) ; while ( metaInfoPathUrls . hasMoreElements ( ) ) { String originalUrl = metaInfoPathUrls . nextElement ( ) . toExternalForm ( ) ; String finalUrl = originalUrl . replaceFirst ( "/META-INF" , "" ) ; if ( finalUrl . startsWith ( "jar:" ) ) { if ( finalUrl . endsWith ( "!" ) ) { finalUrl = finalUrl . replaceFirst ( "^jar:" , "" ) . replaceFirst ( "!$" , "" ) ; } else { logger . warning ( "ClassLoader URL " + finalUrl + " starts with jar: but does not end with !, don't knnow how to handle it. Skipping" ) ; continue ; } } URL finalUrlObj = new URL ( finalUrl ) ; if ( seenUrls . add ( finalUrlObj . toExternalForm ( ) ) ) { returnUrls . add ( finalUrlObj ) ; } } } List < Path > returnPaths = new ArrayList < > ( ) ; for ( URL url : returnUrls ) { Path path = rootUrlToPath ( url ) ; if ( path != null ) { logger . fine ( "Found classloader root at " + path . toString ( ) ) ; returnPaths . add ( path ) ; } } return returnPaths ;


signature:
public class ClassLoaderResourceAccessor { /** * Converts the given URL to a Path . Used by { @ link # findRootPaths ( ClassLoader ) } to convert classloader URLs to Paths to pass to { @ link # addRootPath ( Path ) } .
 * @ return null if url cannot or should not be converted to a Path . */
protected Path rootUrlToPath ( URL url ) { } }

implementation: String protocol = url . getProtocol ( ) ; switch ( protocol ) { case "file" : return FileSystems . getDefault ( ) . getPath ( url . getFile ( ) . replace ( "%20" , " " ) . replaceFirst ( "/(\\w)\\:/" , "$1:/" ) ) ; default : Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . warning ( "Unknown protocol '" + protocol + "' for ClassLoaderResourceAccessor on " + url . toExternalForm ( ) ) ; return null ; }


signature: public class ForeignKeySnapshotGenerator { @ Override protected void addTo ( DatabaseObject foundObject , DatabaseSnapshot snapshot ) throws DatabaseException , InvalidExampleException { } }

implementation: if ( ! snapshot . getSnapshotControl ( ) . shouldInclude ( ForeignKey . class ) ) { return ; } if ( foundObject instanceof Table ) { Table table = ( Table ) foundObject ; Database database = snapshot . getDatabase ( ) ; Schema schema ; schema = table . getSchema ( ) ; Set < String > seenFks = new HashSet < > ( ) ; List < CachedRow > importedKeyMetadataResultSet ; try { importedKeyMetadataResultSet = ( ( JdbcDatabaseSnapshot ) snapshot ) . getMetaDataFromCache ( ) . getForeignKeys ( ( ( AbstractJdbcDatabase ) database ) . getJdbcCatalogName ( schema ) , ( ( AbstractJdbcDatabase ) database ) . getJdbcSchemaName ( schema ) , database . correctObjectName ( table . getName ( ) , Table . class ) , null ) ; for ( CachedRow row : importedKeyMetadataResultSet ) { ForeignKey fk = new ForeignKey ( ) . setName ( row . getString ( "FK_NAME" ) ) . setForeignKeyTable ( table ) ; if ( seenFks . add ( fk . getName ( ) ) ) { table . getOutgoingForeignKeys ( ) . add ( fk ) ; } } } catch ( Exception e ) { throw new DatabaseException ( e ) ; } }


signature:
public class ForeignKeySnapshotGenerator { /** * Method to map ' validate ' option for FK . This thing works only for ORACLE
 * @ param database - DB where FK will be created
 * @ param foreignKey - FK object to persist validate option
 * @ param cachedRow - it ' s a cache - map to get metadata about FK */
private void setValidateOptionIfAvailable ( Database database , ForeignKey foreignKey , CachedRow cachedRow ) { } }

implementation: if ( ! ( database instanceof OracleDatabase ) ) { return ; } final String constraintValidate = cachedRow . getString ( "FK_VALIDATE" ) ; final String VALIDATE = "VALIDATED" ; if ( constraintValidate != null && ! constraintValidate . isEmpty ( ) ) { foreignKey . setShouldValidate ( VALIDATE . equals ( cleanNameFromDatabase ( constraintValidate . trim ( ) , database ) ) ) ; }


signature:
public class ForeignKeySnapshotGenerator { /** * Sql server JDBC drivers prior to 6.3.3 used sp _ fkeys to determine the delete / cascade metadata .
 * The sp _ fkeys stored procedure spec says that returned integer values of 0 , 1 , 2 , or 4
 * translate to cascade , noAction , SetNull , or SetDefault which are not the values in the JDBC
 * standard .
 * If this method returns true , the sp _ fkeys values should be used . Otherwise use the standard jdbc logic
 * The change in logic went in with https : / / github . com / Microsoft / mssql - jdbc / pull / 490 */
private boolean driverUsesSpFkeys ( Database database ) throws DatabaseException { } }

implementation: if ( ! ( database instanceof MSSQLDatabase ) ) { return false ; } DatabaseConnection connection = database . getConnection ( ) ; if ( ! ( connection instanceof JdbcConnection ) ) { return false ; } try { DatabaseMetaData metaData = ( ( JdbcConnection ) connection ) . getMetaData ( ) ; int driverMajorVersion = metaData . getDriverMajorVersion ( ) ; int driverMinorVersion = metaData . getDriverMinorVersion ( ) ; String driverName = metaData . getDriverName ( ) ; if ( ! driverName . startsWith ( "Microsoft" ) ) { return false ; } if ( driverMajorVersion > 6 || ( driverMajorVersion == 6 && driverMinorVersion >= 3 ) ) { return false ; } return true ; } catch ( SQLException e ) { throw new DatabaseException ( e ) ; }


signature:
public class CreateTableGeneratorInformix { /** * Informix SQL - specific implementation of the CREATE TABLE SQL generator .
 * @ param statement The properties of the statement that we will translate into SQL
 * @ param database For this implementation always an object of the InformixDatabase type
 * @ param sqlGeneratorChain Other generators in the pipeline for this command
 * @ return An array of Sql [ ] statements containing the requested SQL statements for Informix SQL */
@ Override public Sql [ ] generateSql ( CreateTableStatement statement , Database database , SqlGeneratorChain sqlGeneratorChain ) { } }

implementation:
StringBuilder buffer = new StringBuilder ( ) ; // CREATE TABLE table _ name . . .
buffer . append ( "CREATE TABLE " ) . append ( database . escapeTableName ( statement . getCatalogName ( ) , statement . getSchemaName ( ) , statement . getTableName ( ) ) ) . append ( " " ) ; buffer . append ( "(" ) ; Iterator < String > columnIterator = statement . getColumns ( ) . iterator ( ) ; List < String > primaryKeyColumns = new LinkedList < > ( ) ; /* * Build the list of columns and constraints in the form
 * column1,
 * columnN ,
 * constraint1,
 * constraintN */
while ( columnIterator . hasNext ( ) ) { String column = columnIterator . next ( ) ; buffer . append ( database . escapeColumnName ( statement . getCatalogName ( ) , statement . getSchemaName ( ) , statement . getTableName ( ) , column ) ) ; buffer . append ( " " ) . append ( statement . getColumnTypes ( ) . get ( column ) . toDatabaseDataType ( database ) . toSql ( ) ) ; AutoIncrementConstraint autoIncrementConstraint = null ; for ( AutoIncrementConstraint currentAutoIncrementConstraint : statement . getAutoIncrementConstraints ( ) ) { if ( column . equals ( currentAutoIncrementConstraint . getColumnName ( ) ) ) { autoIncrementConstraint = currentAutoIncrementConstraint ; break ; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null ; boolean isPrimaryKeyColumn = ( statement . getPrimaryKeyConstraint ( ) != null ) && statement . getPrimaryKeyConstraint ( ) . getColumns ( ) . contains ( column ) ; if ( isPrimaryKeyColumn ) { primaryKeyColumns . add ( column ) ; } if ( statement . getDefaultValue ( column ) != null ) { Object defaultValue = statement . getDefaultValue ( column ) ; buffer . append ( " DEFAULT " ) ; buffer . append ( statement . getColumnTypes ( ) . get ( column ) . objectToSql ( defaultValue , database ) ) ; } if ( isAutoIncrementColumn ) { // TODO : check if database supports auto increment on non primary key column
if ( database . supportsAutoIncrement ( ) ) { String autoIncrementClause = database . getAutoIncrementClause ( autoIncrementConstraint . getStartWith ( ) , autoIncrementConstraint . getIncrementBy ( ) ) ; if ( ! autoIncrementClause . isEmpty ( ) ) { buffer . append ( " " ) . append ( autoIncrementClause ) ; } } else { Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . warning ( LogType . LOG , database . getShortName ( ) + " does not support autoincrement columns as requested for " + ( database . escapeTableName ( statement . getCatalogName ( ) , statement . getSchemaName ( ) , statement . getTableName ( ) ) ) ) ; } } if ( statement . getNotNullColumns ( ) . get ( column ) != null ) { buffer . append ( " NOT NULL" ) ; } if ( columnIterator . hasNext ( ) ) { buffer . append ( ", " ) ; } } buffer . append ( "," ) ; /* * We only create a PRIMARY KEY constraint if one is defined and has at least 1 column .
 * General Informix SQL syntax , according to the docs for 11.5
 * https : / / www . ibm . com / support / knowledgecenter / SSGU8G _ 11.50.0 / com . ibm . sqls . doc / ids _ sqs _ 0100 . htm
 * is :
 * ( columns . . . - - > PRIMARY KEY ( column1 , . . . , columnN ) [ CONSTRAINT pk _ name ] */
PrimaryKeyConstraint pkConstraint = statement . getPrimaryKeyConstraint ( ) ; if ( ( statement . getPrimaryKeyConstraint ( ) != null ) && ! statement . getPrimaryKeyConstraint ( ) . getColumns ( ) . isEmpty ( ) ) { buffer . append ( " PRIMARY KEY (" ) ; buffer . append ( StringUtil . join ( primaryKeyColumns , ", " ) ) ; buffer . append ( ")" ) ; if ( ! StringUtil . isEmpty ( pkConstraint . getConstraintName ( ) ) ) { buffer . append ( " CONSTRAINT " ) ; buffer . append ( database . escapeConstraintName ( pkConstraint . getConstraintName ( ) ) ) ; } // Setting up table space for PK ' s index if it exist
buffer . append ( "," ) ; } for ( ForeignKeyConstraint fkConstraint : statement . getForeignKeyConstraints ( ) ) { String referencesString = fkConstraint . getReferences ( ) ; if ( ! referencesString . contains ( "." ) && ( database . getDefaultSchemaName ( ) != null ) ) { referencesString = database . getDefaultSchemaName ( ) + "." + referencesString ; } buffer . append ( " FOREIGN KEY (" ) . append ( database . escapeColumnName ( statement . getCatalogName ( ) , statement . getSchemaName ( ) , statement . getTableName ( ) , fkConstraint . getColumn ( ) ) ) . append ( ") REFERENCES " ) . append ( referencesString ) ; if ( fkConstraint . isDeleteCascade ( ) ) { buffer . append ( " ON DELETE CASCADE" ) ; } buffer . append ( " CONSTRAINT " ) ; buffer . append ( database . escapeConstraintName ( fkConstraint . getForeignKeyName ( ) ) ) ; if ( fkConstraint . isInitiallyDeferred ( ) ) { buffer . append ( " INITIALLY DEFERRED" ) ; } if ( fkConstraint . isDeferrable ( ) ) { buffer . append ( " DEFERRABLE" ) ; } buffer . append ( "," ) ; } // TODO : code duplication . Maybe we can merge this whole class into CreateTableGenerator again .
for ( UniqueConstraint uniqueConstraint : statement . getUniqueConstraints ( ) ) { if ( ( uniqueConstraint . getConstraintName ( ) != null ) && ! constraintNameAfterUnique ( database ) ) { buffer . append ( " CONSTRAINT " ) ; buffer . append ( database . escapeConstraintName ( uniqueConstraint . getConstraintName ( ) ) ) ; } buffer . append ( " UNIQUE (" ) ; buffer . append ( database . escapeColumnNameList ( StringUtil . join ( uniqueConstraint . getColumns ( ) , ", " ) ) ) ; buffer . append ( ")" ) ; if ( ( uniqueConstraint . getConstraintName ( ) != null ) && constraintNameAfterUnique ( database ) ) { buffer . append ( " CONSTRAINT " ) ; buffer . append ( database . escapeConstraintName ( uniqueConstraint . getConstraintName ( ) ) ) ; } buffer . append ( "," ) ; } /* * Here , the list of columns and constraints in the form
 * ( column1 , . . . , columnN , constraint1 , . . . , constraintN ,
 * ends . We cannot leave an expression like " , ) " , so we remove the last comma . */
String sql = buffer . toString ( ) . replaceFirst ( ",\\s*$" , "" ) + ")" ; if ( ( statement . getTablespace ( ) != null ) && database . supportsTablespaces ( ) ) { sql += " IN " + statement . getTablespace ( ) ; } return new Sql [ ] { new UnparsedSql ( sql , new Table ( ) . setName ( statement . getTableName ( ) ) . setSchema ( new Schema ( statement . getCatalogName ( ) , statement . getSchemaName ( ) ) ) ) } ;


signature:
public class CDILiquibase { /** * Subclasses may override this method add change some database settings such as
 * default schema before returning the database object .
 * @ param c
 * @ return a Database implementation retrieved from the { @ link liquibase . database . DatabaseFactory } .
 * @ throws DatabaseException */
protected Database createDatabase ( Connection c ) throws DatabaseException { } }

implementation: Database database = DatabaseFactory . getInstance ( ) . findCorrectDatabaseImplementation ( new JdbcConnection ( c ) ) ; if ( config . getDefaultSchema ( ) != null ) { database . setDefaultSchemaName ( config . getDefaultSchema ( ) ) ; } return database ;


signature:
public class SnapshotControl { /** * Adds a new DatabaseObject type to the list of object types to be included in snapshots .
 * @ param type The type to be added
 * @ param database The database to check for any dependent types that need to be included as well
 * @ return true if the type was added to the list , false if it was already present . */
public boolean addType ( Class < ? extends DatabaseObject > type , Database database ) { } }

implementation: boolean added = this . types . add ( type ) ; if ( added ) { for ( Class < ? extends DatabaseObject > container : SnapshotGeneratorFactory . getInstance ( ) . getContainerTypes ( type , database ) ) { addType ( container , database ) ; } } return added ;


signature:
public class AbstractSQLChange { /** * Calculates the checksum based on the contained SQL .
 * @ see liquibase . change . AbstractChange # generateCheckSum ( ) */
@ Override public CheckSum generateCheckSum ( ) { } }

implementation: InputStream stream = null ; try { stream = openSqlStream ( ) ; String sql = this . sql ; if ( ( stream == null ) && ( sql == null ) ) { sql = "" ; } if ( sql != null ) { stream = new ByteArrayInputStream ( sql . getBytes ( LiquibaseConfiguration . getInstance ( ) . getConfiguration ( GlobalConfiguration . class ) . getOutputEncoding ( ) ) ) ; } return CheckSum . compute ( new NormalizingStream ( this . getEndDelimiter ( ) , this . isSplitStatements ( ) , this . isStripComments ( ) , stream ) , false ) ; } catch ( IOException e ) { throw new UnexpectedLiquibaseException ( e ) ; } finally { if ( stream != null ) { try { stream . close ( ) ; } catch ( IOException e ) { Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . fine ( LogType . LOG , "Error closing stream" , e ) ; } } }


signature:
public class AbstractSQLChange { /** * Generates one or more SqlStatements depending on how the SQL should be parsed .
 * If split statements is set to true then the SQL is split and each command is made into a separate SqlStatement .
 * < p > < / p >
 * If stripping comments is true then any comments are removed before the splitting is executed .
 * The set SQL is passed through the { @ link java . sql . Connection # nativeSQL } method if a connection is available . */
@ Override public SqlStatement [ ] generateStatements ( Database database ) { } }

implementation: List < SqlStatement > returnStatements = new ArrayList < > ( ) ; String sql = StringUtil . trimToNull ( getSql ( ) ) ; if ( sql == null ) { return new SqlStatement [ 0 ] ; } String processedSQL = normalizeLineEndings ( sql ) ; for ( String statement : StringUtil . processMutliLineSQL ( processedSQL , isStripComments ( ) , isSplitStatements ( ) , getEndDelimiter ( ) ) ) { if ( database instanceof MSSQLDatabase ) { statement = statement . replaceAll ( "\\n" , "\r\n" ) ; } String escapedStatement = statement ; try { if ( database . getConnection ( ) != null ) { escapedStatement = database . getConnection ( ) . nativeSQL ( statement ) ; } } catch ( DatabaseException e ) { escapedStatement = statement ; } returnStatements . add ( new RawSqlStatement ( escapedStatement , getEndDelimiter ( ) ) ) ; } return returnStatements . toArray ( new SqlStatement [ returnStatements . size ( ) ] ) ;


signature:
public class SpringLiquibase { /** * Executed automatically when the bean is initialized . */
@ Override public void afterPropertiesSet ( ) throws LiquibaseException { } }

implementation: ConfigurationProperty shouldRunProperty = LiquibaseConfiguration . getInstance ( ) . getProperty ( GlobalConfiguration . class , GlobalConfiguration . SHOULD_RUN ) ; if ( ! shouldRunProperty . getValue ( Boolean . class ) ) { Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . info ( LogType . LOG , "Liquibase did not run because " + LiquibaseConfiguration . getInstance ( ) . describeValueLookupLogic ( shouldRunProperty ) + " was set to false" ) ; return ; } if ( ! shouldRun ) { Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . info ( LogType . LOG , "Liquibase did not run because 'shouldRun' " + "property was set " + "to false on " + getBeanName ( ) + " Liquibase Spring bean." ) ; return ; } Connection c = null ; Liquibase liquibase = null ; try { c = getDataSource ( ) . getConnection ( ) ; liquibase = createLiquibase ( c ) ; generateRollbackFile ( liquibase ) ; performUpdate ( liquibase ) ; } catch ( SQLException e ) { throw new DatabaseException ( e ) ; } finally { Database database = null ; if ( liquibase != null ) { database = liquibase . getDatabase ( ) ; } if ( database != null ) { database . close ( ) ; } }


signature:
public class SpringLiquibase { /** * Subclasses may override this method add change some database settings such as
 * default schema before returning the database object .
 * @ param c
 * @ return a Database implementation retrieved from the { @ link DatabaseFactory } .
 * @ throws DatabaseException */
protected Database createDatabase ( Connection c , ResourceAccessor resourceAccessor ) throws DatabaseException { } }

implementation: DatabaseConnection liquibaseConnection ; if ( c == null ) { log . warning ( LogType . LOG , "Null connection returned by liquibase datasource. Using offline unknown database" ) ; liquibaseConnection = new OfflineConnection ( "offline:unknown" , resourceAccessor ) ; } else { liquibaseConnection = new JdbcConnection ( c ) ; } Database database = DatabaseFactory . getInstance ( ) . findCorrectDatabaseImplementation ( liquibaseConnection ) ; if ( StringUtil . trimToNull ( this . defaultSchema ) != null ) { if ( database . supportsSchemas ( ) ) { database . setDefaultSchemaName ( this . defaultSchema ) ; } else if ( database . supportsCatalogs ( ) ) { database . setDefaultCatalogName ( this . defaultSchema ) ; } } if ( StringUtil . trimToNull ( this . liquibaseSchema ) != null ) { if ( database . supportsSchemas ( ) ) { database . setLiquibaseSchemaName ( this . liquibaseSchema ) ; } else if ( database . supportsCatalogs ( ) ) { database . setLiquibaseCatalogName ( this . liquibaseSchema ) ; } } if ( StringUtil . trimToNull ( this . liquibaseTablespace ) != null && database . supportsTablespaces ( ) ) { database . setLiquibaseTablespaceName ( this . liquibaseTablespace ) ; } if ( StringUtil . trimToNull ( this . databaseChangeLogTable ) != null ) { database . setDatabaseChangeLogTableName ( this . databaseChangeLogTable ) ; } if ( StringUtil . trimToNull ( this . databaseChangeLogLockTable ) != null ) { database . setDatabaseChangeLogLockTableName ( this . databaseChangeLogLockTable ) ; } return database ;


signature:
public class AbstractCSVToBean { /** * Returns the trimmed value of the string only if the property the string is describing should be trimmed
 * to be converted to that type .
 * @ param s - String describing the value .
 * @ param prop - property descriptor of the value .
 * @ return the string passed in if the property is a string otherwise it will return the string with the
 * beginning and end whitespace removed . */
protected String checkForTrim ( String s , PropertyDescriptor prop ) { } }

implementation: return trimmableProperty ( prop ) ? s . trim ( ) : s ;


signature:
public class AbstractCSVToBean { /** * Convert a string value to its Object value .
 * @ param value - String value
 * @ param prop - PropertyDescriptor
 * @ return The object set to value ( i . e . Integer ) . Will return String if no PropertyEditor is found .
 * @ throws ReflectiveOperationException - Thrown on error getting the property editor from the property descriptor . */
protected Object convertValue ( String value , PropertyDescriptor prop ) throws ReflectiveOperationException { } }

implementation: PropertyEditor editor = getPropertyEditor ( prop ) ; Object obj = value ; if ( null != editor ) { editor . setAsText ( value ) ; obj = editor . getValue ( ) ; } return obj ;


signature:
public class Main { /** * Entry point . This is what gets executes when starting this program from the command line . This is actually
 * a simple wrapper so that an errorlevel of ! = 0 is guaranteed in case of an uncaught exception .
 * @ param args the command line arguments */
public static void main ( String [ ] args ) { } }

implementation: int errorLevel = 0 ; try { errorLevel = run ( args ) ; } catch ( Throwable e ) { System . exit ( - 1 ) ; } System . exit ( errorLevel ) ;


signature:
public class Main { /** * Process the command line arguments and perform the appropriate main action ( update , rollback etc . )
 * @ param args the command line arguments
 * @ return the errorlevel to be returned to the operating system , e . g . for further processing by scripts
 * @ throws LiquibaseException a runtime exception */
public static int run ( String [ ] args ) throws Exception { } }

implementation:
return Scope . child ( null , Collections . singletonMap ( Scope . Attr . logService . name ( ) , new CommandLineLoggerService ( ) ) , new Scope . ScopedRunnerWithReturn < Integer > ( ) { @ Override public Integer run ( ) throws Exception { Logger log = Scope . getCurrentScope ( ) . getLog ( Main . class ) ; boolean outputLoggingEnabled = false ; try { GlobalConfiguration globalConfiguration = LiquibaseConfiguration . getInstance ( ) . getConfiguration ( GlobalConfiguration . class ) ; if ( ! globalConfiguration . getShouldRun ( ) ) { log . warning ( LogType . USER_MESSAGE , ( String . format ( coreBundle . getString ( "did.not.run.because.param.was.set.to.false" ) , LiquibaseConfiguration . getInstance ( ) . describeValueLookupLogic ( globalConfiguration . getProperty ( GlobalConfiguration . SHOULD_RUN ) ) ) ) ) ; return 0 ; } Main main = new Main ( ) ; log . info ( LogType . USER_MESSAGE , CommandLineUtils . getBanner ( ) ) ; if ( ( args . length == 1 ) && ( "--" + OPTIONS . HELP ) . equals ( args [ 0 ] ) ) { main . printHelp ( System . out ) ; return 0 ; } else if ( ( args . length == 1 ) && ( "--" + OPTIONS . VERSION ) . equals ( args [ 0 ] ) ) { log . info ( LogType . USER_MESSAGE , String . format ( coreBundle . getString ( "version.number" ) , LiquibaseUtil . getBuildVersion ( ) + StreamUtil . getLineSeparator ( ) ) ) ; return 0 ; } try { main . parseOptions ( args ) ; } catch ( CommandLineParsingException e ) { log . warning ( LogType . USER_MESSAGE , coreBundle . getString ( "how.to.display.help" ) ) ; throw e ; } List < String > setupMessages = main . checkSetup ( ) ; if ( ! setupMessages . isEmpty ( ) ) { main . printHelp ( setupMessages , System . err ) ; return 1 ; } main . applyDefaults ( ) ; Scope . child ( Scope . Attr . resourceAccessor , new ClassLoaderResourceAccessor ( main . configureClassLoader ( ) ) , ( ) -> { main . doMigration ( ) ; if ( COMMANDS . UPDATE . equals ( main . command ) ) { log . info ( LogType . USER_MESSAGE , coreBundle . getString ( "update.successful" ) ) ; } else if ( main . command . startsWith ( COMMANDS . ROLLBACK ) && ! main . command . endsWith ( "SQL" ) ) { log . info ( LogType . USER_MESSAGE , coreBundle . getString ( "rollback.successful" ) ) ; } else if ( ! main . command . endsWith ( "SQL" ) ) { log . info ( LogType . USER_MESSAGE , String . format ( coreBundle . getString ( "command.successful" ) , main . command ) ) ; } } ) ; } catch ( Exception e ) { String message = e . getMessage ( ) ; if ( e . getCause ( ) != null ) { message = e . getCause ( ) . getMessage ( ) ; } if ( message == null ) { message = coreBundle . getString ( "unknown.reason" ) ; } // At a minimum , log the message . We don ' t need to print the stack
// trace because the logger already did that upstream .
try { if ( e . getCause ( ) instanceof ValidationFailedException ) { ( ( ValidationFailedException ) e . getCause ( ) ) . printDescriptiveError ( System . out ) ; } else { log . severe ( LogType . USER_MESSAGE , ( String . format ( coreBundle . getString ( "unexpected.error" ) , message ) ) , e ) ; log . severe ( LogType . USER_MESSAGE , generateLogLevelWarningMessage ( outputLoggingEnabled ) ) ; } } catch ( IllegalFormatException e1 ) { e1 . printStackTrace ( ) ; } throw new LiquibaseException ( String . format ( coreBundle . getString ( "unexpected.error" ) , message ) , e ) ; } return 0 ; } } ) ;


signature:
public class Main { /** * What the number 2 stands for is obvious from the context */
@ SuppressWarnings ( "squid:S109" ) private static String [ ] splitArg ( String arg ) throws CommandLineParsingException { } }

implementation: String [ ] splitArg = arg . split ( "=" , 2 ) ; if ( splitArg . length < 2 ) { throw new CommandLineParsingException ( String . format ( coreBundle . getString ( "could.not.parse.expression" ) , arg ) ) ; } splitArg [ 0 ] = splitArg [ 0 ] . replaceFirst ( "--" , "" ) ; return splitArg ;


signature:
public class Main { /** * Returns true if the parameter - - changeLogFile is requited for a given command
 * @ param command the command to test
 * @ return true if a ChangeLog is required , false if not . */
private static boolean isChangeLogRequired ( String command ) { } }

implementation: return command . toLowerCase ( ) . startsWith ( COMMANDS . UPDATE ) || command . toLowerCase ( ) . startsWith ( COMMANDS . ROLLBACK ) || COMMANDS . CALCULATE_CHECKSUM . equalsIgnoreCase ( command ) || COMMANDS . STATUS . equalsIgnoreCase ( command ) || COMMANDS . VALIDATE . equalsIgnoreCase ( command ) || COMMANDS . CHANGELOG_SYNC . equalsIgnoreCase ( command ) || COMMANDS . CHANGELOG_SYNC_SQL . equalsIgnoreCase ( command ) || COMMANDS . GENERATE_CHANGELOG . equalsIgnoreCase ( command ) ;


signature:
public class Main { /** * Returns true if the given arg is a valid main command of Liquibase .
 * @ param arg the String to test
 * @ return true if it is a valid main command , false if not */
private static boolean isCommand ( String arg ) { } }

implementation: return COMMANDS . MIGRATE . equals ( arg ) || COMMANDS . MIGRATE_SQL . equalsIgnoreCase ( arg ) || COMMANDS . UPDATE . equalsIgnoreCase ( arg ) || COMMANDS . UPDATE_SQL . equalsIgnoreCase ( arg ) || COMMANDS . UPDATE_COUNT . equalsIgnoreCase ( arg ) || COMMANDS . UPDATE_COUNT_SQL . equalsIgnoreCase ( arg ) || COMMANDS . UPDATE_TO_TAG . equalsIgnoreCase ( arg ) || COMMANDS . UPDATE_TO_TAG_SQL . equalsIgnoreCase ( arg ) || COMMANDS . ROLLBACK . equalsIgnoreCase ( arg ) || COMMANDS . ROLLBACK_TO_DATE . equalsIgnoreCase ( arg ) || COMMANDS . ROLLBACK_COUNT . equalsIgnoreCase ( arg ) || COMMANDS . ROLLBACK_SQL . equalsIgnoreCase ( arg ) || COMMANDS . ROLLBACK_TO_DATE_SQL . equalsIgnoreCase ( arg ) || COMMANDS . ROLLBACK_COUNT_SQL . equalsIgnoreCase ( arg ) || COMMANDS . FUTURE_ROLLBACK_SQL . equalsIgnoreCase ( arg ) || COMMANDS . FUTURE_ROLLBACK_COUNT_SQL . equalsIgnoreCase ( arg ) || COMMANDS . FUTURE_ROLLBACK_TO_TAG_SQL . equalsIgnoreCase ( arg ) || COMMANDS . UPDATE_TESTING_ROLLBACK . equalsIgnoreCase ( arg ) || COMMANDS . TAG . equalsIgnoreCase ( arg ) || COMMANDS . TAG_EXISTS . equalsIgnoreCase ( arg ) || COMMANDS . LIST_LOCKS . equalsIgnoreCase ( arg ) || COMMANDS . DROP_ALL . equalsIgnoreCase ( arg ) || COMMANDS . RELEASE_LOCKS . equalsIgnoreCase ( arg ) || COMMANDS . STATUS . equalsIgnoreCase ( arg ) || COMMANDS . UNEXPECTED_CHANGESETS . equalsIgnoreCase ( arg ) || COMMANDS . VALIDATE . equalsIgnoreCase ( arg ) || COMMANDS . HELP . equalsIgnoreCase ( arg ) || COMMANDS . DIFF . equalsIgnoreCase ( arg ) || COMMANDS . DIFF_CHANGELOG . equalsIgnoreCase ( arg ) || COMMANDS . GENERATE_CHANGELOG . equalsIgnoreCase ( arg ) || COMMANDS . SNAPSHOT . equalsIgnoreCase ( arg ) || COMMANDS . SNAPSHOT_REFERENCE . equalsIgnoreCase ( arg ) || COMMANDS . EXECUTE_SQL . equalsIgnoreCase ( arg ) || COMMANDS . CALCULATE_CHECKSUM . equalsIgnoreCase ( arg ) || COMMANDS . CLEAR_CHECKSUMS . equalsIgnoreCase ( arg ) || COMMANDS . DB_DOC . equalsIgnoreCase ( arg ) || COMMANDS . CHANGELOG_SYNC . equalsIgnoreCase ( arg ) || COMMANDS . CHANGELOG_SYNC_SQL . equalsIgnoreCase ( arg ) || COMMANDS . MARK_NEXT_CHANGESET_RAN . equalsIgnoreCase ( arg ) || COMMANDS . MARK_NEXT_CHANGESET_RAN_SQL . equalsIgnoreCase ( arg ) ;


signature:
public class Main { /** * Returns true if the given main command arg needs no special parameters .
 * @ param arg the main command to test
 * @ return true if arg is a valid main command and needs no special parameters , false in all other cases */
private static boolean isNoArgCommand ( String arg ) { } }

implementation: return COMMANDS . MIGRATE . equals ( arg ) || COMMANDS . MIGRATE_SQL . equalsIgnoreCase ( arg ) || COMMANDS . UPDATE . equalsIgnoreCase ( arg ) || COMMANDS . UPDATE_SQL . equalsIgnoreCase ( arg ) || COMMANDS . FUTURE_ROLLBACK_SQL . equalsIgnoreCase ( arg ) || COMMANDS . UPDATE_TESTING_ROLLBACK . equalsIgnoreCase ( arg ) || COMMANDS . LIST_LOCKS . equalsIgnoreCase ( arg ) || COMMANDS . DROP_ALL . equalsIgnoreCase ( arg ) || COMMANDS . RELEASE_LOCKS . equalsIgnoreCase ( arg ) || COMMANDS . VALIDATE . equalsIgnoreCase ( arg ) || COMMANDS . HELP . equalsIgnoreCase ( arg ) || COMMANDS . CLEAR_CHECKSUMS . equalsIgnoreCase ( arg ) || COMMANDS . CHANGELOG_SYNC . equalsIgnoreCase ( arg ) || COMMANDS . CHANGELOG_SYNC_SQL . equalsIgnoreCase ( arg ) || COMMANDS . MARK_NEXT_CHANGESET_RAN . equalsIgnoreCase ( arg ) || COMMANDS . MARK_NEXT_CHANGESET_RAN_SQL . equalsIgnoreCase ( arg ) ;


signature:
public class Main { /** * Extract a single object from a JAR file into a temporary file .
 * @ param jar the JAR file from which we will extract
 * @ param entry the object inside the JAR file that to be extracted
 * @ return a File object with the temporary file containing the extracted object
 * @ throws IOException if an I / O problem occurs */
private static File extract ( JarFile jar , JarEntry entry ) throws IOException { } }

implementation:
// expand to temp dir and add to list
File tempFile = File . createTempFile ( "liquibase.tmp" , null ) ; // read from jar and write to the tempJar file
try ( BufferedInputStream inStream = new BufferedInputStream ( jar . getInputStream ( entry ) ) ; BufferedOutputStream outStream = new BufferedOutputStream ( new FileOutputStream ( tempFile ) ) ) { int status ; while ( ( status = inStream . read ( ) ) != - 1 ) { outStream . write ( status ) ; } } return tempFile ;


signature:
public class Main { /** * Search for both liquibase . properties ( or whatever the name of the current
 * defaultsFile is ) and the " local " variant liquibase . local . properties . The contents of the local
 * variant overwrite parameters with the same name in the regular properties file .
 * @ throws CommandLineParsingException if an error occurs during parsing */
protected void parseDefaultPropertyFiles ( ) throws CommandLineParsingException { } }

implementation: File [ ] potentialPropertyFiles = new File [ 2 ] ; potentialPropertyFiles [ 0 ] = new File ( defaultsFile ) ; String localDefaultsPathName = defaultsFile . replaceFirst ( "(\\.[^\\.]+)$" , ".local$1" ) ; potentialPropertyFiles [ 1 ] = new File ( localDefaultsPathName ) ; for ( File potentialPropertyFile : potentialPropertyFiles ) { try { if ( potentialPropertyFile . exists ( ) ) { parseDefaultPropertyFileFromFile ( potentialPropertyFile ) ; } else { parseDefaultPropertyFileFromResource ( potentialPropertyFile ) ; } } catch ( IOException e ) { throw new CommandLineParsingException ( e ) ; } }


signature:
public class Main { /** * Open a property file that is embedded as a Java resource and parse it .
 * @ param potentialPropertyFile location and file name of the property file
 * @ throws IOException if the file cannot be opened
 * @ throws CommandLineParsingException if an error occurs during parsing */
private void parseDefaultPropertyFileFromResource ( File potentialPropertyFile ) throws IOException , CommandLineParsingException { } }

implementation: try ( InputStream resourceAsStream = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( potentialPropertyFile . getAbsolutePath ( ) ) ) { if ( resourceAsStream != null ) { parsePropertiesFile ( resourceAsStream ) ; } }


signature:
public class Main { /** * Open a regular property file ( not embedded in a resource - use { @ link # parseDefaultPropertyFileFromResource }
 * for that ) and parse it .
 * @ param potentialPropertyFile path and file name to the the property file
 * @ throws IOException if the file cannot be opened
 * @ throws CommandLineParsingException if an error occurs during parsing */
private void parseDefaultPropertyFileFromFile ( File potentialPropertyFile ) throws IOException , CommandLineParsingException { } }

implementation: try ( FileInputStream stream = new FileInputStream ( potentialPropertyFile ) ) { parsePropertiesFile ( stream ) ; }


signature:
public class Main { /** * On windows machines , it splits args on ' = ' signs . Put it back like it was . */
protected String [ ] fixupArgs ( String [ ] args ) { } }

implementation:
List < String > fixedArgs = new ArrayList < > ( ) ; for ( int i = 0 ; i < args . length ; i ++ ) { String arg = args [ i ] ; if ( ( arg . startsWith ( "--" ) || arg . startsWith ( "-D" ) ) && ! arg . contains ( "=" ) ) { String nextArg = null ; if ( ( i + 1 ) < args . length ) { nextArg = args [ i + 1 ] ; } if ( ( nextArg != null ) && ! nextArg . startsWith ( "--" ) && ! isCommand ( nextArg ) ) { arg = arg + "=" + nextArg ; i ++ ; } } // Sometimes , commas are still escaped as \ , at this point , fix it :
arg = arg . replace ( "\\," , "," ) ; fixedArgs . add ( arg ) ; } return fixedArgs . toArray ( new String [ fixedArgs . size ( ) ] ) ;


signature:
public class Main { /** * After parsing , checks if the given combination of main command and can be executed .
 * @ return an empty List if successful , or a list of error messages */
protected List < String > checkSetup ( ) { } }

implementation: List < String > messages = new ArrayList < > ( ) ; if ( command == null ) { messages . add ( coreBundle . getString ( "command.not.passed" ) ) ; } else if ( ! isCommand ( command ) ) { messages . add ( String . format ( coreBundle . getString ( "command.unknown" ) , command ) ) ; } else { if ( StringUtil . trimToNull ( url ) == null ) { messages . add ( String . format ( coreBundle . getString ( "option.required" ) , "--" + OPTIONS . URL ) ) ; } if ( isChangeLogRequired ( command ) && ( StringUtil . trimToNull ( changeLogFile ) == null ) ) { messages . add ( String . format ( coreBundle . getString ( "option.required" ) , "--" + OPTIONS . CHANGELOG_FILE ) ) ; } if ( isNoArgCommand ( command ) && ! commandParams . isEmpty ( ) ) { messages . add ( coreBundle . getString ( ERRORMSG_UNEXPECTED_PARAMETERS ) + commandParams ) ; } else { validateCommandParameters ( messages ) ; } } return messages ;


signature:
public class Main { /** * Checks for unexpected ( unknown ) command line parameters and , if any problems are found ,
 * returns the list of issues in String form .
 * @ param messages an array of Strings to which messages for issues found will be added */
private void checkForUnexpectedCommandParameter ( List < String > messages ) { } }

implementation: if ( COMMANDS . UPDATE_COUNT . equalsIgnoreCase ( command ) || COMMANDS . UPDATE_COUNT_SQL . equalsIgnoreCase ( command ) || COMMANDS . UPDATE_TO_TAG . equalsIgnoreCase ( command ) || COMMANDS . UPDATE_TO_TAG_SQL . equalsIgnoreCase ( command ) || COMMANDS . CALCULATE_CHECKSUM . equalsIgnoreCase ( command ) || COMMANDS . DB_DOC . equalsIgnoreCase ( command ) || COMMANDS . TAG . equalsIgnoreCase ( command ) || COMMANDS . TAG_EXISTS . equalsIgnoreCase ( command ) ) { if ( ( ! commandParams . isEmpty ( ) ) && commandParams . iterator ( ) . next ( ) . startsWith ( "-" ) ) { messages . add ( coreBundle . getString ( ERRORMSG_UNEXPECTED_PARAMETERS ) + commandParams ) ; } } else if ( COMMANDS . STATUS . equalsIgnoreCase ( command ) || COMMANDS . UNEXPECTED_CHANGESETS . equalsIgnoreCase ( command ) ) { if ( ( ! commandParams . isEmpty ( ) ) && ! commandParams . iterator ( ) . next ( ) . equalsIgnoreCase ( "--" + OPTIONS . VERBOSE ) ) { messages . add ( coreBundle . getString ( ERRORMSG_UNEXPECTED_PARAMETERS ) + commandParams ) ; } } else if ( COMMANDS . DIFF . equalsIgnoreCase ( command ) || COMMANDS . DIFF_CHANGELOG . equalsIgnoreCase ( command ) ) { if ( ( ! commandParams . isEmpty ( ) ) ) { for ( String cmdParm : commandParams ) { if ( ! cmdParm . startsWith ( "--" + OPTIONS . REFERENCE_USERNAME ) && ! cmdParm . startsWith ( "--" + OPTIONS . REFERENCE_PASSWORD ) && ! cmdParm . startsWith ( "--" + OPTIONS . REFERENCE_DRIVER ) && ! cmdParm . startsWith ( "--" + OPTIONS . REFERENCE_DEFAULT_CATALOG_NAME ) && ! cmdParm . startsWith ( "--" + OPTIONS . REFERENCE_DEFAULT_SCHEMA_NAME ) && ! cmdParm . startsWith ( "--" + OPTIONS . INCLUDE_SCHEMA ) && ! cmdParm . startsWith ( "--" + OPTIONS . INCLUDE_CATALOG ) && ! cmdParm . startsWith ( "--" + OPTIONS . INCLUDE_TABLESPACE ) && ! cmdParm . startsWith ( "--" + OPTIONS . SCHEMAS ) && ! cmdParm . startsWith ( "--" + OPTIONS . OUTPUT_SCHEMAS_AS ) && ! cmdParm . startsWith ( "--" + OPTIONS . REFERENCE_SCHEMAS ) && ! cmdParm . startsWith ( "--" + OPTIONS . REFERENCE_URL ) && ! cmdParm . startsWith ( "--" + OPTIONS . EXCLUDE_OBJECTS ) && ! cmdParm . startsWith ( "--" + OPTIONS . INCLUDE_OBJECTS ) && ! cmdParm . startsWith ( "--" + OPTIONS . DIFF_TYPES ) ) { messages . add ( String . format ( coreBundle . getString ( "unexpected.command.parameter" ) , cmdParm ) ) ; } } } } else if ( ( COMMANDS . SNAPSHOT . equalsIgnoreCase ( command ) || COMMANDS . GENERATE_CHANGELOG . equalsIgnoreCase ( command ) ) && ( ! commandParams . isEmpty ( ) ) ) { for ( String cmdParm : commandParams ) { if ( ! cmdParm . startsWith ( "--" + OPTIONS . INCLUDE_SCHEMA ) && ! cmdParm . startsWith ( "--" + OPTIONS . INCLUDE_CATALOG ) && ! cmdParm . startsWith ( "--" + OPTIONS . INCLUDE_TABLESPACE ) && ! cmdParm . startsWith ( "--" + OPTIONS . SCHEMAS ) ) { messages . add ( String . format ( coreBundle . getString ( "unexpected.command.parameter" ) , cmdParm ) ) ; } } }


signature:
public class Main { /** * Checks the command line for correctness and reports on unexpected , missing and / or malformed parameters .
 * @ param messages an array of Strings to which messages for issues found will be added */
private void validateCommandParameters ( final List < String > messages ) { } }

implementation: checkForUnexpectedCommandParameter ( messages ) ; checkForMissingCommandParameters ( messages ) ; checkForMalformedCommandParameters ( messages ) ;


signature:
public class Main { /** * Checks for missing command line parameters and , if any problems are found ,
 * returns the list of issues in String form .
 * @ param messages an array of Strings to which messages for issues found will be added */
private void checkForMissingCommandParameters ( final List < String > messages ) { } }

implementation: if ( ( commandParams . isEmpty ( ) || commandParams . iterator ( ) . next ( ) . startsWith ( "-" ) ) && ( COMMANDS . CALCULATE_CHECKSUM . equalsIgnoreCase ( command ) ) ) { messages . add ( coreBundle . getString ( "changeset.identifier.missing" ) ) ; }


signature:
public class Main { /** * Checks for incorrectly written command line parameters and , if any problems are found ,
 * returns the list of issues in String form .
 * @ param messages an array of Strings to which messages for issues found will be added */
private void checkForMalformedCommandParameters ( final List < String > messages ) { } }

implementation: if ( commandParams . isEmpty ( ) ) { return ; } final int CHANGESET_MINIMUM_IDENTIFIER_PARTS = 3 ; if ( COMMANDS . CALCULATE_CHECKSUM . equalsIgnoreCase ( command ) ) { for ( final String param : commandParams ) { if ( ( param != null ) && ! param . startsWith ( "-" ) ) { final String [ ] parts = param . split ( "::" ) ; if ( parts . length < CHANGESET_MINIMUM_IDENTIFIER_PARTS ) { messages . add ( coreBundle . getString ( "changeset.identifier.must.have.form.filepath.id.author" ) ) ; break ; } } } } else if ( COMMANDS . DIFF_CHANGELOG . equalsIgnoreCase ( command ) && ( diffTypes != null ) && diffTypes . toLowerCase ( ) . contains ( "data" ) ) { messages . add ( String . format ( coreBundle . getString ( "including.data.diffchangelog.has.no.effect" ) , OPTIONS . DIFF_TYPES , COMMANDS . GENERATE_CHANGELOG ) ) ; }


signature:
public class Main { /** * Reads various execution parameters from an InputStream and sets our internal state according to the values
 * found .
 * @ param propertiesInputStream an InputStream from a Java properties file
 * @ throws IOException if there is a problem reading the InputStream
 * @ throws CommandLineParsingException if an invalid property is encountered */
protected void parsePropertiesFile ( InputStream propertiesInputStream ) throws IOException , CommandLineParsingException { } }

implementation: Properties props = new Properties ( ) ; props . load ( propertiesInputStream ) ; if ( props . containsKey ( "strict" ) ) { strict = Boolean . valueOf ( props . getProperty ( "strict" ) ) ; } for ( Map . Entry entry : props . entrySet ( ) ) { try { if ( "promptOnNonLocalDatabase" . equals ( entry . getKey ( ) ) ) { continue ; } if ( ( ( String ) entry . getKey ( ) ) . startsWith ( "parameter." ) ) { changeLogParameters . put ( ( ( String ) entry . getKey ( ) ) . replaceFirst ( "^parameter." , "" ) , entry . getValue ( ) ) ; } else { Field field = getClass ( ) . getDeclaredField ( ( String ) entry . getKey ( ) ) ; Object currentValue = field . get ( this ) ; if ( currentValue == null ) { String value = entry . getValue ( ) . toString ( ) . trim ( ) ; if ( field . getType ( ) . equals ( Boolean . class ) ) { field . set ( this , Boolean . valueOf ( value ) ) ; } else { field . set ( this , value ) ; } } } } catch ( NoSuchFieldException ignored ) { if ( strict ) { throw new CommandLineParsingException ( String . format ( coreBundle . getString ( "parameter.unknown" ) , entry . getKey ( ) ) ) ; } else { Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . warning ( LogType . LOG , String . format ( coreBundle . getString ( "parameter.ignored" ) , entry . getKey ( ) ) ) ; } } catch ( IllegalAccessException e ) { throw new UnexpectedLiquibaseException ( String . format ( coreBundle . getString ( "parameter.unknown" ) , entry . getKey ( ) ) ) ; } }


signature:
public class Main { /** * If any errors have been found , print the list of errors first , then print the command line help text .
 * @ param errorMessages List of error messages
 * @ param stream the output stream to write the text to */
protected void printHelp ( List < String > errorMessages , PrintStream stream ) { } }

implementation: stream . println ( coreBundle . getString ( "errors" ) ) ; for ( String message : errorMessages ) { stream . println ( "  " + message ) ; } stream . println ( ) ;


signature:
public class Main { /** * Print instructions on how to use this program from the command line .
 * @ param stream the output stream to write the help text to */
protected void printHelp ( PrintStream stream ) { } }

implementation: String helpText = commandLineHelpBundle . getString ( "commandline-helptext" ) ; stream . println ( helpText ) ;


signature:
public class Main { /** * Parses the command line options . If an invalid argument is given , a CommandLineParsingException is thrown .
 * @ param paramArgs the arguments to parse
 * @ throws CommandLineParsingException thrown if an invalid argument is passed */
protected void parseOptions ( String [ ] paramArgs ) throws CommandLineParsingException { } }

implementation:
String [ ] args = fixupArgs ( paramArgs ) ; boolean seenCommand = false ; for ( String arg : args ) { if ( isCommand ( arg ) ) { this . command = arg ; if ( this . command . equalsIgnoreCase ( COMMANDS . MIGRATE ) ) { this . command = COMMANDS . UPDATE ; } else if ( this . command . equalsIgnoreCase ( COMMANDS . MIGRATE_SQL ) ) { this . command = COMMANDS . UPDATE_SQL ; } seenCommand = true ; } else if ( seenCommand ) { // ChangeLog parameter :
if ( arg . startsWith ( "-D" ) ) { String [ ] splitArg = splitArg ( arg ) ; String attributeName = splitArg [ 0 ] . replaceFirst ( "^-D" , "" ) ; String value = splitArg [ 1 ] ; changeLogParameters . put ( attributeName , value ) ; } else { commandParams . add ( arg ) ; if ( arg . startsWith ( "--" ) ) { parseOptionArgument ( arg ) ; } } } else if ( arg . startsWith ( "--" ) ) { parseOptionArgument ( arg ) ; } else { throw new CommandLineParsingException ( String . format ( coreBundle . getString ( "unexpected.value" ) , arg ) ) ; } } // Now apply default values from the default property files . We waited with this until this point
// since command line parameters might have changed the location where we will look for them .
parseDefaultPropertyFiles ( ) ;


signature:
public class Main { /** * Parses an option ( " - - someOption " ) from the command line
 * @ param arg the option to parse ( including the " - - " )
 * @ throws CommandLineParsingException if a problem occurs */
private void parseOptionArgument ( String arg ) throws CommandLineParsingException { } }

implementation:
final String PROMPT_FOR_VALUE = "PROMPT" ; if ( arg . toLowerCase ( ) . startsWith ( "--" + OPTIONS . VERBOSE ) ) return ; String [ ] splitArg = splitArg ( arg ) ; String attributeName = splitArg [ 0 ] ; String value = splitArg [ 1 ] ; if ( PROMPT_FOR_VALUE . equalsIgnoreCase ( StringUtil . trimToEmpty ( value ) ) ) { Console c = System . console ( ) ; if ( c == null ) { throw new CommandLineParsingException ( String . format ( MessageFormat . format ( coreBundle . getString ( "cannot.prompt.for.the.value.no.console" ) , attributeName ) ) ) ; } // Prompt for value
if ( attributeName . toLowerCase ( ) . contains ( "password" ) ) { value = new String ( c . readPassword ( attributeName + ": " ) ) ; } else { value = c . readLine ( attributeName + ": " ) ; } } try { Field field = getClass ( ) . getDeclaredField ( attributeName ) ; if ( field . getType ( ) . equals ( Boolean . class ) ) { field . set ( this , Boolean . valueOf ( value ) ) ; } else { field . set ( this , value ) ; } } catch ( IllegalAccessException | NoSuchFieldException e ) { throw new CommandLineParsingException ( String . format ( coreBundle . getString ( "option.unknown" ) , attributeName ) ) ; }


signature:
public class Main { /** * Do the actual database migration , i . e . apply the ChangeSets .
 * @ throws Exception */
protected void doMigration ( ) throws Exception { } }

implementation:
if ( COMMANDS . HELP . equalsIgnoreCase ( command ) ) { printHelp ( System . err ) ; return ; } try { // if ( null ! = logFile ) {
// Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . setLogLevel ( logLevel , logFile ) ;
// } else {
// Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . setLogLevel ( logLevel ) ;
} catch ( IllegalArgumentException e ) { throw new CommandLineParsingException ( e . getMessage ( ) , e ) ; } FileSystemResourceAccessor fsOpener = new FileSystemResourceAccessor ( ) ; CommandLineResourceAccessor clOpener = new CommandLineResourceAccessor ( classLoader ) ; CompositeResourceAccessor fileOpener = new CompositeResourceAccessor ( fsOpener , clOpener ) ; Database database = CommandLineUtils . createDatabaseObject ( fileOpener , this . url , this . username , this . password , this . driver , this . defaultCatalogName , this . defaultSchemaName , Boolean . parseBoolean ( outputDefaultCatalog ) , Boolean . parseBoolean ( outputDefaultSchema ) , this . databaseClass , this . driverPropertiesFile , this . propertyProviderClass , this . liquibaseCatalogName , this . liquibaseSchemaName , this . databaseChangeLogTableName , this . databaseChangeLogLockTableName ) ; database . setLiquibaseTablespaceName ( this . databaseChangeLogTablespaceName ) ; try { if ( ( excludeObjects != null ) && ( includeObjects != null ) ) { throw new UnexpectedLiquibaseException ( String . format ( coreBundle . getString ( "cannot.specify.both" ) , OPTIONS . EXCLUDE_OBJECTS , OPTIONS . INCLUDE_OBJECTS ) ) ; } ObjectChangeFilter objectChangeFilter = null ; CompareControl . ComputedSchemas computedSchemas = CompareControl . computeSchemas ( schemas , referenceSchemas , outputSchemasAs , defaultCatalogName , defaultSchemaName , referenceDefaultCatalogName , referenceDefaultSchemaName , database ) ; CompareControl . SchemaComparison [ ] finalSchemaComparisons = computedSchemas . finalSchemaComparisons ; DiffOutputControl diffOutputControl = new DiffOutputControl ( includeCatalog , includeSchema , includeTablespace , finalSchemaComparisons ) ; if ( excludeObjects != null ) { objectChangeFilter = new StandardObjectChangeFilter ( StandardObjectChangeFilter . FilterType . EXCLUDE , excludeObjects ) ; diffOutputControl . setObjectChangeFilter ( objectChangeFilter ) ; } if ( includeObjects != null ) { objectChangeFilter = new StandardObjectChangeFilter ( StandardObjectChangeFilter . FilterType . INCLUDE , includeObjects ) ; diffOutputControl . setObjectChangeFilter ( objectChangeFilter ) ; } for ( CompareControl . SchemaComparison schema : finalSchemaComparisons ) { diffOutputControl . addIncludedSchema ( schema . getReferenceSchema ( ) ) ; diffOutputControl . addIncludedSchema ( schema . getComparisonSchema ( ) ) ; } if ( COMMANDS . DIFF . equalsIgnoreCase ( command ) ) { CommandLineUtils . doDiff ( createReferenceDatabaseFromCommandParams ( commandParams , fileOpener ) , database , StringUtil . trimToNull ( diffTypes ) , finalSchemaComparisons ) ; return ; } else if ( COMMANDS . DIFF_CHANGELOG . equalsIgnoreCase ( command ) ) { CommandLineUtils . doDiffToChangeLog ( changeLogFile , createReferenceDatabaseFromCommandParams ( commandParams , fileOpener ) , database , diffOutputControl , objectChangeFilter , StringUtil . trimToNull ( diffTypes ) , finalSchemaComparisons ) ; return ; } else if ( COMMANDS . GENERATE_CHANGELOG . equalsIgnoreCase ( command ) ) { String currentChangeLogFile = this . changeLogFile ; if ( currentChangeLogFile == null ) { // will output to stdout :
currentChangeLogFile = "" ; } File file = new File ( currentChangeLogFile ) ; if ( file . exists ( ) && ( ! Boolean . parseBoolean ( overwriteOutputFile ) ) ) { throw new LiquibaseException ( String . format ( coreBundle . getString ( "changelogfile.already.exists" ) , currentChangeLogFile ) ) ; } else { try { if ( ! file . delete ( ) ) { // Nothing needs to be done
} } catch ( SecurityException e ) { throw new LiquibaseException ( String . format ( coreBundle . getString ( "attempt.to.delete.the.file.failed.cannot.continue" ) , currentChangeLogFile ) , e ) ; } } CatalogAndSchema [ ] finalTargetSchemas = computedSchemas . finalTargetSchemas ; CommandLineUtils . doGenerateChangeLog ( currentChangeLogFile , database , finalTargetSchemas , StringUtil . trimToNull ( diffTypes ) , StringUtil . trimToNull ( changeSetAuthor ) , StringUtil . trimToNull ( changeSetContext ) , StringUtil . trimToNull ( dataOutputDirectory ) , diffOutputControl ) ; return ; } else if ( COMMANDS . SNAPSHOT . equalsIgnoreCase ( command ) ) { SnapshotCommand snapshotCommand = ( SnapshotCommand ) CommandFactory . getInstance ( ) . getCommand ( COMMANDS . SNAPSHOT ) ; snapshotCommand . setDatabase ( database ) ; snapshotCommand . setSchemas ( getCommandParam ( OPTIONS . SCHEMAS , database . getDefaultSchema ( ) . getSchemaName ( ) ) ) ; snapshotCommand . setSerializerFormat ( getCommandParam ( "snapshotFormat" , null ) ) ; Writer outputWriter = getOutputWriter ( ) ; String result = snapshotCommand . execute ( ) . print ( ) ; outputWriter . write ( result ) ; outputWriter . flush ( ) ; outputWriter . close ( ) ; return ; } else if ( COMMANDS . EXECUTE_SQL . equalsIgnoreCase ( command ) ) { ExecuteSqlCommand executeSqlCommand = ( ExecuteSqlCommand ) CommandFactory . getInstance ( ) . getCommand ( COMMANDS . EXECUTE_SQL ) ; executeSqlCommand . setDatabase ( database ) ; executeSqlCommand . setSql ( getCommandParam ( "sql" , null ) ) ; executeSqlCommand . setSqlFile ( getCommandParam ( "sqlFile" , null ) ) ; executeSqlCommand . setDelimiter ( getCommandParam ( "delimiter" , ";" ) ) ; Writer outputWriter = getOutputWriter ( ) ; outputWriter . write ( executeSqlCommand . execute ( ) . print ( ) ) ; outputWriter . flush ( ) ; outputWriter . close ( ) ; return ; } else if ( COMMANDS . SNAPSHOT_REFERENCE . equalsIgnoreCase ( command ) ) { SnapshotCommand snapshotCommand = ( SnapshotCommand ) CommandFactory . getInstance ( ) . getCommand ( COMMANDS . SNAPSHOT ) ; Database referenceDatabase = createReferenceDatabaseFromCommandParams ( commandParams , fileOpener ) ; snapshotCommand . setDatabase ( referenceDatabase ) ; snapshotCommand . setSchemas ( getCommandParam ( OPTIONS . SCHEMAS , referenceDatabase . getDefaultSchema ( ) . getSchemaName ( ) ) ) ; Writer outputWriter = getOutputWriter ( ) ; outputWriter . write ( snapshotCommand . execute ( ) . print ( ) ) ; outputWriter . flush ( ) ; outputWriter . close ( ) ; return ; } Liquibase liquibase = new Liquibase ( changeLogFile , fileOpener , database ) ; ChangeExecListener listener = ChangeExecListenerUtils . getChangeExecListener ( liquibase . getDatabase ( ) , liquibase . getResourceAccessor ( ) , changeExecListenerClass , changeExecListenerPropertiesFile ) ; liquibase . setChangeExecListener ( listener ) ; database . setCurrentDateTimeFunction ( currentDateTimeFunction ) ; for ( Map . Entry < String , Object > entry : changeLogParameters . entrySet ( ) ) { liquibase . setChangeLogParameter ( entry . getKey ( ) , entry . getValue ( ) ) ; } if ( COMMANDS . LIST_LOCKS . equalsIgnoreCase ( command ) ) { liquibase . reportLocks ( System . err ) ; return ; } else if ( COMMANDS . RELEASE_LOCKS . equalsIgnoreCase ( command ) ) { LockService lockService = LockServiceFactory . getInstance ( ) . getLockService ( database ) ; lockService . forceReleaseLock ( ) ; Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . info ( LogType . USER_MESSAGE , String . format ( coreBundle . getString ( "successfully.released.database.change.log.locks" ) , liquibase . getDatabase ( ) . getConnection ( ) . getConnectionUserName ( ) + "@" + liquibase . getDatabase ( ) . getConnection ( ) . getURL ( ) ) ) ; return ; } else if ( COMMANDS . TAG . equalsIgnoreCase ( command ) ) { liquibase . tag ( getCommandArgument ( ) ) ; Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . info ( LogType . LOG , String . format ( coreBundle . getString ( "successfully.tagged" ) , liquibase . getDatabase ( ) . getConnection ( ) . getConnectionUserName ( ) + "@" + liquibase . getDatabase ( ) . getConnection ( ) . getURL ( ) ) ) ; return ; } else if ( COMMANDS . TAG_EXISTS . equalsIgnoreCase ( command ) ) { String tag = commandParams . iterator ( ) . next ( ) ; boolean exists = liquibase . tagExists ( tag ) ; if ( exists ) { Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . info ( LogType . LOG , String . format ( coreBundle . getString ( "tag.exists" ) , tag , liquibase . getDatabase ( ) . getConnection ( ) . getConnectionUserName ( ) + "@" + liquibase . getDatabase ( ) . getConnection ( ) . getURL ( ) ) ) ; } else { Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . info ( LogType . LOG , String . format ( coreBundle . getString ( "tag.does.not.exist" ) , tag , liquibase . getDatabase ( ) . getConnection ( ) . getConnectionUserName ( ) + "@" + liquibase . getDatabase ( ) . getConnection ( ) . getURL ( ) ) ) ; } return ; } else if ( COMMANDS . DROP_ALL . equals ( command ) ) { DropAllCommand dropAllCommand = ( DropAllCommand ) CommandFactory . getInstance ( ) . getCommand ( COMMANDS . DROP_ALL ) ; dropAllCommand . setDatabase ( liquibase . getDatabase ( ) ) ; dropAllCommand . setSchemas ( getCommandParam ( OPTIONS . SCHEMAS , database . getDefaultSchema ( ) . getSchemaName ( ) ) ) ; Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . info ( LogType . USER_MESSAGE , dropAllCommand . execute ( ) . print ( ) ) ; return ; } else if ( COMMANDS . STATUS . equalsIgnoreCase ( command ) ) { boolean runVerbose = false ; if ( commandParams . contains ( "--" + OPTIONS . VERBOSE ) ) { runVerbose = true ; } liquibase . reportStatus ( runVerbose , new Contexts ( contexts ) , new LabelExpression ( labels ) , getOutputWriter ( ) ) ; return ; } else if ( COMMANDS . UNEXPECTED_CHANGESETS . equalsIgnoreCase ( command ) ) { boolean runVerbose = false ; if ( commandParams . contains ( "--" + OPTIONS . VERBOSE ) ) { runVerbose = true ; } liquibase . reportUnexpectedChangeSets ( runVerbose , contexts , getOutputWriter ( ) ) ; return ; } else if ( COMMANDS . VALIDATE . equalsIgnoreCase ( command ) ) { try { liquibase . validate ( ) ; } catch ( ValidationFailedException e ) { e . printDescriptiveError ( System . err ) ; return ; } Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . info ( LogType . USER_MESSAGE , coreBundle . getString ( "no.validation.errors.found" ) ) ; return ; } else if ( COMMANDS . CLEAR_CHECKSUMS . equalsIgnoreCase ( command ) ) { liquibase . clearCheckSums ( ) ; return ; } else if ( COMMANDS . CALCULATE_CHECKSUM . equalsIgnoreCase ( command ) ) { CheckSum checkSum = null ; checkSum = liquibase . calculateCheckSum ( commandParams . iterator ( ) . next ( ) ) ; Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . info ( LogType . USER_MESSAGE , checkSum . toString ( ) ) ; return ; } else if ( COMMANDS . DB_DOC . equalsIgnoreCase ( command ) ) { if ( commandParams . isEmpty ( ) ) { throw new CommandLineParsingException ( coreBundle . getString ( "dbdoc.requires.output.directory" ) ) ; } if ( changeLogFile == null ) { throw new CommandLineParsingException ( coreBundle . getString ( "dbdoc.requires.changelog.parameter" ) ) ; } liquibase . generateDocumentation ( commandParams . iterator ( ) . next ( ) , contexts ) ; return ; } try { if ( COMMANDS . UPDATE . equalsIgnoreCase ( command ) ) { liquibase . update ( new Contexts ( contexts ) , new LabelExpression ( labels ) ) ; } else if ( COMMANDS . CHANGELOG_SYNC . equalsIgnoreCase ( command ) ) { liquibase . changeLogSync ( new Contexts ( contexts ) , new LabelExpression ( labels ) ) ; } else if ( COMMANDS . CHANGELOG_SYNC_SQL . equalsIgnoreCase ( command ) ) { liquibase . changeLogSync ( new Contexts ( contexts ) , new LabelExpression ( labels ) , getOutputWriter ( ) ) ; } else if ( COMMANDS . MARK_NEXT_CHANGESET_RAN . equalsIgnoreCase ( command ) ) { liquibase . markNextChangeSetRan ( new Contexts ( contexts ) , new LabelExpression ( labels ) ) ; } else if ( COMMANDS . MARK_NEXT_CHANGESET_RAN_SQL . equalsIgnoreCase ( command ) ) { liquibase . markNextChangeSetRan ( new Contexts ( contexts ) , new LabelExpression ( labels ) , getOutputWriter ( ) ) ; } else if ( COMMANDS . UPDATE_COUNT . equalsIgnoreCase ( command ) ) { liquibase . update ( Integer . parseInt ( commandParams . iterator ( ) . next ( ) ) , new Contexts ( contexts ) , new LabelExpression ( labels ) ) ; } else if ( COMMANDS . UPDATE_COUNT_SQL . equalsIgnoreCase ( command ) ) { liquibase . update ( Integer . parseInt ( commandParams . iterator ( ) . next ( ) ) , new Contexts ( contexts ) , new LabelExpression ( labels ) , getOutputWriter ( ) ) ; } else if ( COMMANDS . UPDATE_TO_TAG . equalsIgnoreCase ( command ) ) { if ( ( commandParams == null ) || commandParams . isEmpty ( ) ) { throw new CommandLineParsingException ( String . format ( coreBundle . getString ( "command.requires.tag" ) , COMMANDS . UPDATE_TO_TAG ) ) ; } liquibase . update ( commandParams . iterator ( ) . next ( ) , new Contexts ( contexts ) , new LabelExpression ( labels ) ) ; } else if ( COMMANDS . UPDATE_TO_TAG_SQL . equalsIgnoreCase ( command ) ) { if ( ( commandParams == null ) || commandParams . isEmpty ( ) ) { throw new CommandLineParsingException ( String . format ( coreBundle . getString ( "command.requires.tag" ) , COMMANDS . UPDATE_TO_TAG_SQL ) ) ; } liquibase . update ( commandParams . iterator ( ) . next ( ) , new Contexts ( contexts ) , new LabelExpression ( labels ) , getOutputWriter ( ) ) ; } else if ( COMMANDS . UPDATE_SQL . equalsIgnoreCase ( command ) ) { liquibase . update ( new Contexts ( contexts ) , new LabelExpression ( labels ) , getOutputWriter ( ) ) ; } else if ( COMMANDS . ROLLBACK . equalsIgnoreCase ( command ) ) { if ( getCommandArgument ( ) == null ) { throw new CommandLineParsingException ( String . format ( coreBundle . getString ( "command.requires.tag" ) , COMMANDS . ROLLBACK ) ) ; } liquibase . rollback ( getCommandArgument ( ) , getCommandParam ( COMMANDS . ROLLBACK_SCRIPT , null ) , new Contexts ( contexts ) , new LabelExpression ( labels ) ) ; } else if ( COMMANDS . ROLLBACK_TO_DATE . equalsIgnoreCase ( command ) ) { if ( getCommandArgument ( ) == null ) { throw new CommandLineParsingException ( String . format ( coreBundle . getString ( "command.requires.timestamp" ) , COMMANDS . ROLLBACK_TO_DATE ) ) ; } liquibase . rollback ( new ISODateFormat ( ) . parse ( getCommandArgument ( ) ) , getCommandParam ( COMMANDS . ROLLBACK_SCRIPT , null ) , new Contexts ( contexts ) , new LabelExpression ( labels ) ) ; } else if ( COMMANDS . ROLLBACK_COUNT . equalsIgnoreCase ( command ) ) { liquibase . rollback ( Integer . parseInt ( getCommandArgument ( ) ) , getCommandParam ( COMMANDS . ROLLBACK_SCRIPT , null ) , new Contexts ( contexts ) , new LabelExpression ( labels ) ) ; } else if ( COMMANDS . ROLLBACK_SQL . equalsIgnoreCase ( command ) ) { if ( getCommandArgument ( ) == null ) { throw new CommandLineParsingException ( String . format ( coreBundle . getString ( "command.requires.tag" ) , COMMANDS . ROLLBACK_SQL ) ) ; } liquibase . rollback ( getCommandArgument ( ) , getCommandParam ( COMMANDS . ROLLBACK_SCRIPT , null ) , new Contexts ( contexts ) , new LabelExpression ( labels ) , getOutputWriter ( ) ) ; } else if ( COMMANDS . ROLLBACK_TO_DATE_SQL . equalsIgnoreCase ( command ) ) { if ( getCommandArgument ( ) == null ) { throw new CommandLineParsingException ( String . format ( coreBundle . getString ( "command.requires.timestamp" ) , COMMANDS . ROLLBACK_TO_DATE_SQL ) ) ; } liquibase . rollback ( new ISODateFormat ( ) . parse ( getCommandArgument ( ) ) , getCommandParam ( COMMANDS . ROLLBACK_SCRIPT , null ) , new Contexts ( contexts ) , new LabelExpression ( labels ) , getOutputWriter ( ) ) ; } else if ( COMMANDS . ROLLBACK_COUNT_SQL . equalsIgnoreCase ( command ) ) { if ( getCommandArgument ( ) == null ) { throw new CommandLineParsingException ( String . format ( coreBundle . getString ( "command.requires.count" ) , COMMANDS . ROLLBACK_COUNT_SQL ) ) ; } liquibase . rollback ( Integer . parseInt ( getCommandArgument ( ) ) , getCommandParam ( COMMANDS . ROLLBACK_SCRIPT , null ) , new Contexts ( contexts ) , new LabelExpression ( labels ) , getOutputWriter ( ) ) ; } else if ( COMMANDS . FUTURE_ROLLBACK_SQL . equalsIgnoreCase ( command ) ) { liquibase . futureRollbackSQL ( new Contexts ( contexts ) , new LabelExpression ( labels ) , getOutputWriter ( ) ) ; } else if ( COMMANDS . FUTURE_ROLLBACK_COUNT_SQL . equalsIgnoreCase ( command ) ) { if ( getCommandArgument ( ) == null ) { throw new CommandLineParsingException ( String . format ( coreBundle . getString ( "command.requires.count" ) , COMMANDS . FUTURE_ROLLBACK_COUNT_SQL ) ) ; } liquibase . futureRollbackSQL ( Integer . parseInt ( getCommandArgument ( ) ) , new Contexts ( contexts ) , new LabelExpression ( labels ) , getOutputWriter ( ) ) ; } else if ( COMMANDS . FUTURE_ROLLBACK_FROM_TAG_SQL . equalsIgnoreCase ( command ) ) { if ( getCommandArgument ( ) == null ) { throw new CommandLineParsingException ( String . format ( coreBundle . getString ( "command.requires.tag" ) , COMMANDS . FUTURE_ROLLBACK_FROM_TAG_SQL ) ) ; } liquibase . futureRollbackSQL ( getCommandArgument ( ) , new Contexts ( contexts ) , new LabelExpression ( labels ) , getOutputWriter ( ) ) ; } else if ( COMMANDS . UPDATE_TESTING_ROLLBACK . equalsIgnoreCase ( command ) ) { liquibase . updateTestingRollback ( new Contexts ( contexts ) , new LabelExpression ( labels ) ) ; } else { throw new CommandLineParsingException ( String . format ( coreBundle . getString ( "command.unknown" ) , command ) ) ; } } catch ( ParseException ignored ) { throw new CommandLineParsingException ( coreBundle . getString ( "timeformat.invalid" ) ) ; } } finally { try { database . rollback ( ) ; database . close ( ) ; } catch ( DatabaseException e ) { Scope . getCurrentScope ( ) . getLog ( getClass ( ) ) . warning ( LogType . LOG , coreBundle . getString ( "problem.closing.connection" ) , e ) ; } }


signature:
public class Main { /** * Returns the value for a command line parameter of the form parameterName = value , or defaultValue if that
 * parameter has not been specified by the user .
 * @ param paramName name of the parameter
 * @ param defaultValue return value if parameter is not given
 * @ return the user - specified value for paramName , or defaultValue
 * @ throws CommandLineParsingException if a parameter on the command line is un - parsable */
private String getCommandParam ( String paramName , String defaultValue ) throws CommandLineParsingException { } }

implementation: for ( String param : commandParams ) { if ( ! param . contains ( "=" ) ) { continue ; } String [ ] splitArg = splitArg ( param ) ; String attributeName = splitArg [ 0 ] ; String value = splitArg [ 1 ] ; if ( attributeName . equalsIgnoreCase ( paramName ) ) { return value ; } } return defaultValue ;


signature:
public class NumberUtils { /** * Parse the given text into a number instance of the given target class ,
 * using the corresponding default < code > decode < / code > methods . Trims the
 * input < code > String < / code > before attempting to parse the number . Supports
 * numbers in hex format ( with leading 0x ) and in octal format ( with leading 0 ) .
 * @ param text the text to convert
 * @ param targetClass the target class to parse into
 * @ return the parsed number
 * @ throws IllegalArgumentException if the target class is not supported
 * ( i . e . not a standard Number subclass as included in the JDK )
 * @ see java . lang . Byte # decode
 * @ see java . lang . Short # decode
 * @ see java . lang . Integer # decode
 * @ see java . lang . Long # decode
 * @ see # decodeBigInteger ( String )
 * @ see java . lang . Float # valueOf
 * @ see java . lang . Double # valueOf
 * @ see java . math . BigDecimal # BigDecimal ( String ) */
public static Number parseNumber ( String text , Class targetClass ) { } }

implementation: String trimmed = text . trim ( ) ; if ( targetClass . equals ( Byte . class ) ) { return Byte . decode ( trimmed ) ; } else if ( targetClass . equals ( Short . class ) ) { return Short . decode ( trimmed ) ; } else if ( targetClass . equals ( Integer . class ) ) { return Integer . decode ( trimmed ) ; } else if ( targetClass . equals ( Long . class ) ) { return Long . decode ( trimmed ) ; } else if ( targetClass . equals ( BigInteger . class ) ) { return decodeBigInteger ( trimmed ) ; } else if ( targetClass . equals ( Float . class ) ) { return Float . valueOf ( trimmed ) ; } else if ( targetClass . equals ( Double . class ) ) { return Double . valueOf ( trimmed ) ; } else if ( targetClass . equals ( BigDecimal . class ) || targetClass . equals ( Number . class ) ) { return new BigDecimal ( trimmed ) ; } else { throw new IllegalArgumentException ( "Cannot convert String [" + text + "] to target class [" + targetClass . getName ( ) + "]" ) ; }


signature:
public class NumberUtils { /** * Parse the given text into a number instance of the given target class ,
 * using the given NumberFormat . Trims the input < code > String < / code >
 * before attempting to parse the number .
 * @ param text the text to convert
 * @ param targetClass the target class to parse into
 * @ param numberFormat the NumberFormat to use for parsing ( if < code > null < / code > ,
 * this method falls back to < code > parseNumber ( String , Class ) < / code > )
 * @ return the parsed number
 * @ throws IllegalArgumentException if the target class is not supported
 * ( i . e . not a standard Number subclass as included in the JDK )
 * @ see java . text . NumberFormat # parse
 * @ see # convertNumberToTargetClass
 * @ see # parseNumber ( String , Class ) */
public static Number parseNumber ( String text , Class targetClass , NumberFormat numberFormat ) { } }

implementation: if ( numberFormat != null ) { try { Number number = numberFormat . parse ( text . trim ( ) ) ; return convertNumberToTargetClass ( number , targetClass ) ; } catch ( ParseException ex ) { throw new IllegalArgumentException ( ex . getMessage ( ) ) ; } } else { return parseNumber ( text , targetClass ) ; }


signature:
public class NumberUtils { /** * Convenience method for converting a string to an Integer object
 * @ param value string value
 * @ return Null if the value is null , otherwise the converted integer */
public static Integer readInteger ( String value ) { } }

implementation: if ( value == null ) { return null ; } return Integer . valueOf ( value ) ;


signature:
public class ObjectMetaData { /** * Convenience method to return the { @ link liquibase . ObjectMetaData . Attribute } information for the given attribute .
 * Returns null if the attribute name doesn ' t exist . */
public Attribute getAttribute ( String attributeName ) { } }

implementation: for ( Attribute attribute : attributes ) { if ( attribute . name . equals ( attributeName ) ) { return attribute ; } } return null ;


signature:
public class LabelExpression { /** * Returns true if the passed runtime labels match this label expression */
public boolean matches ( Labels runtimeLabels ) { } }

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


signature:
public class CreateViewChange { /** * Calculates the checksum based on the contained SQL .
 * @ see liquibase . change . AbstractChange # generateCheckSum ( ) */
@ Override public CheckSum generateCheckSum ( ) { } }

implementation: if ( this . path == null ) { return super . generateCheckSum ( ) ; } InputStream stream = null ; try { stream = openSqlStream ( ) ; } catch ( IOException e ) { throw new UnexpectedLiquibaseException ( e ) ; } try { String selectQuery = this . selectQuery ; if ( ( stream == null ) && ( selectQuery == null ) ) { selectQuery = "" ; } String encoding = LiquibaseConfiguration . getInstance ( ) . getConfiguration ( GlobalConfiguration . class ) . getOutputEncoding ( ) ; if ( selectQuery != null ) { try { stream = new ByteArrayInputStream ( selectQuery . getBytes ( encoding ) ) ; } catch ( UnsupportedEncodingException e ) { throw new AssertionError ( encoding + " is not supported by the JVM, this should not happen according to the JavaDoc of the Charset class" ) ; } } CheckSum checkSum = CheckSum . compute ( new AbstractSQLChange . NormalizingStream ( ";" , false , false , stream ) , false ) ; return CheckSum . compute ( super . generateCheckSum ( ) . toString ( ) + ":" + checkSum . toString ( ) ) ; } finally { if ( stream != null ) { try { stream . close ( ) ; } catch ( IOException ignore ) { } } }


signature:
public class SQLiteDatabase { /** * Uses { @ link SqlGeneratorFactory } to generate { @ link Sql } for the specified visitor and db objects .
 * @ param database
 * @ param alterTableVisitor
 * @ param catalogName
 * @ param schemaName
 * @ param tableName
 * @ return */
public static Sql [ ] getAlterTableSqls ( Database database , SQLiteDatabase . AlterTableVisitor alterTableVisitor , String catalogName , String schemaName , String tableName ) { } }

implementation:
Sql [ ] generatedSqls ; try { List < SqlStatement > statements = SQLiteDatabase . getAlterTableStatements ( alterTableVisitor , database , catalogName , schemaName , tableName ) ; // convert from SqlStatement to Sql
SqlStatement [ ] sqlStatements = new SqlStatement [ statements . size ( ) ] ; sqlStatements = statements . toArray ( sqlStatements ) ; generatedSqls = SqlGeneratorFactory . getInstance ( ) . generateSql ( sqlStatements , database ) ; } catch ( DatabaseException e ) { throw new UnexpectedLiquibaseException ( e ) ; } return generatedSqls ;


signature:
public class SnapshotGeneratorFactory { /** * Checks if a specific object is present in a database
 * @ param example The DatabaseObject to check for existence
 * @ param database The DBMS in which the object might exist
 * @ return true if object existence can be confirmed , false otherweise
 * @ throws DatabaseException If a problem occurs in the DBMS - specific code
 * @ throws InvalidExampleException If the object cannot be checked properly , e . g . if the object name is ambiguous */
public boolean has ( DatabaseObject example , Database database ) throws DatabaseException , InvalidExampleException { } }

implementation:
// @ todo I have seen duplicates in types - maybe convert the List into a Set ? Need to understand it more thoroughly .
List < Class < ? extends DatabaseObject > > types = new ArrayList < > ( getContainerTypes ( example . getClass ( ) , database ) ) ; types . add ( example . getClass ( ) ) ; /* * Does the query concern the DATABASECHANGELOG / DATABASECHANGELOGLOCK table ? If so , we do a quick & dirty
 * SELECT COUNT ( * ) on that table . If that works , we count that as confirmation of existence . */
// @ todo Actually , there may be extreme cases ( distorted table statistics etc . ) where a COUNT ( * ) might not be so cheap . Maybe SELECT a dummy constant is the better way ?
if ( ( example instanceof Table ) && ( example . getName ( ) . equals ( database . getDatabaseChangeLogTableName ( ) ) || example . getName ( ) . equals ( database . getDatabaseChangeLogLockTableName ( ) ) ) ) { try { ExecutorService . getInstance ( ) . getExecutor ( database ) . queryForInt ( new RawSqlStatement ( "SELECT COUNT(*) FROM " + database . escapeObjectName ( database . getLiquibaseCatalogName ( ) , database . getLiquibaseSchemaName ( ) , example . getName ( ) , Table . class ) ) ) ; return true ; } catch ( DatabaseException e ) { if ( database instanceof PostgresDatabase ) { // throws " current transaction is aborted " unless we roll back the connection
database . rollback ( ) ; } return false ; } } /* * If the query is about another object , try to create a snapshot of the of the object ( or used the cached
 * snapshot . If that works , we count that as confirmation of existence . */
SnapshotControl snapshotControl = ( new SnapshotControl ( database , false , types . toArray ( new Class [ types . size ( ) ] ) ) ) ; snapshotControl . setWarnIfObjectNotFound ( false ) ; if ( createSnapshot ( example , database , snapshotControl ) != null ) { return true ; } CatalogAndSchema catalogAndSchema ; if ( example . getSchema ( ) == null ) { catalogAndSchema = database . getDefaultSchema ( ) ; } else { catalogAndSchema = example . getSchema ( ) . toCatalogAndSchema ( ) ; } DatabaseSnapshot snapshot = createSnapshot ( catalogAndSchema , database , new SnapshotControl ( database , false , example . getClass ( ) ) . setWarnIfObjectNotFound ( false ) ) ; for ( DatabaseObject obj : snapshot . get ( example . getClass ( ) ) ) { if ( DatabaseObjectComparatorFactory . getInstance ( ) . isSameObject ( example , obj , null , database ) ) { return true ; } } return false ;


signature:
public class SnapshotGeneratorFactory { /** * Creates a database snapshot for a given array of catalog / schema combinations .
 * @ param examples an array of CatalogAndSchema objects
 * @ param database the database to work on
 * @ param snapshotControl the options / settings for snapshot generation
 * @ return a database snapshot that includes all objects matching the specification
 * @ throws DatabaseException if a problem occurs during snapshotting
 * @ throws InvalidExampleException if the given catalog / schema combinations are invalid ( e . g . duplicates ) */
public DatabaseSnapshot createSnapshot ( CatalogAndSchema [ ] examples , Database database , SnapshotControl snapshotControl ) throws DatabaseException , InvalidExampleException { } }

implementation:
if ( database == null ) { return null ; } /* * Translate the given examples into " real " Schema objects according to the database ' s abilities ( e . g .
 * does the DB support catalogs ? schemas ? are the given schema / catalog names the default ones for the
 * DB connection ? ) */
Schema [ ] schemas = new Schema [ examples . length ] ; for ( int i = 0 ; i < schemas . length ; i ++ ) { examples [ i ] = examples [ i ] . customize ( database ) ; schemas [ i ] = new Schema ( examples [ i ] . getCatalogName ( ) , examples [ i ] . getSchemaName ( ) ) ; } return createSnapshot ( schemas , database , snapshotControl ) ;


signature:
public class SnapshotGeneratorFactory { /** * Creates a database snapshot for a given array of DatabaseObjects
 * @ param examples an array of DatabaseObjects objects
 * @ param database the database to work on
 * @ param snapshotControl the options / settings for snapshot generation
 * @ return a database snapshot that includes all objects matching the specification
 * @ throws DatabaseException if a problem occurs during snapshotting
 * @ throws InvalidExampleException if the given catalog / schema combinations are invalid ( e . g . duplicates ) */
public DatabaseSnapshot createSnapshot ( DatabaseObject [ ] examples , Database database , SnapshotControl snapshotControl ) throws DatabaseException , InvalidExampleException { } }

implementation: DatabaseConnection conn = database . getConnection ( ) ; if ( conn == null ) { return new EmptyDatabaseSnapshot ( database , snapshotControl ) ; } if ( conn instanceof OfflineConnection ) { DatabaseSnapshot snapshot = ( ( OfflineConnection ) conn ) . getSnapshot ( examples ) ; if ( snapshot == null ) { throw new DatabaseException ( "No snapshotFile parameter specified for offline database" ) ; } return snapshot ; } return new JdbcDatabaseSnapshot ( examples , database , snapshotControl ) ;


signature:
public class SnapshotGeneratorFactory { /** * Creates a DatabaseSnapshot for a single DatabaseObject .
 * @ param example the object to snapshot
 * @ param database the database to work on
 * @ param < T > the type of the object ( must extend DatabaseObject )
 * @ return the snapshot of the desired object
 * @ throws DatabaseException if a problem occurs during snapshotting
 * @ throws InvalidExampleException if the given catalog / schema combinations are invalid ( e . g . duplicates ) */
public < T extends DatabaseObject > T createSnapshot ( T example , Database database ) throws DatabaseException , InvalidExampleException { } }

implementation: return createSnapshot ( example , database , new SnapshotControl ( database ) ) ;


signature:
public class DropAllForeignKeyConstraintsChange { /** * Iterates through all the FOREIGN KEYs of the target table and outputs a list of DropForeignKeyConstraintChanges
 * for a given database type .
 * @ param database the database type for which subchanges need to be generated
 * @ return the list of generated DropForeignKeyConstraintChanges */
private List < DropForeignKeyConstraintChange > generateChildren ( Database database ) { } }

implementation:
// Make a new list
List < DropForeignKeyConstraintChange > childDropChanges = new ArrayList < > ( ) ; try { SnapshotControl control = new SnapshotControl ( database ) ; control . getTypesToInclude ( ) . add ( ForeignKey . class ) ; CatalogAndSchema catalogAndSchema = new CatalogAndSchema ( getBaseTableCatalogName ( ) , getBaseTableSchemaName ( ) ) ; catalogAndSchema = catalogAndSchema . standardize ( database ) ; Table target = SnapshotGeneratorFactory . getInstance ( ) . createSnapshot ( new Table ( catalogAndSchema . getCatalogName ( ) , catalogAndSchema . getSchemaName ( ) , database . correctObjectName ( getBaseTableName ( ) , Table . class ) ) , database ) ; List < ForeignKey > results = ( ( target == null ) ? null : target . getOutgoingForeignKeys ( ) ) ; Set < String > handledConstraints = new HashSet < > ( ) ; if ( ( results != null ) && ( ! results . isEmpty ( ) ) ) { for ( ForeignKey fk : results ) { Table baseTable = fk . getForeignKeyTable ( ) ; String constraintName = fk . getName ( ) ; if ( DatabaseObjectComparatorFactory . getInstance ( ) . isSameObject ( baseTable , target , null , database ) ) { if ( ! handledConstraints . contains ( constraintName ) ) { DropForeignKeyConstraintChange dropForeignKeyConstraintChange = new DropForeignKeyConstraintChange ( ) ; dropForeignKeyConstraintChange . setBaseTableSchemaName ( getBaseTableSchemaName ( ) ) ; dropForeignKeyConstraintChange . setBaseTableName ( baseTableName ) ; dropForeignKeyConstraintChange . setConstraintName ( constraintName ) ; childDropChanges . add ( dropForeignKeyConstraintChange ) ; handledConstraints . add ( constraintName ) ; } } else { throw new UnexpectedLiquibaseException ( "Expected to return only foreign keys for base table name: " + getBaseTableName ( ) + " and got results for table: " + baseTableName ) ; } } } return childDropChanges ; } catch ( DatabaseException | InvalidExampleException e ) { throw new UnexpectedLiquibaseException ( "Failed to find foreign keys for table: " + getBaseTableName ( ) , e ) ; }


signature: public class Index { @ Override public int compareTo ( Object other ) { } }

implementation:
Index o = ( Index ) other ; int returnValue = 0 ; if ( ( this . getRelation ( ) != null ) && ( o . getRelation ( ) != null ) ) { returnValue = this . getRelation ( ) . compareTo ( o . getRelation ( ) ) ; if ( ( returnValue == 0 ) && ( this . getRelation ( ) . getSchema ( ) != null ) && ( o . getRelation ( ) . getSchema ( ) != null ) ) { returnValue = StringUtil . trimToEmpty ( this . getRelation ( ) . getSchema ( ) . getName ( ) ) . compareToIgnoreCase ( StringUtil . trimToEmpty ( o . getRelation ( ) . getSchema ( ) . getName ( ) ) ) ; } } if ( returnValue == 0 ) { String thisName = StringUtil . trimToEmpty ( this . getName ( ) ) ; String oName = StringUtil . trimToEmpty ( o . getName ( ) ) ; returnValue = thisName . compareTo ( oName ) ; } // We should not have two indexes that have the same name and tablename
/* if ( returnValue = = 0 ) {
 returnValue = this . getColumnName ( ) . compareTo ( o . getColumnName ( ) ) ; */
return returnValue ;


signature:
public class FileUtil { /** * Clean a directory without deleting it . */
private static void cleanDirectory ( final File directory ) throws IOException { } }

implementation: if ( ! directory . exists ( ) ) { return ; } if ( ! directory . isDirectory ( ) ) { return ; } IOException exception = null ; final File [ ] files = directory . listFiles ( ) ; if ( files != null ) { for ( final File file : files ) { try { cleanDirectory ( file ) ; if ( ! file . delete ( ) ) { throw new IOException ( "Cannot delete " + file . getAbsolutePath ( ) ) ; } } catch ( final IOException ioe ) { exception = ioe ; } } } if ( null != exception ) { throw exception ; }


signature:
public class StringUtil { /** * Returns the trimmed ( left and right ) form of the input string . If the string is empty after trimming ( or null
 * was passed in the first place ) , null is returned , i . e . the input string is reduced to nothing .
 * @ param string the string to trim
 * @ return the trimmed string or null */
public static String trimToNull ( String string ) { } }

implementation: if ( string == null ) { return null ; } String returnString = string . trim ( ) ; if ( returnString . isEmpty ( ) ) { return null ; } else { return returnString ; }


signature:
public class StringUtil { /** * Removes any comments from multiple line SQL using { @ link # stripComments ( String ) }
 * and then extracts each individual statement using { @ link # splitSQL ( String , String ) } .
 * @ param multiLineSQL A String containing all the SQL statements
 * @ param stripComments If true then comments will be stripped , if false then they will be left in the code */
public static String [ ] processMutliLineSQL ( String multiLineSQL , boolean stripComments , boolean splitStatements , String endDelimiter ) { } }

implementation:
StringClauses parsed = SqlParser . parse ( multiLineSQL , true , ! stripComments ) ; List < String > returnArray = new ArrayList < > ( ) ; StringBuilder currentString = new StringBuilder ( ) ; String previousPiece = null ; boolean previousDelimiter = false ; List < Object > parsedArray = Arrays . asList ( parsed . toArray ( true ) ) ; for ( Object piece : mergeTokens ( parsedArray , endDelimiter ) ) { if ( splitStatements && ( piece instanceof String ) && isDelimiter ( ( String ) piece , previousPiece , endDelimiter ) ) { String trimmedString = StringUtil . trimToNull ( currentString . toString ( ) ) ; if ( trimmedString != null ) { returnArray . add ( trimmedString ) ; } currentString = new StringBuilder ( ) ; previousDelimiter = true ; } else { if ( ! previousDelimiter || ( StringUtil . trimToNull ( ( String ) piece ) != null ) ) { // don ' t include whitespace after a delimiter
if ( ( currentString . length ( ) > 0 ) || ( StringUtil . trimToNull ( ( String ) piece ) != null ) ) { // don ' t include whitespace before the statement
currentString . append ( piece ) ; } } previousDelimiter = false ; } previousPiece = ( String ) piece ; } String trimmedString = StringUtil . trimToNull ( currentString . toString ( ) ) ; if ( trimmedString != null ) { returnArray . add ( trimmedString ) ; } return returnArray . toArray ( new String [ returnArray . size ( ) ] ) ;