proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/executor/jvm/ColumnMapRowMapper.java
|
ColumnMapRowMapper
|
mapRow
|
class ColumnMapRowMapper implements RowMapper {
private final boolean caseSensitiveDatabase;
public ColumnMapRowMapper(boolean caseSensitiveDatabase) {
this.caseSensitiveDatabase = caseSensitiveDatabase;
}
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {<FILL_FUNCTION_BODY>}
/**
* Create a Map instance to be used as column map.
* @param columnCount the column count, to be used as initial
* capacity for the Map
* @return the new Map instance
*/
protected Map createColumnMap(int columnCount) {
return new LinkedHashMap(columnCount);
}
/**
* Determine the key to use for the given column in the column Map.
*
* @param columnName the column name (uppercase) as returned by the ResultSet
* @return the column key to use
* @see java.sql.ResultSetMetaData#getColumnName
*/
protected String getColumnKey(String columnName) {
if (this.caseSensitiveDatabase) {
return columnName;
}
return columnName.toUpperCase(Locale.US);
}
/**
* Retrieve a JDBC object value for the specified column.
* <p>The default implementation uses the <code>getObject</code> method.
* Additionally, this implementation includes a "hack" to get around Oracle
* returning a non standard object for their TIMESTAMP datatype.
*
* @param rs is the ResultSet holding the data
* @param index is the column index
* @return the Object returned
*/
protected Object getColumnValue(ResultSet rs, int index) throws SQLException {
return JdbcUtil.getResultSetValue(rs, index);
}
}
|
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
Map mapOfColValues = createColumnMap(columnCount);
for (int i = 1; i <= columnCount; i++) {
String key = getColumnKey(rsmd.getColumnLabel(i));
Object obj = getColumnValue(rs, i);
mapOfColValues.put(key, obj);
}
return mapOfColValues;
| 458
| 123
| 581
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/executor/jvm/JdbcExecutor.java
|
QueryStatementCallback
|
doInStatement
|
class QueryStatementCallback implements StatementCallback {
private final SqlStatement sql;
private final List<SqlVisitor> sqlVisitors;
private final ResultSetExtractor rse;
private QueryStatementCallback(SqlStatement sql, ResultSetExtractor rse, List<SqlVisitor> sqlVisitors) {
this.sql = sql;
this.rse = rse;
this.sqlVisitors = sqlVisitors;
}
/**
* 1. Applies all SqlVisitor to the stmt
* 2. Executes the (possibly modified) stmt
* 3. Reads all data from the java.sql.ResultSet into an Object and returns the Object.
*
* @param stmt A JDBC Statement that is expected to return a ResultSet (e.g. SELECT)
* @return An object representing all data from the result set.
* @throws SQLException If an error occurs during SQL processing
* @throws DatabaseException If an error occurs in the DBMS-specific program code
*/
@Override
// Incorrect warning, at least at this point. The situation here is not that we inject some unsanitised
// parameter into a query. Instead, we process a whole query. The check should be performed at the places where
// the query is composed.
@SuppressWarnings("squid:S2077")
public Object doInStatement(Statement stmt) throws SQLException, DatabaseException {<FILL_FUNCTION_BODY>}
@Override
public SqlStatement getStatement() {
return sql;
}
}
|
ResultSet rs = null;
try {
String[] sqlToExecute = applyVisitors(sql, sqlVisitors);
if (sqlToExecute.length != 1) {
throw new DatabaseException("Can only query with statements that return one sql statement");
}
try {
rs = stmt.executeQuery(sqlToExecute[0]);
ResultSet rsToUse = rs;
return rse.extractData(rsToUse);
} finally {
for (SqlListener listener : Scope.getCurrentScope().getListeners(SqlListener.class)) {
listener.readSqlWillRun(sqlToExecute[0]);
}
}
} finally {
if (rs != null) {
JdbcUtil.closeResultSet(rs);
}
}
| 391
| 202
| 593
|
<methods>public non-sealed void <init>() ,public void execute(liquibase.change.Change) throws liquibase.exception.DatabaseException,public void execute(liquibase.change.Change, List<liquibase.sql.visitor.SqlVisitor>) throws liquibase.exception.DatabaseException,public abstract java.lang.String getName() ,public abstract int getPriority() ,public void modifyChangeSet(liquibase.changelog.ChangeSet) ,public void setDatabase(liquibase.database.Database) ,public void setResourceAccessor(liquibase.resource.ResourceAccessor) ,public liquibase.exception.ValidationErrors validate(liquibase.changelog.ChangeSet) <variables>protected liquibase.database.Database database,protected liquibase.resource.ResourceAccessor resourceAccessor
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/executor/jvm/RowMapperNotNullConstraintsResultSetExtractor.java
|
RowMapperNotNullConstraintsResultSetExtractor
|
extractData
|
class RowMapperNotNullConstraintsResultSetExtractor extends RowMapperResultSetExtractor {
/**
* Field describes condition for NotNullConstraint in String format e.g. "ID" IS NOT NULL | name = 'foo' | etc.
*/
private static final String SEARCH_CONDITION_FIELD = "SEARCH_CONDITION";
private static final String SEARCH_CONDITION = " is not null";
public RowMapperNotNullConstraintsResultSetExtractor(RowMapper rowMapper) {
super(rowMapper);
if (!(rowMapper instanceof ColumnMapRowMapper)) {
throw new AssertionError(String.format("Class %s should work only with %s",
RowMapperNotNullConstraintsResultSetExtractor.class, ColumnMapRowMapper.class));
}
}
@Override
public Object extractData(ResultSet resultSet) throws SQLException {<FILL_FUNCTION_BODY>}
}
|
List<Object> resultList = (this.rowsExpected > 0 ? new ArrayList<>(this.rowsExpected) : new ArrayList<>());
int rowNum = 0;
while (resultSet.next()) {
Map mapOfColValues = (Map) this.rowMapper.mapRow(resultSet, rowNum++);
Object searchCondition = mapOfColValues.get(SEARCH_CONDITION_FIELD);
if (searchCondition == null) {
continue;
}
String searchConditionString = searchCondition.toString().toLowerCase();
if (searchConditionString.contains(" or ") || searchConditionString.contains(" and ")) {
continue;
}
if (!searchConditionString.contains(SEARCH_CONDITION)) {
continue;
}
resultList.add(mapOfColValues);
}
return resultList;
| 224
| 211
| 435
|
<methods>public void <init>(liquibase.executor.jvm.RowMapper) ,public void <init>(liquibase.executor.jvm.RowMapper, int) ,public java.lang.Object extractData(java.sql.ResultSet) throws java.sql.SQLException<variables>protected final non-sealed liquibase.executor.jvm.RowMapper rowMapper,protected final non-sealed int rowsExpected
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/executor/jvm/RowMapperResultSetExtractor.java
|
RowMapperResultSetExtractor
|
extractData
|
class RowMapperResultSetExtractor implements ResultSetExtractor {
protected final RowMapper rowMapper;
protected final int rowsExpected;
/**
* Create a new RowMapperResultSetExtractor.
*
* @param rowMapper the RowMapper which creates an object for each row
*/
public RowMapperResultSetExtractor(RowMapper rowMapper) {
this(rowMapper, 0);
}
/**
* Create a new RowMapperResultSetExtractor.
*
* @param rowMapper the RowMapper which creates an object for each row
* @param rowsExpected the number of expected rows
* (just used for optimized collection handling)
*/
public RowMapperResultSetExtractor(RowMapper rowMapper, int rowsExpected) {
this.rowMapper = rowMapper;
this.rowsExpected = rowsExpected;
}
@Override
public Object extractData(ResultSet rs) throws SQLException {<FILL_FUNCTION_BODY>}
}
|
List results = ((this.rowsExpected > 0) ? new ArrayList(this.rowsExpected) : new ArrayList());
int rowNum = 0;
while (rs.next()) {
results.add(this.rowMapper.mapRow(rs, rowNum++));
}
return results;
| 248
| 74
| 322
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/executor/jvm/StatementCreatorUtils.java
|
StatementCreatorUtils
|
setParameterValueInternal
|
class StatementCreatorUtils {
/**
* Set the value for a parameter. The method used is based on the SQL type
* of the parameter and we can handle complex types like arrays and LOBs.
*
* @param ps the prepared statement or callable statement
* @param paramIndex index of the parameter we are setting
* @param param the parameter as it is declared including type
* @param inValue the value to set
* @throws SQLException if thrown by PreparedStatement methods
*/
public static void setParameterValue(
PreparedStatement ps, int paramIndex, SqlParameter param, Object inValue)
throws SQLException {
setParameterValueInternal(ps, paramIndex, param.getSqlType(), param.getTypeName(), param.getScale(), inValue);
}
/**
* Set the value for a parameter. The method used is based on the SQL type
* of the parameter and we can handle complex types like arrays and LOBs.
*
* @param ps the prepared statement or callable statement
* @param paramIndex index of the parameter we are setting
* @param sqlType the SQL type of the parameter
* @param inValue the value to set (plain value or a SqlTypeValue)
* @throws SQLException if thrown by PreparedStatement methods
*/
public static void setParameterValue(
PreparedStatement ps, int paramIndex, int sqlType, Object inValue)
throws SQLException {
setParameterValueInternal(ps, paramIndex, sqlType, null, null, inValue);
}
/**
* Set the value for a parameter. The method used is based on the SQL type
* of the parameter and we can handle complex types like arrays and LOBs.
*
* @param ps the prepared statement or callable statement
* @param paramIndex index of the parameter we are setting
* @param sqlType the SQL type of the parameter
* @param typeName the type name of the parameter
* (optional, only used for SQL NULL and SqlTypeValue)
* @param scale the number of digits after the decimal point
* (for DECIMAL and NUMERIC types)
* @param inValue the value to set (plain value or a SqlTypeValue)
* @throws SQLException if thrown by PreparedStatement methods
*/
private static void setParameterValueInternal(
PreparedStatement ps, int paramIndex, int sqlType, String typeName, Integer scale, Object inValue)
throws SQLException {<FILL_FUNCTION_BODY>}
/**
* Check whether the given value can be treated as a String value.
*/
private static boolean isStringValue(Object inValue) {
return ((inValue instanceof CharSequence) || (inValue instanceof StringWriter));
}
/**
* Check whether the given value is a <code>java.util.Date</code>
* (but not one of the JDBC-specific subclasses).
*/
private static boolean isDateValue(Object inValue) {
return ((inValue instanceof java.util.Date) && !((inValue instanceof java.sql.Date) || (inValue instanceof
java.sql.Time) || (inValue instanceof java.sql.Timestamp)));
}
}
|
if (inValue == null) {
if (sqlType == SqlTypeValue.TYPE_UNKNOWN) {
boolean useSetObject = false;
try {
useSetObject = (ps.getConnection().getMetaData().getDatabaseProductName().indexOf("Informix") != -1);
}
catch (Throwable ex) {
// logger.debug("Could not check database product name", ex);
}
if (useSetObject) {
ps.setObject(paramIndex, null);
} else {
ps.setNull(paramIndex, Types.NULL);
}
} else if (typeName != null) {
ps.setNull(paramIndex, sqlType, typeName);
} else {
ps.setNull(paramIndex, sqlType);
}
} else { // inValue != null
if (inValue instanceof SqlTypeValue) {
((SqlTypeValue) inValue).setTypeValue(ps, paramIndex, sqlType, typeName);
} else if ((sqlType == Types.VARCHAR) || (sqlType == -9)) { //-9 is Types.NVARCHAR in java 1.6
ps.setString(paramIndex, inValue.toString());
} else if ((sqlType == Types.DECIMAL) || (sqlType == Types.NUMERIC)) {
if (inValue instanceof BigDecimal) {
ps.setBigDecimal(paramIndex, (BigDecimal) inValue);
} else if (scale != null) {
ps.setObject(paramIndex, inValue, sqlType, scale);
} else {
ps.setObject(paramIndex, inValue, sqlType);
}
} else if (sqlType == Types.DATE) {
if (inValue instanceof java.util.Date) {
if (inValue instanceof java.sql.Date) {
ps.setDate(paramIndex, (java.sql.Date) inValue);
} else {
ps.setDate(paramIndex, new java.sql.Date(((java.util.Date) inValue).getTime()));
}
} else if (inValue instanceof Calendar) {
Calendar cal = (Calendar) inValue;
ps.setDate(paramIndex, new java.sql.Date(cal.getTime().getTime()), cal);
} else {
ps.setObject(paramIndex, inValue, Types.DATE);
}
} else if (sqlType == Types.TIME) {
if (inValue instanceof java.util.Date) {
if (inValue instanceof java.sql.Time) {
ps.setTime(paramIndex, (java.sql.Time) inValue);
} else {
ps.setTime(paramIndex, new java.sql.Time(((java.util.Date) inValue).getTime()));
}
} else if (inValue instanceof Calendar) {
Calendar cal = (Calendar) inValue;
ps.setTime(paramIndex, new java.sql.Time(cal.getTime().getTime()), cal);
} else {
ps.setObject(paramIndex, inValue, Types.TIME);
}
} else if (sqlType == Types.TIMESTAMP) {
if (inValue instanceof java.util.Date) {
if (inValue instanceof java.sql.Timestamp) {
ps.setTimestamp(paramIndex, (java.sql.Timestamp) inValue);
} else {
ps.setTimestamp(paramIndex, new java.sql.Timestamp(((java.util.Date) inValue).getTime()));
}
} else if (inValue instanceof Calendar) {
Calendar cal = (Calendar) inValue;
ps.setTimestamp(paramIndex, new java.sql.Timestamp(cal.getTime().getTime()), cal);
} else {
ps.setObject(paramIndex, inValue, Types.TIMESTAMP);
}
} else if (sqlType == SqlTypeValue.TYPE_UNKNOWN) {
if (isStringValue(inValue)) {
ps.setString(paramIndex, inValue.toString());
} else if (isDateValue(inValue)) {
ps.setTimestamp(paramIndex, new java.sql.Timestamp(((java.util.Date) inValue).getTime()));
} else if (inValue instanceof Calendar) {
Calendar cal = (Calendar) inValue;
ps.setTimestamp(paramIndex, new java.sql.Timestamp(cal.getTime().getTime()));
} else {
// Fall back to generic setObject call without SQL type specified.
ps.setObject(paramIndex, inValue);
}
} else {
// Fall back to generic setObject call with SQL type specified.
ps.setObject(paramIndex, inValue, sqlType);
}
}
| 793
| 1,176
| 1,969
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/AbstractChangeLogBasedTask.java
|
AbstractChangeLogBasedTask
|
validateParameters
|
class AbstractChangeLogBasedTask extends BaseLiquibaseTask {
@Setter
private String searchPath;
@Setter
private String changeLogDirectory;
@Setter
private String changeLogFile;
@Getter
@Setter
private String contexts;
@Getter
private LabelExpression labelFilter;
@Getter
@Setter
private FileResource outputFile;
@Setter
private String outputEncoding;
@Override
protected void validateParameters() {<FILL_FUNCTION_BODY>}
protected Writer getOutputFileWriter() throws IOException {
return new OutputStreamWriter(outputFile.getOutputStream(), getOutputEncoding());
}
/**
* Gets the change log directory set from Ant.
* @return The change log directory resource.
*/
@Override
public String getChangeLogDirectory() {
return changeLogDirectory;
}
/**
* Gets the change log directory set from Ant.
* @return The change log directory resource.
*/
@Override
public String getSearchPath() {
return searchPath;
}
/**
* Gets the change log file set from Ant.
* @return The change log file resource.
*/
@Override
public String getChangeLogFile() {
return changeLogFile;
}
/**
* @deprecated use {@link #getLabelFilter()}
*/
public LabelExpression getLabels() {
return getLabelFilter();
}
/**
* @deprecated use {@link #setLabelFilter(String)}
*/
public void setLabels(String labelFilter) {
this.setLabelFilter(labelFilter);
}
public void setLabelFilter(String labelFilter) {
this.labelFilter = new LabelExpression(labelFilter);
}
public String getOutputEncoding() {
return (StringUtil.trimToNull(outputEncoding) == null) ? getDefaultOutputEncoding() : outputEncoding.trim();
}
}
|
super.validateParameters();
if(changeLogFile == null) {
throw new BuildException("Change log file is required.");
}
| 499
| 38
| 537
|
<methods>public void <init>() ,public void addChangeLogParameters(liquibase.integration.ant.type.ChangeLogParametersType) ,public void addDatabase(liquibase.integration.ant.type.DatabaseType) ,public Path createClasspath() ,public final void execute() throws BuildException,public java.lang.String getChangeLogDirectory() ,public java.lang.String getSearchPath() ,public void init() throws BuildException,public boolean isPromptOnNonLocalDatabase() ,public void setChangeLogParametersRef(Reference) ,public void setClasspathRef(Reference) ,public void setDatabaseRef(Reference) ,public void setPromptOnNonLocalDatabase(boolean) <variables>private liquibase.integration.ant.type.ChangeLogParametersType changeLogParameters,private AntClassLoader classLoader,private Path classpath,private static final java.util.ResourceBundle coreBundle,private liquibase.integration.ant.type.DatabaseType databaseType,private liquibase.Liquibase liquibase,private liquibase.resource.ResourceAccessor resourceAccessor,private final Map<java.lang.String,java.lang.Object> scopeValues
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/AbstractDatabaseDiffTask.java
|
AbstractDatabaseDiffTask
|
validateParameters
|
class AbstractDatabaseDiffTask extends BaseLiquibaseTask {
private DatabaseType referenceDatabaseType;
@Getter
@Setter
private String diffTypes;
protected DiffResult getDiffResult() {
Liquibase liquibase = getLiquibase();
Database targetDatabase = liquibase.getDatabase();
Database referenceDatabase = createDatabaseFromType(referenceDatabaseType, getResourceAccessor());
CatalogAndSchema targetCatalogAndSchema = buildCatalogAndSchema(targetDatabase);
CatalogAndSchema referenceCatalogAndSchema = buildCatalogAndSchema(referenceDatabase);
CompareControl.SchemaComparison[] schemaComparisons = {
new CompareControl.SchemaComparison(referenceCatalogAndSchema, targetCatalogAndSchema)
};
SnapshotGeneratorFactory snapshotGeneratorFactory = SnapshotGeneratorFactory.getInstance();
DatabaseSnapshot referenceSnapshot;
try {
referenceSnapshot = snapshotGeneratorFactory.createSnapshot(referenceDatabase.getDefaultSchema(),
referenceDatabase, new SnapshotControl(referenceDatabase, diffTypes));
} catch (LiquibaseException e) {
throw new BuildException("Unable to create a DatabaseSnapshot: " + e.getMessage(), e);
}
CompareControl compareControl = new CompareControl(schemaComparisons, referenceSnapshot.getSnapshotControl().getTypesToInclude());
try {
return liquibase.diff(referenceDatabase, targetDatabase, compareControl);
} catch (LiquibaseException e) {
throw new BuildException("Unable to diff databases: " + e.getMessage(), e);
}
}
@Override
protected void validateParameters() {<FILL_FUNCTION_BODY>}
private CatalogAndSchema buildCatalogAndSchema(Database database) {
return new CatalogAndSchema(database.getDefaultCatalogName(), database.getDefaultSchemaName());
}
public void addReferenceDatabase(DatabaseType referenceDatabase) {
if(this.referenceDatabaseType != null) {
throw new BuildException("Only one <referenceDatabase> element is allowed.");
}
this.referenceDatabaseType = referenceDatabase;
}
public void setReferenceDatabaseRef(Reference referenceDatabaseRef) {
referenceDatabaseType = new DatabaseType(getProject());
referenceDatabaseType.setRefid(referenceDatabaseRef);
}
}
|
super.validateParameters();
if(referenceDatabaseType == null) {
throw new BuildException("Reference database element or reference required.");
}
| 558
| 39
| 597
|
<methods>public void <init>() ,public void addChangeLogParameters(liquibase.integration.ant.type.ChangeLogParametersType) ,public void addDatabase(liquibase.integration.ant.type.DatabaseType) ,public Path createClasspath() ,public final void execute() throws BuildException,public java.lang.String getChangeLogDirectory() ,public java.lang.String getSearchPath() ,public void init() throws BuildException,public boolean isPromptOnNonLocalDatabase() ,public void setChangeLogParametersRef(Reference) ,public void setClasspathRef(Reference) ,public void setDatabaseRef(Reference) ,public void setPromptOnNonLocalDatabase(boolean) <variables>private liquibase.integration.ant.type.ChangeLogParametersType changeLogParameters,private AntClassLoader classLoader,private Path classpath,private static final java.util.ResourceBundle coreBundle,private liquibase.integration.ant.type.DatabaseType databaseType,private liquibase.Liquibase liquibase,private liquibase.resource.ResourceAccessor resourceAccessor,private final Map<java.lang.String,java.lang.Object> scopeValues
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/AntTaskLogger.java
|
AntTaskLogger
|
log
|
class AntTaskLogger extends AbstractLogger {
private final Task task;
/**
* @deprecated use {@link AntTaskLogger(Task)} instead
*/
@Deprecated
public AntTaskLogger(Task task, LogMessageFilter ignored) {
this(task);
}
public AntTaskLogger(Task task) {
this.task = task;
}
@Override
public void log(Level level, String message, Throwable e) {<FILL_FUNCTION_BODY>}
}
|
if (level == Level.OFF) {
return;
}
int antLevel;
if (level.intValue() == Level.SEVERE.intValue()) {
antLevel = Project.MSG_ERR;
} else if (level.intValue() == Level.WARNING.intValue()) {
antLevel = Project.MSG_WARN;
} else if (level.intValue() == Level.INFO.intValue()) {
antLevel = Project.MSG_INFO;
} else if (level.intValue() == Level.CONFIG.intValue()) {
//no config level, using debug
antLevel = Project.MSG_DEBUG;
} else if (level.intValue() == Level.FINE.intValue()) {
antLevel = Project.MSG_DEBUG;
} else {
//lower than FINE
antLevel = Project.MSG_DEBUG;
}
task.log(filterMessage(message), e, antLevel);
| 129
| 242
| 371
|
<methods>public void config(java.lang.String) ,public void config(java.lang.String, java.lang.Throwable) ,public void debug(java.lang.String) ,public void debug(java.lang.String, java.lang.Throwable) ,public void fine(java.lang.String) ,public void fine(java.lang.String, java.lang.Throwable) ,public void info(java.lang.String) ,public void info(java.lang.String, java.lang.Throwable) ,public void severe(java.lang.String) ,public void severe(java.lang.String, java.lang.Throwable) ,public void warning(java.lang.String) ,public void warning(java.lang.String, java.lang.Throwable) <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/BaseLiquibaseTask.java
|
BaseLiquibaseTask
|
addDatabase
|
class BaseLiquibaseTask extends Task {
private static final ResourceBundle coreBundle = getBundle("liquibase/i18n/liquibase-core");
private final Map<String, Object> scopeValues = new HashMap<>();
private AntClassLoader classLoader;
private Liquibase liquibase;
private ResourceAccessor resourceAccessor;
private Path classpath;
private DatabaseType databaseType;
private ChangeLogParametersType changeLogParameters;
public BaseLiquibaseTask() {
super();
}
@Override
public void init() throws BuildException {
scopeValues.put(Scope.Attr.logService.name(), new AntTaskLogService(this));
classpath = new Path(getProject());
}
@Override
public final void execute() throws BuildException {
super.execute();
log(coreBundle.getString("starting.liquibase"), Project.MSG_INFO);
classLoader = getProject().createClassLoader(classpath);
classLoader.setParent(this.getClass().getClassLoader());
classLoader.setThreadContextLoader();
validateParameters();
final Database[] database = {null};
try {
resourceAccessor = createResourceAccessor(classLoader);
scopeValues.put(Scope.Attr.resourceAccessor.name(), resourceAccessor);
scopeValues.put(Scope.Attr.classLoader.name(), classLoader);
Scope.child(scopeValues, () -> {
database[0] = createDatabaseFromType(databaseType, resourceAccessor);
liquibase = new Liquibase(getChangeLogFile(), resourceAccessor, database[0]);
if (changeLogParameters != null) {
changeLogParameters.applyParameters(liquibase);
}
if (shouldRun()) {
executeWithLiquibaseClassloader();
}
});
} catch (Exception e) {
throw new BuildException("Unable to initialize Liquibase: " + e.getMessage(), e);
} finally {
closeDatabase(database[0]);
classLoader.resetThreadContextLoader();
classLoader.cleanup();
classLoader = null;
}
}
protected abstract void executeWithLiquibaseClassloader() throws BuildException;
protected Database createDatabaseFromConfiguredDatabaseType() {
return createDatabaseFromType(databaseType, getResourceAccessor());
}
protected Database createDatabaseFromType(DatabaseType databaseType, ResourceAccessor resourceAccessor) {
return databaseType.createDatabase(resourceAccessor);
}
protected Liquibase getLiquibase() {
return liquibase;
}
protected ResourceAccessor getResourceAccessor() {
if (resourceAccessor == null) {
throw new IllegalStateException("The ResourceAccessor has not been initialized. This usually means this " +
"method has been called before the task's execute method has called.");
}
return resourceAccessor;
}
/**
* This method is designed to be overridden by subclasses when a change log is needed. By default it returns null.
*
* @return Returns null in this implementation. Subclasses that need a change log should implement.
* @see AbstractChangeLogBasedTask#getChangeLogDirectory()
*/
public String getChangeLogDirectory() {
return null;
}
/**
* This method is designed to be overridden by subclasses when a change log is needed. By default it returns null.
*
* @return Returns null in this implementation. Subclasses that need a change log should implement.
*/
public String getSearchPath() {
return null;
}
/**
* This method is designed to be overridden by subclasses when a change log is needed. By default it returns null.
*
* @return Returns null in this implementation. Subclasses that need a change log should implement.
* @see AbstractChangeLogBasedTask#getChangeLogFile()
*/
protected String getChangeLogFile() {
return null;
}
protected boolean shouldRun() {
if (!LiquibaseCommandLineConfiguration.SHOULD_RUN.getCurrentValue()) {
log("Liquibase did not run because " + LiquibaseCommandLineConfiguration.SHOULD_RUN.getKey() + " was set to false", Project.MSG_INFO);
return false;
}
return true;
}
protected String getDefaultOutputEncoding() {
return GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue();
}
/**
* Subclasses that override this method must always call <code>super.validateParameters()</code> method.
*/
protected void validateParameters() {
if (databaseType == null) {
throw new BuildException("A database or databaseref is required.");
}
}
/**
* Creates a suitable ResourceAccessor for use in an Ant task..
*
* @param classLoader The ClassLoader to use in the ResourceAccessor. It is preferable that it is an AntClassLoader.
* @return A ResourceAccessor.
*/
@SuppressWarnings("java:S2095")
private ResourceAccessor createResourceAccessor(AntClassLoader classLoader) {
return new SearchPathResourceAccessor(getSearchPath(),
new AntResourceAccessor(classLoader, getChangeLogDirectory()),
new ClassLoaderResourceAccessor(Thread.currentThread().getContextClassLoader())
);
}
/*
* Ant parameters
*/
/**
* Convenience method to safely close the database connection.
*
* @param database The database to close.
*/
protected void closeDatabase(Database database) {
try {
if (database != null) {
database.close();
}
} catch (DatabaseException e) {
log("Error closing the database connection.", e, Project.MSG_WARN);
}
}
public Path createClasspath() {
if (this.classpath == null) {
this.classpath = new Path(getProject());
}
return this.classpath.createPath();
}
public void setClasspathRef(Reference r) {
createClasspath().setRefid(r);
}
public void addDatabase(DatabaseType databaseType) {<FILL_FUNCTION_BODY>}
public void setDatabaseRef(Reference databaseRef) {
databaseType = new DatabaseType(getProject());
databaseType.setRefid(databaseRef);
}
public void addChangeLogParameters(ChangeLogParametersType changeLogParameters) {
if (this.changeLogParameters != null) {
throw new BuildException("Only one <changeLogParameters> element is allowed.");
}
this.changeLogParameters = changeLogParameters;
}
public void setChangeLogParametersRef(Reference changeLogParametersRef) {
changeLogParameters = new ChangeLogParametersType(getProject());
changeLogParameters.setRefid(changeLogParametersRef);
}
/**
* @deprecated no longer prompts
*/
public boolean isPromptOnNonLocalDatabase() {
return false;
}
/**
* @deprecated no longer prompts
*/
public void setPromptOnNonLocalDatabase(boolean promptOnNonLocalDatabase) {
log("NOTE: The promptOnLocalDatabase functionality has been removed", Project.MSG_INFO);
}
}
|
if (this.databaseType != null) {
throw new BuildException("Only one <database> element is allowed.");
}
this.databaseType = databaseType;
| 1,843
| 45
| 1,888
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/ChangeLogSyncTask.java
|
ChangeLogSyncTask
|
executeWithLiquibaseClassloader
|
class ChangeLogSyncTask extends AbstractChangeLogBasedTask {
private String toTag;
@Override
public void executeWithLiquibaseClassloader() throws BuildException {<FILL_FUNCTION_BODY>}
public void setToTag(String toTag) {
this.toTag = toTag;
}
}
|
Liquibase liquibase = getLiquibase();
OutputStreamWriter writer = null;
try {
FileResource outputFile = getOutputFile();
if (outputFile != null) {
writer = new OutputStreamWriter(outputFile.getOutputStream(), getOutputEncoding());
liquibase.changeLogSync(toTag, new Contexts(getContexts()), getLabelFilter(), writer);
} else {
liquibase.changeLogSync(toTag, new Contexts(getContexts()), getLabelFilter());
}
} catch (UnsupportedEncodingException e) {
throw new BuildException("Unable to generate sync SQL. Encoding [" + getOutputEncoding() + "] is not supported.", e);
} catch (IOException e) {
throw new BuildException("Unable to generate sync SQL. Error creating output writer.", e);
} catch (LiquibaseException e) {
throw new BuildException("Unable to sync change log: " + e.getMessage(), e);
} finally {
FileUtils.close(writer);
}
| 83
| 258
| 341
|
<methods>public non-sealed void <init>() ,public java.lang.String getChangeLogDirectory() ,public java.lang.String getChangeLogFile() ,public liquibase.LabelExpression getLabels() ,public java.lang.String getOutputEncoding() ,public java.lang.String getSearchPath() ,public void setLabelFilter(java.lang.String) ,public void setLabels(java.lang.String) <variables>private java.lang.String changeLogDirectory,private java.lang.String changeLogFile,private java.lang.String contexts,private liquibase.LabelExpression labelFilter,private java.lang.String outputEncoding,private FileResource outputFile,private java.lang.String searchPath
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/ChangeLogSyncToTagTask.java
|
ChangeLogSyncToTagTask
|
executeWithLiquibaseClassloader
|
class ChangeLogSyncToTagTask extends AbstractChangeLogBasedTask {
private String toTag;
@Override
public void executeWithLiquibaseClassloader() throws BuildException {<FILL_FUNCTION_BODY>}
public void setToTag(String toTag) {
this.toTag = toTag;
}
}
|
Liquibase liquibase = getLiquibase();
OutputStreamWriter writer = null;
try {
FileResource outputFile = getOutputFile();
if (outputFile != null) {
writer = new OutputStreamWriter(outputFile.getOutputStream(), getOutputEncoding());
liquibase.changeLogSync(toTag, new Contexts(getContexts()), getLabelFilter(), writer);
} else {
liquibase.changeLogSync(toTag, new Contexts(getContexts()), getLabelFilter());
}
} catch (UnsupportedEncodingException e) {
throw new BuildException("Unable to generate sync SQL. Encoding [" + getOutputEncoding() + "] is not supported.", e);
} catch (IOException e) {
throw new BuildException("Unable to generate sync SQL. Error creating output writer.", e);
} catch (LiquibaseException e) {
throw new BuildException("Unable to sync change log: " + e.getMessage(), e);
} finally {
FileUtils.close(writer);
}
| 85
| 258
| 343
|
<methods>public non-sealed void <init>() ,public java.lang.String getChangeLogDirectory() ,public java.lang.String getChangeLogFile() ,public liquibase.LabelExpression getLabels() ,public java.lang.String getOutputEncoding() ,public java.lang.String getSearchPath() ,public void setLabelFilter(java.lang.String) ,public void setLabels(java.lang.String) <variables>private java.lang.String changeLogDirectory,private java.lang.String changeLogFile,private java.lang.String contexts,private liquibase.LabelExpression labelFilter,private java.lang.String outputEncoding,private FileResource outputFile,private java.lang.String searchPath
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/DBDocTask.java
|
DBDocTask
|
executeWithLiquibaseClassloader
|
class DBDocTask extends BaseLiquibaseTask {
private FileResource outputDirectory;
private String changeLog;
private String contexts;
@Override
public void executeWithLiquibaseClassloader() throws BuildException {<FILL_FUNCTION_BODY>}
@Override
protected void validateParameters() {
super.validateParameters();
if(changeLog == null) {
throw new BuildException("Change log is required.");
}
if(outputDirectory == null) {
throw new BuildException("Output directory is required.");
}
}
@Override
protected String getChangeLogFile() {
return changeLog;
}
public void setChangeLogFile(String changeLog) {
this.changeLog = changeLog;
}
public FileResource getOutputDirectory() {
return outputDirectory;
}
public void setOutputDirectory(FileResource outputDirectory) {
this.outputDirectory = outputDirectory;
}
public void setContexts(String contexts) {
this.contexts = contexts;
}
}
|
File outputDirFile = outputDirectory.getFile();
if(!outputDirFile.exists()) {
boolean success = outputDirFile.mkdirs();
if(!success) {
throw new BuildException("Unable to create output directory.");
}
}
if(!outputDirFile.isDirectory()) {
throw new BuildException("Output path is not a directory.");
}
Liquibase liquibase = getLiquibase();
try {
if (contexts != null) {
liquibase.generateDocumentation(outputDirectory.toString(), contexts);
} else {
liquibase.generateDocumentation(outputDirectory.toString());
}
} catch (LiquibaseException e) {
throw new BuildException("Liquibase encountered an error while creating database documentation. " + e, e);
}
| 269
| 209
| 478
|
<methods>public void <init>() ,public void addChangeLogParameters(liquibase.integration.ant.type.ChangeLogParametersType) ,public void addDatabase(liquibase.integration.ant.type.DatabaseType) ,public Path createClasspath() ,public final void execute() throws BuildException,public java.lang.String getChangeLogDirectory() ,public java.lang.String getSearchPath() ,public void init() throws BuildException,public boolean isPromptOnNonLocalDatabase() ,public void setChangeLogParametersRef(Reference) ,public void setClasspathRef(Reference) ,public void setDatabaseRef(Reference) ,public void setPromptOnNonLocalDatabase(boolean) <variables>private liquibase.integration.ant.type.ChangeLogParametersType changeLogParameters,private AntClassLoader classLoader,private Path classpath,private static final java.util.ResourceBundle coreBundle,private liquibase.integration.ant.type.DatabaseType databaseType,private liquibase.Liquibase liquibase,private liquibase.resource.ResourceAccessor resourceAccessor,private final Map<java.lang.String,java.lang.Object> scopeValues
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/DatabaseRollbackFutureTask.java
|
DatabaseRollbackFutureTask
|
executeWithLiquibaseClassloader
|
class DatabaseRollbackFutureTask extends AbstractChangeLogBasedTask {
@Override
public void executeWithLiquibaseClassloader() throws BuildException {<FILL_FUNCTION_BODY>}
@Override
protected void validateParameters() {
super.validateParameters();
if(getOutputFile() == null) {
throw new BuildException("Output file is required.");
}
}
}
|
Liquibase liquibase = getLiquibase();
try (Writer outputFileWriter = getOutputFileWriter()) {
liquibase.futureRollbackSQL(new Contexts(getContexts()), getLabelFilter(), outputFileWriter);
} catch (LiquibaseException e) {
throw new BuildException("Unable to generate future rollback SQL: " + e.getMessage(), e);
} catch (IOException e) {
throw new BuildException("Unable to generate future rollback SQL. Error creating output writer.", e);
}
| 101
| 134
| 235
|
<methods>public non-sealed void <init>() ,public java.lang.String getChangeLogDirectory() ,public java.lang.String getChangeLogFile() ,public liquibase.LabelExpression getLabels() ,public java.lang.String getOutputEncoding() ,public java.lang.String getSearchPath() ,public void setLabelFilter(java.lang.String) ,public void setLabels(java.lang.String) <variables>private java.lang.String changeLogDirectory,private java.lang.String changeLogFile,private java.lang.String contexts,private liquibase.LabelExpression labelFilter,private java.lang.String outputEncoding,private FileResource outputFile,private java.lang.String searchPath
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/DatabaseRollbackTask.java
|
DatabaseRollbackTask
|
executeWithLiquibaseClassloader
|
class DatabaseRollbackTask extends AbstractChangeLogBasedTask {
private Date rollbackDate;
private String rollbackTag;
private Integer rollbackCount;
private String rollbackScript;
@Override
public void executeWithLiquibaseClassloader() throws BuildException {<FILL_FUNCTION_BODY>}
public Date getRollbackDate() {
if (rollbackDate == null) {
return null;
}
return new Date(rollbackDate.getTime());
}
public void setRollbackDate(String rollbackDateStr) {
if((rollbackTag != null) || (rollbackCount != null)) {
throw new BuildException("Unable to rollback database. A tag or count has already been set.");
}
try {
this.rollbackDate = DateUtils.parseIso8601DateTimeOrDate(rollbackDateStr);
} catch (ParseException e) {
throw new BuildException("Unable to parse rollback date/time string into a Date object. Please make sure the date or date/time is in ISO 8601 format (yyyy-MM-dd or yyyy-MM-ddTHH:mm:ss).", e);
}
}
public String getRollbackTag() {
return rollbackTag;
}
public void setRollbackTag(String rollbackTag) {
if((rollbackDate != null) || (rollbackCount != null)) {
throw new BuildException("Unable to rollback database. A date or count has already been set.");
}
this.rollbackTag = rollbackTag;
}
public Integer getRollbackCount() {
return rollbackCount;
}
public void setRollbackCount(Integer rollbackCount) {
if((rollbackDate != null) || (rollbackTag != null)) {
throw new BuildException("Unable to rollback database. A date or tag has already been set.");
}
this.rollbackCount = rollbackCount;
}
public String getRollbackScript() {
return rollbackScript;
}
public void setRollbackScript(String rollbackScript) {
this.rollbackScript = rollbackScript;
}
}
|
Writer writer = null;
Liquibase liquibase = getLiquibase();
try {
FileResource outputFile = getOutputFile();
if(rollbackCount != null) {
if(outputFile != null) {
writer = getOutputFileWriter();
liquibase.rollback(rollbackCount, rollbackScript, new Contexts(getContexts()), getLabelFilter(), writer);
} else {
liquibase.rollback(rollbackCount, rollbackScript, new Contexts(getContexts()), getLabelFilter());
}
} else if(rollbackTag != null) {
if(outputFile != null) {
writer = getOutputFileWriter();
liquibase.rollback(rollbackTag, rollbackScript, new Contexts(getContexts()), getLabelFilter(), writer);
} else {
liquibase.rollback(rollbackTag, rollbackScript, new Contexts(getContexts()), getLabelFilter());
}
} else if(rollbackDate != null) {
if(outputFile != null) {
writer = getOutputFileWriter();
liquibase.rollback(rollbackDate, rollbackScript, new Contexts(getContexts()), getLabelFilter(), writer);
} else {
liquibase.rollback(rollbackDate, rollbackScript, new Contexts(getContexts()), getLabelFilter());
}
} else {
throw new BuildException("Unable to rollback database. No count, tag, or date set.");
}
} catch (LiquibaseException e) {
throw new BuildException("Unable to rollback database: " + e.getMessage(), e);
} catch (UnsupportedEncodingException e) {
throw new BuildException("Unable to generate rollback SQL. Encoding [" + getOutputEncoding() + "] is not supported.", e);
} catch (IOException e) {
throw new BuildException("Unable to generate rollback SQL. Error creating output writer.", e);
} finally {
FileUtils.close(writer);
}
| 562
| 504
| 1,066
|
<methods>public non-sealed void <init>() ,public java.lang.String getChangeLogDirectory() ,public java.lang.String getChangeLogFile() ,public liquibase.LabelExpression getLabels() ,public java.lang.String getOutputEncoding() ,public java.lang.String getSearchPath() ,public void setLabelFilter(java.lang.String) ,public void setLabels(java.lang.String) <variables>private java.lang.String changeLogDirectory,private java.lang.String changeLogFile,private java.lang.String contexts,private liquibase.LabelExpression labelFilter,private java.lang.String outputEncoding,private FileResource outputFile,private java.lang.String searchPath
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/DatabaseUpdateTask.java
|
DatabaseUpdateTask
|
executeWithLiquibaseClassloader
|
class DatabaseUpdateTask extends AbstractChangeLogBasedTask {
private boolean dropFirst;
private String toTag;
@Override
public void executeWithLiquibaseClassloader() throws BuildException {<FILL_FUNCTION_BODY>}
public boolean isDropFirst() {
return dropFirst;
}
public void setDropFirst(boolean dropFirst) {
this.dropFirst = dropFirst;
}
public String getToTag() {
return toTag;
}
public void setToTag(String toTag) {
this.toTag = toTag;
}
}
|
Writer writer = null;
Liquibase liquibase = getLiquibase();
try {
FileResource outputFile = getOutputFile();
if(outputFile != null) {
writer = getOutputFileWriter();
liquibase.update(toTag, new Contexts(getContexts()), getLabelFilter(), writer);
} else {
if(dropFirst) {
liquibase.dropAll();
}
liquibase.update(toTag, new Contexts(getContexts()), getLabelFilter());
}
} catch (LiquibaseException e) {
throw new BuildException("Unable to update database: " + e.getMessage(), e);
} catch (UnsupportedEncodingException e) {
throw new BuildException("Unable to generate update SQL. Encoding [" + getOutputEncoding() + "] is not supported.", e);
} catch (IOException e) {
throw new BuildException("Unable to generate update SQL. Error creating output writer.", e);
} finally {
FileUtils.close(writer);
}
| 154
| 262
| 416
|
<methods>public non-sealed void <init>() ,public java.lang.String getChangeLogDirectory() ,public java.lang.String getChangeLogFile() ,public liquibase.LabelExpression getLabels() ,public java.lang.String getOutputEncoding() ,public java.lang.String getSearchPath() ,public void setLabelFilter(java.lang.String) ,public void setLabels(java.lang.String) <variables>private java.lang.String changeLogDirectory,private java.lang.String changeLogFile,private java.lang.String contexts,private liquibase.LabelExpression labelFilter,private java.lang.String outputEncoding,private FileResource outputFile,private java.lang.String searchPath
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/DatabaseUpdateTestingRollbackTask.java
|
DatabaseUpdateTestingRollbackTask
|
executeWithLiquibaseClassloader
|
class DatabaseUpdateTestingRollbackTask extends AbstractChangeLogBasedTask {
private boolean dropFirst;
@Override
public void executeWithLiquibaseClassloader() throws BuildException {<FILL_FUNCTION_BODY>}
public boolean isDropFirst() {
return dropFirst;
}
public void setDropFirst(boolean dropFirst) {
this.dropFirst = dropFirst;
}
}
|
Liquibase liquibase = getLiquibase();
try {
if (isDropFirst()) {
liquibase.dropAll();
}
liquibase.updateTestingRollback(new Contexts(getContexts()), getLabelFilter());
} catch (LiquibaseException e) {
throw new BuildException("Unable to update database with a rollback test: " + e.getMessage(), e);
}
| 106
| 111
| 217
|
<methods>public non-sealed void <init>() ,public java.lang.String getChangeLogDirectory() ,public java.lang.String getChangeLogFile() ,public liquibase.LabelExpression getLabels() ,public java.lang.String getOutputEncoding() ,public java.lang.String getSearchPath() ,public void setLabelFilter(java.lang.String) ,public void setLabels(java.lang.String) <variables>private java.lang.String changeLogDirectory,private java.lang.String changeLogFile,private java.lang.String contexts,private liquibase.LabelExpression labelFilter,private java.lang.String outputEncoding,private FileResource outputFile,private java.lang.String searchPath
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/DiffDatabaseTask.java
|
DiffDatabaseTask
|
executeWithLiquibaseClassloader
|
class DiffDatabaseTask extends AbstractDatabaseDiffTask {
private FileResource outputFile;
private String outputEncoding = GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue();
@Override
public void executeWithLiquibaseClassloader() throws BuildException {<FILL_FUNCTION_BODY>}
@Override
protected void validateParameters() {
super.validateParameters();
if(outputFile == null) {
throw new BuildException("Unable to make diff report. Output file is required.");
}
}
public void setOutputFile(FileResource outputFile) {
this.outputFile = outputFile;
}
public String getOutputEncoding() {
return outputEncoding;
}
public void setOutputEncoding(String outputEncoding) {
this.outputEncoding = outputEncoding;
}
}
|
PrintStream printStream = null;
try {
printStream = new PrintStream(outputFile.getOutputStream(), true, getOutputEncoding());
DiffResult diffResult = getDiffResult();
DiffToReport diffReport = new DiffToReport(diffResult, printStream);
log("Writing diff report " + outputFile.toString(), Project.MSG_INFO);
diffReport.print();
} catch (DatabaseException e) {
throw new BuildException("Unable to make diff report: " + e.getMessage(), e);
} catch (UnsupportedEncodingException e) {
throw new BuildException("Unable to make diff report. Encoding [" + outputEncoding + "] is not supported.", e);
} catch (IOException e) {
throw new BuildException("Unable to make diff report. Error opening output stream.", e);
} finally {
FileUtils.close(printStream);
}
| 210
| 217
| 427
|
<methods>public non-sealed void <init>() ,public void addReferenceDatabase(liquibase.integration.ant.type.DatabaseType) ,public void setReferenceDatabaseRef(Reference) <variables>private java.lang.String diffTypes,private liquibase.integration.ant.type.DatabaseType referenceDatabaseType
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/DiffDatabaseToChangeLogTask.java
|
DiffDatabaseToChangeLogTask
|
executeWithLiquibaseClassloader
|
class DiffDatabaseToChangeLogTask extends AbstractDatabaseDiffTask {
private final Set<ChangeLogOutputFile> changeLogOutputFiles = new LinkedHashSet<>();
private boolean includeSchema = true;
private boolean includeCatalog = true;
private boolean includeTablespace = true;
private String includeObjects;
private String excludeObjects;
@Override
protected void executeWithLiquibaseClassloader() throws BuildException {<FILL_FUNCTION_BODY>}
@Override
protected void validateParameters() {
super.validateParameters();
if(changeLogOutputFiles.isEmpty()) {
throw new BuildException("At least one output file element (<json>, <yaml>, <xml>, or <txt>)must be defined.");
}
}
public String getOutputEncoding(ChangeLogOutputFile changeLogOutputFile) {
String encoding = changeLogOutputFile.getEncoding();
return (encoding == null) ? getDefaultOutputEncoding() : encoding;
}
private DiffOutputControl getDiffOutputControl() {
DiffOutputControl diffOutputControl = new DiffOutputControl(includeCatalog, includeSchema, includeTablespace, null);
if ((excludeObjects != null) && (includeObjects != null)) {
throw new UnexpectedLiquibaseException("Cannot specify both excludeObjects and includeObjects");
}
if (excludeObjects != null) {
diffOutputControl.setObjectChangeFilter(new StandardObjectChangeFilter(StandardObjectChangeFilter.FilterType.EXCLUDE, excludeObjects));
}
if (includeObjects != null) {
diffOutputControl.setObjectChangeFilter(new StandardObjectChangeFilter(StandardObjectChangeFilter.FilterType.INCLUDE, includeObjects));
}
return diffOutputControl;
}
public void addConfiguredJson(ChangeLogOutputFile changeLogOutputFile) {
changeLogOutputFile.setChangeLogSerializer(new JsonChangeLogSerializer());
changeLogOutputFiles.add(changeLogOutputFile);
}
public void addConfiguredXml(ChangeLogOutputFile changeLogOutputFile) {
changeLogOutputFile.setChangeLogSerializer(ChangeLogSerializerFactory.getInstance().getSerializer("xml"));
changeLogOutputFiles.add(changeLogOutputFile);
}
public void addConfiguredYaml(ChangeLogOutputFile changeLogOutputFile) {
changeLogOutputFile.setChangeLogSerializer(ChangeLogSerializerFactory.getInstance().getSerializer("yaml"));
changeLogOutputFiles.add(changeLogOutputFile);
}
public void addConfiguredTxt(ChangeLogOutputFile changeLogOutputFile) {
changeLogOutputFile.setChangeLogSerializer(new StringChangeLogSerializer());
changeLogOutputFiles.add(changeLogOutputFile);
}
public boolean getIncludeCatalog() {
return includeCatalog;
}
public void setIncludeCatalog(boolean includeCatalog) {
this.includeCatalog = includeCatalog;
}
public boolean getIncludeSchema() {
return includeSchema;
}
public void setIncludeSchema(boolean includeSchema) {
this.includeSchema = includeSchema;
}
public boolean getIncludeTablespace() {
return includeTablespace;
}
public void setIncludeTablespace(boolean includeTablespace) {
this.includeTablespace = includeTablespace;
}
public String getIncludeObjects() {
return includeObjects;
}
public void setIncludeObjects(String includeObjects) {
this.includeObjects = includeObjects;
}
public String getExcludeObjects() {
return excludeObjects;
}
public void setExcludeObjects(String excludeObjects) {
this.excludeObjects = excludeObjects;
}
}
|
for(ChangeLogOutputFile changeLogOutputFile : changeLogOutputFiles) {
PrintStream printStream = null;
String encoding = getOutputEncoding(changeLogOutputFile);
try {
FileResource outputFile = changeLogOutputFile.getOutputFile();
ChangeLogSerializer changeLogSerializer = changeLogOutputFile.getChangeLogSerializer();
printStream = new PrintStream(outputFile.getOutputStream(), true, encoding);
DiffResult diffResult = getDiffResult();
DiffOutputControl diffOutputControl = getDiffOutputControl();
DiffToChangeLog diffToChangeLog = new DiffToChangeLog(diffResult, diffOutputControl);
diffToChangeLog.print(printStream, changeLogSerializer);
} catch (UnsupportedEncodingException e) {
throw new BuildException("Unable to diff databases to change log file. Encoding [" + encoding + "] is not supported.", e);
} catch (IOException e) {
throw new BuildException("Unable to diff databases to change log file. Error creating output stream.", e);
} catch (ParserConfigurationException e) {
throw new BuildException("Unable to diff databases to change log file. Error configuring parser.", e);
} catch (DatabaseException e) {
throw new BuildException("Unable to diff databases to change log file: " + e.getMessage(), e);
} finally {
FileUtils.close(printStream);
}
}
| 934
| 335
| 1,269
|
<methods>public non-sealed void <init>() ,public void addReferenceDatabase(liquibase.integration.ant.type.DatabaseType) ,public void setReferenceDatabaseRef(Reference) <variables>private java.lang.String diffTypes,private liquibase.integration.ant.type.DatabaseType referenceDatabaseType
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/DropAllTask.java
|
DropAllTask
|
executeWithLiquibaseClassloader
|
class DropAllTask extends BaseLiquibaseTask {
private String schemas;
private String catalog;
@Override
public void executeWithLiquibaseClassloader() throws BuildException {<FILL_FUNCTION_BODY>}
public String getCatalog() {
return catalog;
}
public void setCatalog(String catalog) {
this.catalog = catalog;
}
public String getSchemas() {
return schemas;
}
public void setSchemas(String schemas) {
this.schemas = schemas;
}
}
|
Liquibase liquibase = getLiquibase();
try {
if (StringUtil.trimToNull(schemas) != null) {
List<String> schemaNames = StringUtil.splitAndTrim(this.schemas, ",");
List<CatalogAndSchema> schemas = new ArrayList<>();
for (String name : schemaNames) {
schemas.add(new CatalogAndSchema(catalog, name));
}
liquibase.dropAll(schemas.toArray(new CatalogAndSchema[0]));
} else {
liquibase.dropAll();
}
} catch (LiquibaseException e) {
throw new BuildException("Unable to drop all objects from database: " + e.getMessage(), e);
}
| 150
| 194
| 344
|
<methods>public void <init>() ,public void addChangeLogParameters(liquibase.integration.ant.type.ChangeLogParametersType) ,public void addDatabase(liquibase.integration.ant.type.DatabaseType) ,public Path createClasspath() ,public final void execute() throws BuildException,public java.lang.String getChangeLogDirectory() ,public java.lang.String getSearchPath() ,public void init() throws BuildException,public boolean isPromptOnNonLocalDatabase() ,public void setChangeLogParametersRef(Reference) ,public void setClasspathRef(Reference) ,public void setDatabaseRef(Reference) ,public void setPromptOnNonLocalDatabase(boolean) <variables>private liquibase.integration.ant.type.ChangeLogParametersType changeLogParameters,private AntClassLoader classLoader,private Path classpath,private static final java.util.ResourceBundle coreBundle,private liquibase.integration.ant.type.DatabaseType databaseType,private liquibase.Liquibase liquibase,private liquibase.resource.ResourceAccessor resourceAccessor,private final Map<java.lang.String,java.lang.Object> scopeValues
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/GenerateChangeLogTask.java
|
GenerateChangeLogTask
|
executeWithLiquibaseClassloader
|
class GenerateChangeLogTask extends BaseLiquibaseTask {
private final Set<ChangeLogOutputFile> changeLogOutputFiles = new LinkedHashSet<>();
private boolean includeSchema = true;
private boolean includeCatalog = true;
private boolean includeTablespace = true;
private String includeObjects;
private String excludeObjects;
@Override
public void executeWithLiquibaseClassloader() throws BuildException {<FILL_FUNCTION_BODY>}
@Override
protected void validateParameters() {
super.validateParameters();
if(changeLogOutputFiles.isEmpty()) {
throw new BuildException("Unable to generate a change log. No output file defined. Add at least one <xml>, <json>, <yaml>, or <txt> nested element.");
}
}
private String getOutputEncoding(ChangeLogOutputFile changeLogOutputFile) {
String encoding = changeLogOutputFile.getEncoding();
return (encoding == null) ? getDefaultOutputEncoding() : encoding;
}
private CatalogAndSchema buildCatalogAndSchema(Database database) {
return new CatalogAndSchema(database.getDefaultCatalogName(), database.getDefaultSchemaName());
}
private DiffOutputControl getDiffOutputControl() {
DiffOutputControl diffOutputControl = new DiffOutputControl(includeCatalog, includeSchema, includeTablespace, null);
if ((excludeObjects != null) && (includeObjects != null)) {
throw new UnexpectedLiquibaseException("Cannot specify both excludeObjects and includeObjects");
}
if (excludeObjects != null) {
diffOutputControl.setObjectChangeFilter(new StandardObjectChangeFilter(StandardObjectChangeFilter.FilterType.EXCLUDE, excludeObjects));
}
if (includeObjects != null) {
diffOutputControl.setObjectChangeFilter(new StandardObjectChangeFilter(StandardObjectChangeFilter.FilterType.INCLUDE, includeObjects));
}
return diffOutputControl;
}
public void addConfiguredJson(ChangeLogOutputFile changeLogOutputFile) {
changeLogOutputFile.setChangeLogSerializer(new JsonChangeLogSerializer());
changeLogOutputFiles.add(changeLogOutputFile);
}
public void addConfiguredXml(ChangeLogOutputFile changeLogOutputFile) {
changeLogOutputFile.setChangeLogSerializer(ChangeLogSerializerFactory.getInstance().getSerializer("xml"));
changeLogOutputFiles.add(changeLogOutputFile);
}
public void addConfiguredYaml(ChangeLogOutputFile changeLogOutputFile) {
changeLogOutputFile.setChangeLogSerializer(ChangeLogSerializerFactory.getInstance().getSerializer("yaml"));
changeLogOutputFiles.add(changeLogOutputFile);
}
public void addConfiguredTxt(ChangeLogOutputFile changeLogOutputFile) {
changeLogOutputFile.setChangeLogSerializer(new StringChangeLogSerializer());
changeLogOutputFiles.add(changeLogOutputFile);
}
public boolean getIncludeCatalog() {
return includeCatalog;
}
public void setIncludeCatalog(boolean includeCatalog) {
this.includeCatalog = includeCatalog;
}
public boolean getIncludeSchema() {
return includeSchema;
}
public void setIncludeSchema(boolean includeSchema) {
this.includeSchema = includeSchema;
}
public boolean getIncludeTablespace() {
return includeTablespace;
}
public void setIncludeTablespace(boolean includeTablespace) {
this.includeTablespace = includeTablespace;
}
public String getIncludeObjects() {
return includeObjects;
}
public void setIncludeObjects(String includeObjects) {
this.includeObjects = includeObjects;
}
public String getExcludeObjects() {
return excludeObjects;
}
public void setExcludeObjects(String excludeObjects) {
this.excludeObjects = excludeObjects;
}
}
|
Liquibase liquibase = getLiquibase();
Database database = liquibase.getDatabase();
CatalogAndSchema catalogAndSchema = buildCatalogAndSchema(database);
DiffOutputControl diffOutputControl = getDiffOutputControl();
DiffToChangeLog diffToChangeLog = new DiffToChangeLog(diffOutputControl);
for(ChangeLogOutputFile changeLogOutputFile : changeLogOutputFiles) {
String encoding = getOutputEncoding(changeLogOutputFile);
PrintStream printStream = null;
try {
FileResource outputFile = changeLogOutputFile.getOutputFile();
ChangeLogSerializer changeLogSerializer = changeLogOutputFile.getChangeLogSerializer();
log("Writing change log file " + outputFile.toString(), Project.MSG_INFO);
printStream = new PrintStream(outputFile.getOutputStream(), true, encoding);
liquibase.generateChangeLog(catalogAndSchema, diffToChangeLog, printStream, changeLogSerializer);
} catch (UnsupportedEncodingException e) {
throw new BuildException("Unable to generate a change log. Encoding [" + encoding + "] is not supported.", e);
} catch (IOException e) {
throw new BuildException("Unable to generate a change log. Error creating output stream.", e);
} catch (DatabaseException e) {
throw new BuildException("Unable to generate a change log: " + e.getMessage(), e);
} catch (CommandExecutionException e) {
throw new BuildException("Unable to generate a change log, command not found: " + e.getMessage(), e);
} finally {
FileUtils.close(printStream);
}
}
| 987
| 399
| 1,386
|
<methods>public void <init>() ,public void addChangeLogParameters(liquibase.integration.ant.type.ChangeLogParametersType) ,public void addDatabase(liquibase.integration.ant.type.DatabaseType) ,public Path createClasspath() ,public final void execute() throws BuildException,public java.lang.String getChangeLogDirectory() ,public java.lang.String getSearchPath() ,public void init() throws BuildException,public boolean isPromptOnNonLocalDatabase() ,public void setChangeLogParametersRef(Reference) ,public void setClasspathRef(Reference) ,public void setDatabaseRef(Reference) ,public void setPromptOnNonLocalDatabase(boolean) <variables>private liquibase.integration.ant.type.ChangeLogParametersType changeLogParameters,private AntClassLoader classLoader,private Path classpath,private static final java.util.ResourceBundle coreBundle,private liquibase.integration.ant.type.DatabaseType databaseType,private liquibase.Liquibase liquibase,private liquibase.resource.ResourceAccessor resourceAccessor,private final Map<java.lang.String,java.lang.Object> scopeValues
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/MarkNextChangeSetRanTask.java
|
MarkNextChangeSetRanTask
|
executeWithLiquibaseClassloader
|
class MarkNextChangeSetRanTask extends AbstractChangeLogBasedTask {
@Override
public void executeWithLiquibaseClassloader() throws BuildException {<FILL_FUNCTION_BODY>}
}
|
Liquibase liquibase = getLiquibase();
Writer writer = null;
try {
FileResource outputFile = getOutputFile();
if (outputFile != null) {
writer = getOutputFileWriter();
liquibase.markNextChangeSetRan(new Contexts(getContexts()), getLabelFilter(), writer);
} else {
liquibase.markNextChangeSetRan(new Contexts(getContexts()), getLabelFilter());
}
} catch (LiquibaseException e) {
throw new BuildException("Unable to mark next changeset as ran: " + e.getMessage(), e);
} catch (IOException e) {
throw new BuildException("Unable to mark next changeset as ran. Error creating output writer.", e);
} finally {
FileUtils.close(writer);
}
| 51
| 210
| 261
|
<methods>public non-sealed void <init>() ,public java.lang.String getChangeLogDirectory() ,public java.lang.String getChangeLogFile() ,public liquibase.LabelExpression getLabels() ,public java.lang.String getOutputEncoding() ,public java.lang.String getSearchPath() ,public void setLabelFilter(java.lang.String) ,public void setLabels(java.lang.String) <variables>private java.lang.String changeLogDirectory,private java.lang.String changeLogFile,private java.lang.String contexts,private liquibase.LabelExpression labelFilter,private java.lang.String outputEncoding,private FileResource outputFile,private java.lang.String searchPath
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/TagDatabaseTask.java
|
TagDatabaseTask
|
executeWithLiquibaseClassloader
|
class TagDatabaseTask extends BaseLiquibaseTask {
private String tag;
@Override
public void executeWithLiquibaseClassloader() throws BuildException {<FILL_FUNCTION_BODY>}
@Override
protected void validateParameters() {
super.validateParameters();
if(StringUtil.trimToNull(tag) == null) {
throw new BuildException("Unable to tag database. The tag attribute is required.");
}
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
}
|
Liquibase liquibase = getLiquibase();
try {
liquibase.tag(tag);
} catch (LiquibaseException e) {
throw new BuildException("Unable to tag database: " + e.getMessage(), e);
}
| 158
| 70
| 228
|
<methods>public void <init>() ,public void addChangeLogParameters(liquibase.integration.ant.type.ChangeLogParametersType) ,public void addDatabase(liquibase.integration.ant.type.DatabaseType) ,public Path createClasspath() ,public final void execute() throws BuildException,public java.lang.String getChangeLogDirectory() ,public java.lang.String getSearchPath() ,public void init() throws BuildException,public boolean isPromptOnNonLocalDatabase() ,public void setChangeLogParametersRef(Reference) ,public void setClasspathRef(Reference) ,public void setDatabaseRef(Reference) ,public void setPromptOnNonLocalDatabase(boolean) <variables>private liquibase.integration.ant.type.ChangeLogParametersType changeLogParameters,private AntClassLoader classLoader,private Path classpath,private static final java.util.ResourceBundle coreBundle,private liquibase.integration.ant.type.DatabaseType databaseType,private liquibase.Liquibase liquibase,private liquibase.resource.ResourceAccessor resourceAccessor,private final Map<java.lang.String,java.lang.Object> scopeValues
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/type/ChangeLogParametersType.java
|
ChangeLogParametersType
|
applyParameters
|
class ChangeLogParametersType extends DataType {
private final List<PropertySet> propertySets;
private final List<Property> parameters;
public ChangeLogParametersType(Project project) {
setProject(project);
propertySets = new LinkedList<>();
parameters = new LinkedList<>();
}
public void applyParameters(Liquibase liquibase) {<FILL_FUNCTION_BODY>}
@Override
public void setRefid(Reference ref) {
if(!propertySets.isEmpty() || !parameters.isEmpty()) {
throw tooManyAttributes();
}
super.setRefid(ref);
}
public List<PropertySet> getPropertySets() {
return isReference() ? ((ChangeLogParametersType) getCheckedRef()).getPropertySets() : propertySets;
}
public void addConfigured(PropertySet propertySet) {
propertySets.add(propertySet);
}
public List<Property> getChangeLogParameters() {
return isReference() ? ((ChangeLogParametersType) getCheckedRef()).getChangeLogParameters() : parameters;
}
public void addConfiguredChangeLogParameter(Property parameter) {
parameters.add(parameter);
}
}
|
for(Property parameter : getChangeLogParameters()) {
liquibase.setChangeLogParameter(parameter.getName(), parameter.getValue());
}
for(PropertySet propertySet : getPropertySets()) {
Properties properties = propertySet.getProperties();
for(Map.Entry<Object, Object> entry : properties.entrySet()) {
liquibase.setChangeLogParameter((String) entry.getKey(), entry.getValue());
}
}
| 311
| 113
| 424
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/ant/type/ConnectionProperties.java
|
ConnectionProperties
|
buildProperties
|
class ConnectionProperties {
private final List<PropertySet> propertySets;
private final List<Property> properties;
public ConnectionProperties() {
propertySets = new LinkedList<>();
properties = new LinkedList<>();
}
public Properties buildProperties() {<FILL_FUNCTION_BODY>}
public void add(PropertySet propertySet) {
propertySets.add(propertySet);
}
public void addConnectionProperty(Property property) {
properties.add(property);
}
}
|
Properties retProps = new Properties();
for(PropertySet propertySet : propertySets) {
retProps.putAll(propertySet.getProperties());
}
for(Property property : properties) {
retProps.setProperty(property.getName(), property.getValue());
}
return retProps;
| 133
| 79
| 212
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/commandline/Banner.java
|
Banner
|
toString
|
class Banner {
private String version;
private String build;
private String built;
private String path;
private String licensee;
private String licenseEndDate;
public Banner() {
version = LiquibaseUtil.getBuildVersionInfo();
built = LiquibaseUtil.getBuildTime();
build = LiquibaseUtil.getBuildNumber();
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
private static String readFromInputStream(InputStream inputStream) throws IOException {
StringBuilder resultStringBuilder = new StringBuilder();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
resultStringBuilder.append(line + "\n");
}
}
return resultStringBuilder.toString();
}
}
|
StringBuilder banner = new StringBuilder();
if (GlobalConfiguration.SHOW_BANNER.getCurrentValue()) {
// Banner is stored in liquibase/banner.txt in resources.
Class<CommandLineUtils> commandLinUtilsClass = CommandLineUtils.class;
InputStream inputStream = commandLinUtilsClass.getResourceAsStream("/liquibase/banner.txt");
try {
banner.append(readFromInputStream(inputStream));
} catch (IOException e) {
Scope.getCurrentScope().getLog(commandLinUtilsClass).fine("Unable to locate banner file.");
}
}
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Calendar calendar = Calendar.getInstance();
ResourceBundle coreBundle = getBundle("liquibase/i18n/liquibase-core");
banner.append(String.format(
coreBundle.getString("starting.liquibase.at.timestamp"), dateFormat.format(calendar.getTime())
));
if (StringUtil.isNotEmpty(version) && StringUtil.isNotEmpty(built)) {
version = version + " #" + build;
banner.append(String.format(coreBundle.getString("liquibase.version.builddate"), version, built));
}
return banner.toString();
| 235
| 339
| 574
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/commandline/ChangeExecListenerUtils.java
|
ChangeExecListenerUtils
|
getChangeExecListener
|
class ChangeExecListenerUtils {
private ChangeExecListenerUtils() {
}
public static ChangeExecListener getChangeExecListener(
Database database, ResourceAccessor resourceAccessor,
String changeExecListenerClass, String changeExecListenerPropertiesFile) throws Exception {<FILL_FUNCTION_BODY>}
private static Constructor<?> getConstructor(Class<?> clazz, Class<?> ... params) {
try {
return clazz.getConstructor(params);
} catch (Exception e) {
return null;
}
}
private static Properties loadProperties(final String propertiesFile) throws IOException {
if (propertiesFile != null) {
final File file = new File(propertiesFile);
if (file.exists()) {
final Properties properties = new Properties();
try (InputStream inputStream = Files.newInputStream(file.toPath())) {
properties.load(inputStream);
}
return properties;
} else {
throw new FileNotFoundException(propertiesFile);
}
} else {
return null;
}
}
}
|
ChangeExecListener changeExecListener = null;
if (changeExecListenerClass != null) {
Logger logger = Scope.getCurrentScope().getLog(ChangeExecListenerUtils.class);
logger.fine("Setting ChangeExecListener: " + changeExecListenerClass);
ClassLoader classLoader = Scope.getCurrentScope().getClassLoader();
Class<?> clazz = Class.forName(changeExecListenerClass, true, classLoader);
Properties properties = loadProperties(changeExecListenerPropertiesFile);
Constructor<?> cons = getConstructor(clazz, Database.class, Properties.class);
if (cons != null) {
logger.fine("Create " + clazz.getSimpleName() + "(Database, Properties)");
changeExecListener = (ChangeExecListener) cons.newInstance(database, properties);
} else {
cons = getConstructor(clazz, Properties.class, Database.class);
if (cons != null) {
logger.fine("Create " + clazz.getSimpleName() + "(Properties, Database)");
changeExecListener = (ChangeExecListener) cons.newInstance(properties, database);
} else {
cons = getConstructor(clazz, Database.class);
if (cons != null) {
logger.fine("Create " + clazz.getSimpleName() + "(Database)");
changeExecListener = (ChangeExecListener) cons.newInstance(database);
} else {
cons = getConstructor(clazz, Properties.class);
if (cons != null) {
logger.fine("Create " + clazz.getSimpleName() + "(Properties)");
changeExecListener = (ChangeExecListener) cons.newInstance(properties);
} else {
logger.fine("Create " + clazz.getSimpleName() + "()");
changeExecListener = (ChangeExecListener) clazz.getConstructor().newInstance();
}
}
}
}
}
return changeExecListener;
| 268
| 494
| 762
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/servlet/GenericStatusServlet.java
|
GenericStatusServlet
|
doGet
|
class GenericStatusServlet {
private static final long serialVersionUID = 1092565349351848089L;
private static final List<LogRecord> liquibaseRunLog = new ArrayList<>();
public static synchronized void logMessage(LogRecord message) {
liquibaseRunLog.add(message);
}
protected void doGet(GenericServletWrapper.HttpServletRequest httpServletRequest, GenericServletWrapper.HttpServletResponse httpServletResponse) {<FILL_FUNCTION_BODY>}
private String getLevelLink(Level level, Level currentLevel, GenericServletWrapper.HttpServletRequest request) {
if (currentLevel.equals(level)) {
return level.getName();
} else {
return "<a href=" + request.getRequestURI() + "?logLevel=" + level.getName() + ">" + level.getName() + "</a>";
}
}
}
|
httpServletResponse.setContentType("text/html");
try {
PrintWriter writer = httpServletResponse.getWriter();
String logLevelToDisplay = httpServletRequest.getParameter("logLevel");
Level currentLevel = Level.INFO;
if (logLevelToDisplay != null) {
try {
currentLevel = Level.parse(logLevelToDisplay);
} catch (IllegalArgumentException illegalArgumentException) {
throw new IOException(illegalArgumentException);
}
}
writer.println("<html>");
writer.println("<head><title>Liquibase Status</title></head>");
writer.println("<body>");
if (liquibaseRunLog.isEmpty()) {
writer.println("<b>Liquibase did not run</b>");
} else {
writer.println("<b>View level: " + getLevelLink(Level.SEVERE, currentLevel, httpServletRequest)
+ " " + getLevelLink(Level.WARNING, currentLevel, httpServletRequest)
+ " " + getLevelLink(Level.INFO, currentLevel, httpServletRequest)
+ " " + getLevelLink(Level.CONFIG, currentLevel, httpServletRequest)
+ " " + getLevelLink(Level.FINE, currentLevel, httpServletRequest)
+ " " + getLevelLink(Level.FINER, currentLevel, httpServletRequest)
+ " " + getLevelLink(Level.FINEST, currentLevel, httpServletRequest)
+ "</b>");
writer.println("<hr>");
writer.println("<b>Liquibase started at " + DateFormat.getDateTimeInstance().format(new Date
(liquibaseRunLog.get(0).getMillis())));
writer.println("<hr>");
writer.println("<pre>");
for (LogRecord record : liquibaseRunLog) {
if (record.getLevel().intValue() >= currentLevel.intValue()) {
writer.println(record.getLevel() + ": " + record.getMessage());
if (record.getThrown() != null) {
record.getThrown().printStackTrace(writer);
}
}
}
writer.println("");
writer.println("");
writer.println("</pre>");
writer.println("<hr>");
writer.println("<b>Liquibase finished at " + DateFormat.getDateTimeInstance().format(new Date
(liquibaseRunLog.get(liquibaseRunLog.size() - 1).getMillis())));
}
writer.println("</body>");
writer.println("</html>");
} catch (Exception e) {
Scope.getCurrentScope().getLog(getClass()).severe("Error in doGet: "+e.getMessage(), e);
httpServletResponse.setStatus(500);
}
| 237
| 726
| 963
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/servlet/ServletConfigurationValueProvider.java
|
ServletConfigurationValueProvider
|
getProvidedValue
|
class ServletConfigurationValueProvider extends AbstractConfigurationValueProvider {
private static final String JAVA_COMP_ENV = "java:comp/env";
@Override
public int getPrecedence() {
return 30;
}
private final GenericServletWrapper.ServletContext servletContext;
private final InitialContext initialContext;
public ServletConfigurationValueProvider(GenericServletWrapper.ServletContext servletContext, InitialContext initialContext) {
this.servletContext = servletContext;
this.initialContext = initialContext;
}
/**
* Try to read the value that is stored by the given key from
* <ul>
* <li>JNDI</li>
* <li>the servlet context's init parameters</li>
* <li>system properties</li>
* </ul>
*/
@Override
public ProvidedValue getProvidedValue(String... keyAndAliases) {<FILL_FUNCTION_BODY>}
}
|
if (initialContext != null) {
for (String key : keyAndAliases) {
// Try to get value from JNDI
try {
Context envCtx = (Context) initialContext.lookup(JAVA_COMP_ENV);
String valueFromJndi = (String) envCtx.lookup(key);
return new ProvidedValue(keyAndAliases[0], JAVA_COMP_ENV + "/" + key, valueFromJndi, "JNDI", this);
} catch (NamingException e) {
// Ignore
}
}
}
if (servletContext != null) {
for (String key : keyAndAliases) {
// Return the value from the servlet context
String valueFromServletContext = servletContext.getInitParameter(key);
if (valueFromServletContext != null) {
return new ProvidedValue(keyAndAliases[0], key, valueFromServletContext, "Servlet context", this);
}
}
}
return null;
| 252
| 265
| 517
|
<methods>public non-sealed void <init>() ,public void validate(liquibase.command.CommandScope) throws java.lang.IllegalArgumentException<variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/spring/MultiTenantSpringLiquibase.java
|
MultiTenantSpringLiquibase
|
resolveDataSources
|
class MultiTenantSpringLiquibase implements InitializingBean, ResourceLoaderAware {
private final List<DataSource> dataSources = new ArrayList<>();
/**
* Defines the location of data sources suitable for multi-tenant environment.
*/
@Getter
@Setter
private String jndiBase;
/**
* Defines a single data source and several schemas for a multi-tenant environment.
*/
@Getter
@Setter
private DataSource dataSource;
@Getter
@Setter
private List<String> schemas;
private ResourceLoader resourceLoader;
@Getter
@Setter
private String changeLog;
@Getter
@Setter
private String contexts;
@Getter
@Setter
private String labelFilter;
@Getter
@Setter
private Map<String, String> parameters;
@Getter
@Setter
private String defaultSchema;
@Getter
@Setter
private String liquibaseSchema;
@Getter
@Setter
private String liquibaseTablespace;
@Getter
@Setter
private String databaseChangeLogTable;
@Getter
@Setter
private String databaseChangeLogLockTable;
@Getter
@Setter
private boolean dropFirst;
@Getter
@Setter
private boolean clearCheckSums;
@Getter
@Setter
private boolean shouldRun = true;
@Getter
@Setter
private File rollbackFile;
@Override
public void afterPropertiesSet() throws Exception {
Logger log = Scope.getCurrentScope().getLog(getClass());
if ((dataSource != null) || (schemas != null)) {
if ((dataSource == null) && (schemas != null)) {
throw new LiquibaseException("When schemas are defined you should also define a base dataSource");
} else if (dataSource != null) {
log.info("Schema based multitenancy enabled");
if ((schemas == null) || schemas.isEmpty()) {
log.warning("Schemas not defined, using defaultSchema only");
schemas = new ArrayList<>();
schemas.add(defaultSchema);
}
runOnAllSchemas();
}
} else {
log.info("DataSources based multitenancy enabled");
resolveDataSources();
runOnAllDataSources();
}
}
private void resolveDataSources() throws NamingException {<FILL_FUNCTION_BODY>}
private void runOnAllDataSources() throws LiquibaseException {
Logger log = Scope.getCurrentScope().getLog(getClass());
for (DataSource aDataSource : dataSources) {
log.info("Initializing Liquibase for data source " + aDataSource);
SpringLiquibase liquibase = getSpringLiquibase(aDataSource);
liquibase.afterPropertiesSet();
log.info("Liquibase ran for data source " + aDataSource);
}
}
private void runOnAllSchemas() throws LiquibaseException {
Logger log = Scope.getCurrentScope().getLog(getClass());
for (String schema : schemas) {
if ("default".equals(schema)) {
schema = null;
}
log.info("Initializing Liquibase for schema " + schema);
SpringLiquibase liquibase = getSpringLiquibase(dataSource);
liquibase.setDefaultSchema(schema);
liquibase.afterPropertiesSet();
log.info("Liquibase ran for schema " + schema);
}
}
private SpringLiquibase getSpringLiquibase(DataSource dataSource) {
SpringLiquibase liquibase = new SpringLiquibase();
liquibase.setChangeLog(changeLog);
liquibase.setChangeLogParameters(parameters);
liquibase.setContexts(contexts);
liquibase.setLabelFilter(labelFilter);
liquibase.setDropFirst(dropFirst);
liquibase.setClearCheckSums(clearCheckSums);
liquibase.setShouldRun(shouldRun);
liquibase.setRollbackFile(rollbackFile);
liquibase.setResourceLoader(resourceLoader);
liquibase.setDataSource(dataSource);
liquibase.setDefaultSchema(defaultSchema);
liquibase.setLiquibaseSchema(liquibaseSchema);
liquibase.setLiquibaseTablespace(liquibaseTablespace);
liquibase.setDatabaseChangeLogTable(databaseChangeLogTable);
liquibase.setDatabaseChangeLogLockTable(databaseChangeLogLockTable);
return liquibase;
}
/**
* @deprecated use {@link #getLabelFilter()}
*/
public String getLabels() {
return getLabelFilter();
}
/**
* @deprecated use {@link #setLabelFilter(String)}
*/
public void setLabels(String labels) {
setLabelFilter(labels);
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
}
|
Logger log = Scope.getCurrentScope().getLog(getClass());
Context context = new InitialContext();
int lastIndexOf = jndiBase.lastIndexOf("/");
String jndiRoot = jndiBase.substring(0, lastIndexOf);
String jndiParent = jndiBase.substring(lastIndexOf + 1);
Context base = (Context) context.lookup(jndiRoot);
NamingEnumeration<NameClassPair> list = base.list(jndiParent);
while (list.hasMoreElements()) {
NameClassPair entry = list.nextElement();
String name = entry.getName();
String jndiUrl;
if (entry.isRelative()) {
jndiUrl = jndiBase + "/" + name;
} else {
jndiUrl = name;
}
Object lookup = context.lookup(jndiUrl);
if (lookup instanceof DataSource) {
dataSources.add((DataSource) lookup);
log.fine("Added a data source at " + jndiUrl);
} else {
log.info("Skipping a resource " + jndiUrl + " not compatible with DataSource.");
}
}
| 1,355
| 313
| 1,668
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/spring/SpringResource.java
|
SpringResource
|
resolveSibling
|
class SpringResource extends liquibase.resource.AbstractResource {
private final Resource resource;
public SpringResource(String path, URI uri, Resource resource) {
super(path, uri);
this.resource = resource;
}
@Override
public boolean exists() {
return resource.exists();
}
@Override
public liquibase.resource.Resource resolve(String other) {
try {
Resource otherResource = this.resource.createRelative(other);
return new SpringResource(resolvePath(other), otherResource.getURI(), otherResource);
} catch (IOException e) {
throw new UnexpectedLiquibaseException(e.getMessage(), e);
}
}
@Override
public liquibase.resource.Resource resolveSibling(String other) {<FILL_FUNCTION_BODY>}
@Override
public boolean isWritable() {
return resource instanceof WritableResource && ((WritableResource) resource).isWritable();
}
@Override
public InputStream openInputStream() throws IOException {
return resource.getInputStream();
}
@Override
public OutputStream openOutputStream(OpenOptions openOptions) throws IOException {
if (!resource.exists() && !openOptions.isCreateIfNeeded()) {
throw new IOException("Resource " + getUri() + " does not exist");
}
if (openOptions != null && openOptions.isAppend() && exists()) {
throw new IOException("Spring only supports truncating the existing resources.");
}
if (resource instanceof WritableResource) {
return ((WritableResource) resource).getOutputStream();
}
throw new IOException("Read only");
}
}
|
try {
Resource otherResource = this.resource.createRelative(other);
return new SpringResource(resolveSiblingPath(other), otherResource.getURI(), otherResource);
} catch (IOException e) {
throw new UnexpectedLiquibaseException(e.getMessage(), e);
}
| 425
| 79
| 504
|
<methods>public void <init>(java.lang.String, java.net.URI) ,public boolean equals(java.lang.Object) ,public java.lang.String getPath() ,public java.net.URI getUri() ,public int hashCode() ,public boolean isWritable() ,public java.io.OutputStream openOutputStream(liquibase.resource.OpenOptions) throws java.io.IOException,public java.lang.String toString() <variables>private final non-sealed java.lang.String path,private final non-sealed java.net.URI uri
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/integration/spring/SpringResourceAccessor.java
|
SpringResourceAccessor
|
getResourcePath
|
class SpringResourceAccessor extends AbstractResourceAccessor {
private final ResourceLoader resourceLoader;
private final DefaultResourceLoader fallbackResourceLoader;
public SpringResourceAccessor(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
if (resourceLoader == null) {
this.fallbackResourceLoader = new DefaultResourceLoader(Thread.currentThread().getContextClassLoader());
} else {
this.fallbackResourceLoader = new DefaultResourceLoader(resourceLoader.getClassLoader());
}
}
@Override
public void close() throws Exception {
}
@Override
public List<liquibase.resource.Resource> getAll(String path) throws IOException {
path = finalizeSearchPath(path);
final Resource[] springResources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources(path);
List<liquibase.resource.Resource> returnList = new ArrayList<>();
for (Resource resource : springResources) {
if (resource.exists()) {
returnList.add(new SpringResource(path, resource.getURI(), resource));
}
}
if (returnList.isEmpty()) {
return null;
}
return returnList;
}
@Override
public List<liquibase.resource.Resource> search(String searchPath, boolean recursive) throws IOException {
if (recursive) {
searchPath += "/**";
} else {
searchPath += "/*";
}
searchPath = finalizeSearchPath(searchPath);
final Resource[] resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources(searchPath);
List<liquibase.resource.Resource> returnList = new ArrayList<>();
for (Resource resource : resources) {
final boolean isFile = resourceIsFile(resource);
if (isFile) {
returnList.add(new SpringResource(getResourcePath(resource), resource.getURI(), resource));
}
}
return returnList;
}
@Override
public List<String> describeLocations() {
return Collections.singletonList("Spring classpath");
}
/**
* Returns the lookup path to the given resource.
*/
protected String getResourcePath(Resource resource) {<FILL_FUNCTION_BODY>}
/**
* Returns the complete path to the resource, taking the relative path into account
*/
protected String getCompletePath(String relativeTo, String path) throws IOException {
path = path.replace("\\", "/");
String searchPath;
if (relativeTo == null) {
searchPath = path;
} else {
relativeTo = relativeTo.replace("\\", "/");
boolean relativeIsFile;
Resource rootResource = getResource(relativeTo);
relativeIsFile = resourceIsFile(rootResource);
if (relativeIsFile) {
String relativePath = relativeTo.replaceFirst("[^/]+$", "");
searchPath = relativePath + path;
} else {
searchPath = relativeTo + "/" + path;
}
}
return searchPath;
}
/**
* Looks up the given resource.
*/
protected Resource getResource(String resourcePath) {
//some ResourceLoaders (FilteredReactiveWebContextResource) lie about whether they exist or not which can confuse the rest of the code.
//check the "fallback" loader first, and if that can't find it use the "real" one.
// The fallback one should be more reasonable in it's `exists()` function
Resource defaultLoaderResource = fallbackResourceLoader.getResource(resourcePath);
if (defaultLoaderResource.exists()) {
return defaultLoaderResource;
}
return resourceLoader.getResource(resourcePath);
}
/**
* Return true if the given resource is a standard file. Return false if it is a directory.
*/
protected boolean resourceIsFile(Resource resource) throws IOException {
if (resource.exists() && resource.isFile()) {
try {
//we can know for sure
return resource.getFile().isFile();
} catch (UnsupportedOperationException e) {
//native image throws on getFile
return true;
}
} else {
//we have to guess
final String filename = resource.getFilename();
return filename != null && filename.contains(".");
}
}
/**
* Ensure the given searchPath is a valid searchPath.
* Default implementation adds "classpath:" and removes duplicated /'s and classpath:'s
*/
protected String finalizeSearchPath(String searchPath) {
if (searchPath.matches("^classpath\\*?:.*")) {
searchPath = searchPath.replace("classpath:", "").replace("classpath*:", "");
searchPath = "classpath*:/" + searchPath;
} else if (!searchPath.matches("^\\w+:.*")) {
searchPath = "classpath*:/" + searchPath;
}
searchPath = searchPath.replace("\\", "/");
searchPath = searchPath.replaceAll("//+", "/");
searchPath = StringUtils.cleanPath(searchPath);
return searchPath;
}
private String decodeUrl(Resource resource, String url) throws IOException {
try {
url = decode(resource.getURL().toExternalForm(), StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
Scope.getCurrentScope().getLog(getClass()).fine("Failed to decode path " + url + "; continuing without decoding.", e);
}
return url;
}
}
|
if (resource instanceof ContextResource) {
return ((ContextResource) resource).getPathWithinContext();
}
if (resource instanceof ClassPathResource) {
return ((ClassPathResource) resource).getPath();
}
//have to fall back to figuring out the path as best we can
try {
String url = resource.getURL().toExternalForm();
url = decodeUrl(resource, url);
if (url.contains("!")) {
return url.replaceFirst(".*!", "");
} else {
while (!getResource("classpath:" + url).exists()) {
String newUrl = url.replaceFirst("^/?.*?/", "");
if (newUrl.equals(url)) {
throw new UnexpectedLiquibaseException("Could not determine path for " + resource.getURL().toExternalForm());
}
url = newUrl;
}
return url;
}
} catch (IOException e) {
//the path gets stored in the databasechangelog table, so if it gets returned incorrectly it will cause future problems.
//so throw a breaking error now rather than wait for bigger problems down the line
throw new UnexpectedLiquibaseException("Cannot determine resource path for " + resource.getDescription());
}
| 1,413
| 319
| 1,732
|
<methods>public non-sealed void <init>() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/io/EmptyLineAndCommentSkippingInputStream.java
|
EmptyLineAndCommentSkippingInputStream
|
read
|
class EmptyLineAndCommentSkippingInputStream extends BufferedInputStream {
public static final int MAX_CHAR_SIZE_IN_BYTES = 4;
private final String commentLineStartsWith;
private final boolean commentSkipEnabled;
private int lastRead = -1;
/**
* Creates Input stream that does not read (skips) lines starting with <code>commentLineStartsWith</code>
*
* @param in original input stream
* @param commentLineStartsWith comment line pattern (if empty or null, comments will not be enabled)
*/
public EmptyLineAndCommentSkippingInputStream(InputStream in, String commentLineStartsWith) {
super(in);
this.commentLineStartsWith = commentLineStartsWith;
this.commentSkipEnabled = StringUtil.isNotEmpty(commentLineStartsWith);
}
@Override
public synchronized int read() throws IOException {
return read(this.lastRead, false);
}
private int read(final int lastRead, final boolean lookAhead) throws IOException {<FILL_FUNCTION_BODY>}
}
|
int read = super.read();
// skip comment
if (commentSkipEnabled && (read == this.commentLineStartsWith.toCharArray()[0])
&& (lastRead == '\n' || lastRead < 0)) {
while ((((read = super.read())) != '\n') && (read != '\r') && (read > 0)) {
//keep looking
}
}
if (read < 0) {
return read;
}
if (read == '\r') {
return this.read();
}
if (read == '\n') {
if (lastRead == '\n') {
return this.read();
}
}
if (read == '\n') {
if (lastRead < 0) { //don't include beginning newlines
return this.read();
} else {//don't include last newline
mark(MAX_CHAR_SIZE_IN_BYTES);
if (this.read('\n', true) < 0) {
return -1;
} else {
reset();
}
}
}
if (!lookAhead) {
this.lastRead = read;
}
return read;
| 278
| 311
| 589
|
<methods>public void <init>(java.io.InputStream) ,public void <init>(java.io.InputStream, int) ,public synchronized int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public synchronized int read() throws java.io.IOException,public synchronized int read(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public synchronized long skip(long) throws java.io.IOException<variables>private static final long BUF_OFFSET,private static int DEFAULT_BUFFER_SIZE,private static final jdk.internal.misc.Unsafe U,protected volatile byte[] buf,protected int count,protected int marklimit,protected int markpos,protected int pos
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/io/StandardOutputFileHandler.java
|
StandardOutputFileHandler
|
create
|
class StandardOutputFileHandler implements OutputFileHandler {
protected OutputStream outputStream;
@Override
public int getPriority() {
return PRIORITY_DEFAULT;
}
@Override
public void create(String outputFile, CommandScope commandScope) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void close() throws IOException {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
}
}
|
final PathHandlerFactory pathHandlerFactory = Scope.getCurrentScope().getSingleton(PathHandlerFactory.class);
outputStream = pathHandlerFactory.openResourceOutputStream(outputFile, new OpenOptions());
commandScope.setOutput(outputStream);
| 128
| 61
| 189
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/license/LicenseInfo.java
|
LicenseInfo
|
formatExpirationDate
|
class LicenseInfo {
private String issuedTo;
private Date expirationDate;
public LicenseInfo(String issuedTo, Date expirationDate) {
this.issuedTo = issuedTo;
this.expirationDate = expirationDate;
}
public String getIssuedTo() {
return issuedTo;
}
public void setIssuedTo(String issuedTo) {
this.issuedTo = issuedTo;
}
public Date getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
public String formatExpirationDate() {<FILL_FUNCTION_BODY>}
}
|
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
return dateFormat.format(expirationDate);
| 189
| 45
| 234
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/license/LicenseInstallResult.java
|
LicenseInstallResult
|
add
|
class LicenseInstallResult {
public int code;
public List<String> messages;
public LicenseInstallResult(int code) {
this.code = code;
this.messages = new ArrayList<>();
}
public LicenseInstallResult(int code, String message) {
this.code = code;
this.messages = new ArrayList<>();
messages.add(message);
}
public LicenseInstallResult(int code, List<String> results) {
this.code = code;
this.messages = new ArrayList<>();
messages.addAll(results);
}
public void add(LicenseInstallResult result) {<FILL_FUNCTION_BODY>}
}
|
if (result.code != 0) {
this.code = result.code;
}
this.messages.addAll(result.messages);
| 174
| 41
| 215
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/license/LicenseServiceUtils.java
|
LicenseServiceUtils
|
isProLicenseValid
|
class LicenseServiceUtils {
public static final String TRIAL_LICENSE_URL = "https://liquibase.com/trial";
private static final String BASE_INVALID_LICENSE_MESSAGE = "Using '%s' requires a valid Liquibase Pro or Labs license. Get a free license key at " + TRIAL_LICENSE_URL + ".";
/**
* Check for a Liquibase Pro License.
* @return true if licensed, or the installed license also permits access to Liquibase Pro features, false if not
*/
public static boolean isProLicenseValid() {<FILL_FUNCTION_BODY>}
/**
* Throw an exception if there is no valid pro license.
* @param commandNames the name of the command; each element of the array will be joined by spaces
* @throws CommandValidationException the exception thrown if the license is not valid
*/
public static void checkProLicenseAndThrowException(String[] commandNames) throws CommandValidationException {
if (!isProLicenseValid()) {
throw new CommandValidationException(String.format(BASE_INVALID_LICENSE_MESSAGE + " Add liquibase.licenseKey=<yourKey> into your defaults file or use --license-key=<yourKey> before your command in the CLI.", StringUtil.join(commandNames, " ")));
}
}
}
|
LicenseServiceFactory licenseServiceFactory = Scope.getCurrentScope().getSingleton(LicenseServiceFactory.class);
if (licenseServiceFactory == null) {
return false;
}
LicenseService licenseService = licenseServiceFactory.getLicenseService();
if (licenseService == null) {
return false;
}
return licenseService.licenseIsValid("Liquibase Pro");
| 335
| 98
| 433
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/license/Location.java
|
Location
|
toString
|
class Location {
public String name;
public String value;
public Location(String name, String value) {
this.name = name;
this.value = value;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public String getValue() {
return value;
}
}
|
int substring_length = Math.min(value.length(), 10);
return String.format("Base64 string starting with '%s' (%s)", value.substring(0, substring_length), name);
| 93
| 57
| 150
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/lockservice/LockServiceFactory.java
|
LockServiceFactory
|
getInstance
|
class LockServiceFactory {
private static LockServiceFactory instance;
private final List<LockService> registry = new ArrayList<>();
private final Map<Database, LockService> openLockServices = new ConcurrentHashMap<>();
public static synchronized LockServiceFactory getInstance() {<FILL_FUNCTION_BODY>}
/**
* Set the instance used by this singleton. Used primarily for testing.
*/
public static synchronized void setInstance(LockServiceFactory lockServiceFactory) {
LockServiceFactory.instance = lockServiceFactory;
}
public static synchronized void reset() {
instance = null;
}
private LockServiceFactory() {
try {
for (LockService lockService : Scope.getCurrentScope().getServiceLocator().findInstances(LockService.class)) {
register(lockService);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void register(LockService lockService) {
registry.add(0, lockService);
}
public LockService getLockService(Database database) {
if (!openLockServices.containsKey(database)) {
SortedSet<LockService> foundServices = new TreeSet<>((o1, o2) -> -1 * Integer.compare(o1.getPriority(), o2.getPriority()));
for (LockService lockService : registry) {
if (lockService.supports(database)) {
foundServices.add(lockService);
}
}
if (foundServices.isEmpty()) {
throw new UnexpectedLiquibaseException("Cannot find LockService for " + database.getShortName());
}
try {
LockService lockService = foundServices.iterator().next().getClass().getConstructor().newInstance();
lockService.setDatabase(database);
openLockServices.put(database, lockService);
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
}
return openLockServices.get(database);
}
public void resetAll() {
for (LockService lockService : registry) {
lockService.reset();
}
reset();
}
}
|
if (instance == null) {
instance = new LockServiceFactory();
}
return instance;
| 562
| 32
| 594
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/logging/core/BufferedLogService.java
|
BufferedLogService
|
getLogAsString
|
class BufferedLogService extends AbstractLogService {
//
// Truncate the return value at 10MB = 10,000,000 bytes
//
public static final int MAX_LOG_LENGTH = 10000000;
private final List<BufferedLogMessage> log = Collections.synchronizedList(new ArrayList<>());
@Override
public int getPriority() {
return PRIORITY_NOT_APPLICABLE;
}
@Override
public Logger getLog(Class clazz) {
return new BufferedLogger(clazz, this);
}
public String getLogAsString(Level minimumLevel) {<FILL_FUNCTION_BODY>}
public void addLog(BufferedLogMessage log) {
this.log.add(log);
}
@Getter
public static class BufferedLogMessage {
private final Date timestamp;
private final Level level;
private final Class location;
private final String message;
private final Throwable throwable;
public BufferedLogMessage(Level level, Class location, String message, Throwable throwable) {
this.timestamp = new Date();
this.location = location;
this.level = level;
this.message = message;
this.throwable = throwable;
}
}
}
|
StringBuilder returnLog = new StringBuilder();
for (BufferedLogMessage message : log) {
if (minimumLevel == null || minimumLevel.intValue() <= message.getLevel().intValue()) {
returnLog.append("[").append(new ISODateFormat().format(message.getTimestamp())).append("] ");
returnLog.append(message.getLevel().getName()).append(" ");
returnLog.append(message.getMessage());
returnLog.append("\n");
if (message.getThrowable() != null) {
try (final StringWriter stringWriter = new StringWriter();
final PrintWriter printWriter = new PrintWriter(stringWriter)) {
message.getThrowable().printStackTrace(printWriter);
printWriter.flush();
returnLog.append(stringWriter).append("\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
if (returnLog.length() > MAX_LOG_LENGTH) {
returnLog.setLength(MAX_LOG_LENGTH);
}
return returnLog.toString();
| 343
| 276
| 619
|
<methods>public non-sealed void <init>() ,public void close() ,public liquibase.logging.LogMessageFilter getFilter() ,public void setFilter(liquibase.logging.LogMessageFilter) <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/logging/core/BufferedLogger.java
|
BufferedLogger
|
log
|
class BufferedLogger extends AbstractLogger {
private final BufferedLogService bufferedLogService;
private final Class clazz;
/**
* @deprecated use {@link #BufferedLogger(Class, BufferedLogService)}
*/
public BufferedLogger(Class clazz, BufferedLogService bufferedLogService, LogMessageFilter ignored) {
this(clazz, bufferedLogService);
}
public BufferedLogger(Class clazz, BufferedLogService bufferedLogService) {
this.clazz = clazz;
this.bufferedLogService = bufferedLogService;
}
@Override
public void log(Level level, String message, Throwable e) {<FILL_FUNCTION_BODY>}
@Override
public void close() throws Exception {
}
}
|
if (level == Level.OFF) {
return;
}
this.bufferedLogService.addLog(new BufferedLogService.BufferedLogMessage(level, clazz, filterMessage(message), e));
| 204
| 57
| 261
|
<methods>public void config(java.lang.String) ,public void config(java.lang.String, java.lang.Throwable) ,public void debug(java.lang.String) ,public void debug(java.lang.String, java.lang.Throwable) ,public void fine(java.lang.String) ,public void fine(java.lang.String, java.lang.Throwable) ,public void info(java.lang.String) ,public void info(java.lang.String, java.lang.Throwable) ,public void severe(java.lang.String) ,public void severe(java.lang.String, java.lang.Throwable) ,public void warning(java.lang.String) ,public void warning(java.lang.String, java.lang.Throwable) <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/logging/core/CompositeLogService.java
|
CompositeLogService
|
getLog
|
class CompositeLogService extends AbstractLogService {
private List<LogService> services = new ArrayList<>();
public CompositeLogService() {
}
public CompositeLogService(boolean includeCurrentScopeLogService, LogService... logService) {
this.services = new ArrayList<>(Arrays.asList(logService));
if (includeCurrentScopeLogService) {
services.add(Scope.getCurrentScope().get(Scope.Attr.logService, LogService.class));
}
}
@Override
public int getPriority() {
return PRIORITY_NOT_APPLICABLE;
}
@Override
public Logger getLog(Class clazz) {<FILL_FUNCTION_BODY>}
}
|
List<Logger> loggers = new ArrayList<>();
for (LogService service : services) {
loggers.add(service.getLog(clazz));
}
return new CompositeLogger(loggers);
| 187
| 56
| 243
|
<methods>public non-sealed void <init>() ,public void close() ,public liquibase.logging.LogMessageFilter getFilter() ,public void setFilter(liquibase.logging.LogMessageFilter) <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/logging/core/CompositeLogger.java
|
CompositeLogger
|
log
|
class CompositeLogger extends AbstractLogger {
private final List<Logger> loggers;
/**
* @deprecated use {@link #CompositeLogger(List)}
*/
public CompositeLogger(List<Logger> loggers, LogMessageFilter filter) {
this(loggers);
}
public CompositeLogger(List<Logger> loggers) {
this.loggers = loggers;
}
@Override
public void close() throws Exception {
for (Logger logger : loggers) {
logger.close();
}
}
@Override
public void log(Level level, String message, Throwable e) {<FILL_FUNCTION_BODY>}
}
|
if (level == Level.OFF) {
return;
}
for (Logger logger : loggers) {
logger.log(level, message, e);
}
| 176
| 49
| 225
|
<methods>public void config(java.lang.String) ,public void config(java.lang.String, java.lang.Throwable) ,public void debug(java.lang.String) ,public void debug(java.lang.String, java.lang.Throwable) ,public void fine(java.lang.String) ,public void fine(java.lang.String, java.lang.Throwable) ,public void info(java.lang.String) ,public void info(java.lang.String, java.lang.Throwable) ,public void severe(java.lang.String) ,public void severe(java.lang.String, java.lang.Throwable) ,public void warning(java.lang.String) ,public void warning(java.lang.String, java.lang.Throwable) <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/logging/core/JavaLogService.java
|
JavaLogService
|
getLog
|
class JavaLogService extends AbstractLogService {
@Override
public int getPriority() {
return PRIORITY_DEFAULT;
}
private final Map<Class, JavaLogger> loggers = new HashMap<>();
private java.util.logging.Logger parent;
@Override
public Logger getLog(Class clazz) {<FILL_FUNCTION_BODY>}
/**
* Because java.util.logging differentiates between the log name and the class/method logging,
* we can collapses the log names to a simpler/smaller set to allow configuration to rely on the class name less.
* <br><br>
* This implementation always returns the 2nd level liquibase package name for the class passed in OR from any liquibase interfaces/classes it implements.
* For example, all {@link liquibase.change.Change} classes will return a log name of "liquibase.change" no matter what class name or package name they have.
*/
protected String getLogName(Class clazz) {
if (clazz == null) {
return "unknown";
}
if (clazz.getPackage() == null) {
return clazz.getName();
}
final String classPackageName = clazz.getPackage().getName();
if (classPackageName.equals("liquibase")) {
return "liquibase";
}
if (classPackageName.startsWith("liquibase.")) {
return classPackageName.replaceFirst("(liquibase.\\w+)\\.?.*", "$1");
}
for (Class iface : clazz.getInterfaces()) {
if (iface.equals(LiquibaseSerializable.class)) { //don't use liquibase.serializable just because it implements LiquibaseSerializable
continue;
}
final String interfaceLog = getLogName(iface);
if (!interfaceLog.equals("liquibase")) {
return interfaceLog;
}
}
final Class superclass = clazz.getSuperclass();
if (superclass != null && !superclass.equals(Object.class)) {
final String superclassLogName = getLogName(superclass);
if (!superclassLogName.equals("liquibase")) {
return superclassLogName;
}
}
return "liquibase";
}
public java.util.logging.Logger getParent() {
return parent;
}
/**
* Explicitly control the parent logger for all {@link java.util.logging.Logger} instances created.
*/
public void setParent(java.util.logging.Logger parent) {
this.parent = parent;
}
public Formatter getCustomFormatter() {
return null;
}
/**
* Set the formatter for the supplied handler if the supplied log service
* is a JavaLogService and that service specifies a custom formatter.
*/
public static void setFormatterOnHandler(LogService logService, Handler handler) {
if (logService instanceof JavaLogService && handler != null) {
Formatter customFormatter = ((JavaLogService) logService).getCustomFormatter();
if (customFormatter != null) {
handler.setFormatter(customFormatter);
}
}
}
}
|
JavaLogger logger = loggers.get(clazz);
if (logger == null) {
java.util.logging.Logger utilLogger = java.util.logging.Logger.getLogger(getLogName(clazz));
utilLogger.setUseParentHandlers(true);
if (parent != null && !parent.getName().equals(utilLogger.getName())) {
utilLogger.setParent(parent);
}
logger = new JavaLogger(utilLogger);
this.loggers.put(clazz, logger);
}
return logger;
| 835
| 139
| 974
|
<methods>public non-sealed void <init>() ,public void close() ,public liquibase.logging.LogMessageFilter getFilter() ,public void setFilter(liquibase.logging.LogMessageFilter) <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/logging/core/JavaLogger.java
|
JavaLogger
|
log
|
class JavaLogger extends AbstractLogger {
private final String className;
private final java.util.logging.Logger logger;
/**
* @deprecated use {@link #JavaLogger(java.util.logging.Logger)}
*/
@Deprecated
public JavaLogger(java.util.logging.Logger logger, LogMessageFilter filter) {
this(logger);
}
public JavaLogger(java.util.logging.Logger logger) {
this.logger = logger;
this.className = logger.getName();
}
@Override
public void log(Level level, String message, Throwable e) {<FILL_FUNCTION_BODY>}
}
|
if (level.equals(Level.OFF)) {
return;
}
if (!logger.isLoggable(level)) {
return;
}
logger.logp(level, className, null, message, e);
| 166
| 62
| 228
|
<methods>public void config(java.lang.String) ,public void config(java.lang.String, java.lang.Throwable) ,public void debug(java.lang.String) ,public void debug(java.lang.String, java.lang.Throwable) ,public void fine(java.lang.String) ,public void fine(java.lang.String, java.lang.Throwable) ,public void info(java.lang.String) ,public void info(java.lang.String, java.lang.Throwable) ,public void severe(java.lang.String) ,public void severe(java.lang.String, java.lang.Throwable) ,public void warning(java.lang.String) ,public void warning(java.lang.String, java.lang.Throwable) <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/logging/mdc/customobjects/ChangesetsRolledback.java
|
ChangesetsRolledback
|
fromChangesetList
|
class ChangesetsRolledback implements CustomMdcObject {
private int changesetCount;
private List<ChangeSet> changesets;
/**
* Constructor for service locator.
*/
public ChangesetsRolledback() {
}
public ChangesetsRolledback(List<ChangeSet> changeSets) {
changesetCount = changeSets.size();
this.changesets = changeSets;
}
/**
* Generate a {@link ChangesetsRolledback} object from a list of {@link liquibase.changelog.ChangeSet}s.
*/
public static ChangesetsRolledback fromChangesetList(List<liquibase.changelog.ChangeSet> changeSets) {<FILL_FUNCTION_BODY>}
@Getter
@Setter
public static class ChangeSet {
private String changesetId;
private String author;
private String filepath;
private String deploymentId;
public ChangeSet(String changesetId, String author, String filepath, String deploymentId) {
this.changesetId = changesetId;
this.author = author;
this.filepath = filepath;
this.deploymentId = deploymentId;
}
public static ChangeSet fromChangeSet(liquibase.changelog.ChangeSet changeSet) {
return new ChangeSet(changeSet.getId(), changeSet.getAuthor(), changeSet.getFilePath(), changeSet.getDeploymentId());
}
}
}
|
if (changeSets != null) {
List<ChangeSet> changesets = changeSets.stream().map(ChangeSet::fromChangeSet).collect(Collectors.toList());
return new ChangesetsRolledback(changesets);
} else {
return new ChangesetsRolledback(Collections.emptyList());
}
| 391
| 88
| 479
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/logging/mdc/customobjects/ExceptionDetails.java
|
ExceptionDetails
|
getFormattedPrimaryExceptionReason
|
class ExceptionDetails implements CustomMdcObject {
private String primaryException;
private String primaryExceptionReason;
private String primaryExceptionSource;
private String exception;
public ExceptionDetails() {
}
public ExceptionDetails(Throwable exception, String source) {
//
// Drill down to get the lowest level exception
//
Throwable primaryException = exception;
while (primaryException != null && primaryException.getCause() != null) {
primaryException = primaryException.getCause();
}
if (primaryException != null) {
if (primaryException instanceof LiquibaseException || source == null) {
source = LiquibaseUtil.getBuildVersionInfo();
}
this.primaryException = primaryException.getClass().getSimpleName();
this.primaryExceptionReason = primaryException.getMessage();
this.primaryExceptionSource = source;
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
exception.printStackTrace(printWriter);
this.exception = stringWriter.toString();
}
}
public String getFormattedPrimaryException() {
return getPrimaryException() != null
? String.format("ERROR: Exception Primary Class: %s", getPrimaryException())
: "";
}
public String getFormattedPrimaryExceptionReason() {<FILL_FUNCTION_BODY>}
public String getFormattedPrimaryExceptionSource() {
return getPrimaryExceptionSource() != null
? String.format("ERROR: Exception Primary Source: %s", getPrimaryExceptionSource())
: "";
}
public static String findSource(Database database) {
try {
String source;
try {
source = String.format("%s %s", database.getDatabaseProductName(), database.getDatabaseProductVersion());
} catch (DatabaseException dbe) {
source = database.getDatabaseProductName();
}
return source;
} catch (RuntimeException ignored) {
// For some reason we decided to have AbstractJdbcDatabase#getDatabaseProductName throw a runtime exception.
// In this case since we always want to fall back to some sort of identifier for the database
// we can just ignore and return the display name.
return database.getDisplayName();
}
}
}
|
return getPrimaryExceptionReason() != null
? String.format("ERROR: Exception Primary Reason: %s", getPrimaryExceptionReason())
: "";
| 565
| 41
| 606
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/osgi/Activator.java
|
Activator
|
addingBundle
|
class Activator implements BundleActivator, BundleTrackerCustomizer<LiquibaseBundle> {
private static final String LIQUIBASE_CUSTOM_CHANGE_WRAPPER_PACKAGES = "Liquibase-Custom-Change-Packages";
private BundleTracker<LiquibaseBundle> bundleTracker;
private static final List<LiquibaseBundle> liquibaseBundles = new CopyOnWriteArrayList<>();
@Override
public void start(final BundleContext bc) throws Exception {
ContainerChecker.osgiPlatform();
bundleTracker = new BundleTracker<>(bc, Bundle.ACTIVE, this);
bundleTracker.open();
}
@Override
public void stop(BundleContext context) throws Exception {
bundleTracker.close();
liquibaseBundles.clear();
}
public static List<LiquibaseBundle> getLiquibaseBundles() {
return Collections.unmodifiableList(liquibaseBundles);
}
@Override
public LiquibaseBundle addingBundle(Bundle bundle, BundleEvent event) {<FILL_FUNCTION_BODY>}
@Override
public void modifiedBundle(Bundle bundle, BundleEvent event, LiquibaseBundle liquibaseBundle) {
// nothing to do
}
@Override
public void removedBundle(Bundle bundle, BundleEvent event, LiquibaseBundle liquibaseBundle) {
if (liquibaseBundle != null) {
liquibaseBundles.remove(liquibaseBundle);
}
}
@Getter
public static class LiquibaseBundle {
private final Bundle bundle;
private final List<String> allowedPackages;
public LiquibaseBundle(Bundle bundle, String allowedPackages) {
if (bundle == null) {
throw new IllegalArgumentException("bundle cannot be empty");
}
if (allowedPackages == null || allowedPackages.isEmpty()) {
throw new IllegalArgumentException("packages cannot be empty");
}
this.bundle = bundle;
this.allowedPackages = Collections.unmodifiableList(Arrays.asList(allowedPackages.split(",")));
}
public boolean allowedAllPackages() {
return allowedPackages.size() == 1
&& "*".equals(allowedPackages.get(0));
}
}
/**
* @deprecated use {@link ContainerChecker}
*/
@Deprecated
public static class OSGIContainerChecker extends ContainerChecker {
}
}
|
if (bundle.getBundleId() == 0) {
return null;
}
String customWrapperPackages = bundle.getHeaders().get(LIQUIBASE_CUSTOM_CHANGE_WRAPPER_PACKAGES);
if (customWrapperPackages != null) {
LiquibaseBundle lb = new LiquibaseBundle(bundle, customWrapperPackages);
liquibaseBundles.add(lb);
return lb;
}
return null;
| 653
| 124
| 777
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/parser/ChangeLogParserFactory.java
|
ChangeLogParserFactory
|
getParser
|
class ChangeLogParserFactory {
private static ChangeLogParserFactory instance;
private final List<ChangeLogParser> parsers = new ArrayList<>();
public static synchronized void reset() {
instance = new ChangeLogParserFactory();
}
public static synchronized ChangeLogParserFactory getInstance() {
if (instance == null) {
instance = new ChangeLogParserFactory();
}
return instance;
}
/**
* Set the instance used by this singleton. Used primarily for testing.
*/
public static synchronized void setInstance(ChangeLogParserFactory instance) {
ChangeLogParserFactory.instance = instance;
}
private ChangeLogParserFactory() {
try {
List<ChangeLogParser> parser = Scope.getCurrentScope().getServiceLocator().findInstances(ChangeLogParser.class);
register(parser);
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
}
public List<ChangeLogParser> getParsers() {
return new ArrayList<>(parsers);
}
public ChangeLogParser getParser(String fileNameOrExtension, ResourceAccessor resourceAccessor) throws LiquibaseException {<FILL_FUNCTION_BODY>}
public void register(ChangeLogParser changeLogParsers) {
register(Collections.singletonList(changeLogParsers));
}
private void register(List<ChangeLogParser> changeLogParsers) {
parsers.addAll(changeLogParsers);
parsers.sort(ChangeLogParser.COMPARATOR);
}
public void unregister(ChangeLogParser changeLogParser) {
parsers.remove(changeLogParser);
}
public void unregisterAllParsers() {
parsers.clear();
}
}
|
for (ChangeLogParser parser : parsers) {
if (parser.supports(fileNameOrExtension, resourceAccessor)) {
Scope.getCurrentScope().getLog(ChangeLogParserFactory.class).fine(String.format("Matched file '%s' to parser '%s'",
fileNameOrExtension, parser.getClass().getSimpleName()));
return parser;
}
}
throw new UnknownChangelogFormatException("Cannot find parser that supports " + fileNameOrExtension);
| 462
| 125
| 587
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/parser/NamespaceDetailsFactory.java
|
NamespaceDetailsFactory
|
getNamespaceDetails
|
class NamespaceDetailsFactory {
private static NamespaceDetailsFactory instance;
private final List<NamespaceDetails> namespaceDetails = new ArrayList<>();
public static synchronized void reset() {
instance = null;
}
public static synchronized NamespaceDetailsFactory getInstance() {
if (instance == null) {
instance = new NamespaceDetailsFactory();
}
return instance;
}
private NamespaceDetailsFactory() {
try {
for (NamespaceDetails details : Scope.getCurrentScope().getServiceLocator().findInstances(NamespaceDetails.class)) {
register(details);
}
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
}
public Collection<NamespaceDetails> getNamespaceDetails() {
return Collections.unmodifiableCollection(namespaceDetails);
}
public NamespaceDetails getNamespaceDetails(LiquibaseParser parser, String namespace) {<FILL_FUNCTION_BODY>}
public NamespaceDetails getNamespaceDetails(LiquibaseSerializer serializer, String namespace) {
SortedSet<NamespaceDetails> validNamespaceDetails = new TreeSet<>(new SerializerNamespaceDetailsComparator());
for (NamespaceDetails details : namespaceDetails) {
if (details.supports(serializer, namespace)) {
validNamespaceDetails.add(details);
}
}
if (validNamespaceDetails.isEmpty()) {
Scope.getCurrentScope().getLog(getClass()).fine("No serializer namespace details associated with namespace '" + namespace + "' and serializer " + serializer.getClass().getName());
}
return validNamespaceDetails.iterator().next();
}
public void register(NamespaceDetails namespaceDetails) {
this.namespaceDetails.add(namespaceDetails);
}
public void unregister(NamespaceDetails namespaceDetails) {
this.namespaceDetails.remove(namespaceDetails);
}
private class SerializerNamespaceDetailsComparator implements Comparator<NamespaceDetails> {
@Override
public int compare(NamespaceDetails o1, NamespaceDetails o2) {
return Integer.compare(o2.getPriority(), o1.getPriority());
}
}
}
|
SortedSet<NamespaceDetails> validNamespaceDetails = new TreeSet<>(new SerializerNamespaceDetailsComparator());
for (NamespaceDetails details : namespaceDetails) {
if (details.supports(parser, namespace)) {
validNamespaceDetails.add(details);
}
}
if (validNamespaceDetails.isEmpty()) {
Scope.getCurrentScope().getLog(getClass()).fine("No parser namespace details associated with namespace '" + namespace + "' and parser " + parser.getClass().getName());
}
return validNamespaceDetails.iterator().next();
| 545
| 141
| 686
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/parser/SnapshotParserFactory.java
|
SnapshotParserFactory
|
getParser
|
class SnapshotParserFactory {
private static SnapshotParserFactory instance;
private final List<SnapshotParser> parsers;
private final Comparator<SnapshotParser> snapshotParserComparator;
public static synchronized void reset() {
instance = new SnapshotParserFactory();
}
public static synchronized SnapshotParserFactory getInstance() {
if (instance == null) {
instance = new SnapshotParserFactory();
}
return instance;
}
/**
* Set the instance used by this singleton. Used primarily for testing.
*/
public static synchronized void setInstance(SnapshotParserFactory instance) {
SnapshotParserFactory.instance = instance;
}
private SnapshotParserFactory() {
snapshotParserComparator = (o1, o2) -> Integer.compare(o2.getPriority(), o1.getPriority());
parsers = new ArrayList<>();
try {
for (SnapshotParser parser : Scope.getCurrentScope().getServiceLocator().findInstances(SnapshotParser.class)) {
register(parser);
}
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
}
public List<SnapshotParser> getParsers() {
return parsers;
}
public SnapshotParser getParser(String fileNameOrExtension, ResourceAccessor resourceAccessor) throws LiquibaseException {<FILL_FUNCTION_BODY>}
public void register(SnapshotParser snapshotParser) {
parsers.add(snapshotParser);
parsers.sort(snapshotParserComparator);
}
public void unregister(SnapshotParser snapshotParser) {
parsers.remove(snapshotParser);
}
}
|
for (SnapshotParser parser : parsers) {
if (parser.supports(fileNameOrExtension, resourceAccessor)) {
return parser;
}
}
throw new UnknownFormatException("Cannot find parser that supports "+fileNameOrExtension);
| 442
| 67
| 509
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/parser/core/sql/SqlChangeLogParser.java
|
SqlChangeLogParser
|
parse
|
class SqlChangeLogParser implements ChangeLogParser {
@Override
public boolean supports(String changeLogFile, ResourceAccessor resourceAccessor) {
return changeLogFile.toLowerCase().endsWith(".sql");
}
@Override
public int getPriority() {
return PRIORITY_DEFAULT;
}
@Override
public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException {<FILL_FUNCTION_BODY>}
}
|
DatabaseChangeLog changeLog = new DatabaseChangeLog();
changeLog.setPhysicalFilePath(physicalChangeLogLocation);
RawSQLChange change = new RawSQLChange();
try {
Resource sqlResource = resourceAccessor.getExisting(physicalChangeLogLocation);
String sql = StreamUtil.readStreamAsString(sqlResource.openInputStream());
//
// Handle empty files with a WARNING message
//
if (StringUtil.isEmpty(sql)) {
String message = String.format("Unable to parse empty file '%s'", physicalChangeLogLocation);
Scope.getCurrentScope().getLog(getClass()).warning(message);
throw new ChangeLogParseException(message);
}
change.setSql(sql);
} catch (IOException e) {
throw new ChangeLogParseException(e);
}
change.setSplitStatements(false);
change.setStripComments(false);
ChangeSetServiceFactory factory = ChangeSetServiceFactory.getInstance();
ChangeSetService service = factory.createChangeSetService();
ChangeSet changeSet =
service.createChangeSet("raw", "includeAll",
false, false, physicalChangeLogLocation, null,
null, null, null, true,
ObjectQuotingStrategy.LEGACY, changeLog);
changeSet.addChange(change);
changeLog.addChangeSet(changeSet);
return changeLog;
| 134
| 349
| 483
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/parser/core/xml/AbstractChangeLogParser.java
|
AbstractChangeLogParser
|
parse
|
class AbstractChangeLogParser implements ChangeLogParser {
@Override
public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters,
ResourceAccessor resourceAccessor) throws ChangeLogParseException {<FILL_FUNCTION_BODY>}
protected abstract ParsedNode parseToNode(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters,
ResourceAccessor resourceAccessor) throws ChangeLogParseException;
}
|
ParsedNode parsedNode = parseToNode(physicalChangeLogLocation, changeLogParameters, resourceAccessor);
if (parsedNode == null) {
return null;
}
DatabaseChangeLog changeLog = new DatabaseChangeLog(DatabaseChangeLog.normalizePath(physicalChangeLogLocation));
changeLog.setChangeLogParameters(changeLogParameters);
try {
changeLog.load(parsedNode, resourceAccessor);
} catch (Exception e) {
throw new ChangeLogParseException(e);
}
return changeLog;
| 108
| 138
| 246
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/parser/core/xml/LiquibaseEntityResolver.java
|
LiquibaseEntityResolver
|
resolveEntity
|
class LiquibaseEntityResolver implements EntityResolver2 {
private static final String XSD_VERSION_REGEX = "(?:-pro-|-)(?<version>[\\d.]*)\\.xsd";
private static final Pattern XSD_VERSION_PATTERN = Pattern.compile(XSD_VERSION_REGEX);
private boolean shouldWarnOnMismatchedXsdVersion = false;
/**
* The warning message should only be printed once.
*/
private static boolean hasWarnedAboutMismatchedXsdVersion = false;
@Override
@java.lang.SuppressWarnings("squid:S2095")
public InputSource resolveEntity(String name, String publicId, String baseURI, String systemId) throws SAXException, IOException {<FILL_FUNCTION_BODY>}
/**
* Return the classloader used to look for XSD files in the classpath.
*/
protected ClassLoader getSearchClassloader() {
return new CombinedClassLoader();
}
/**
* Print a warning message to the logs and UI if the build version does not match the XSD version. This is a best
* effort check, this method will never throw an exception.
*/
private void warnForMismatchedXsdVersion(String systemId) {
try {
Matcher versionMatcher = XSD_VERSION_PATTERN.matcher(systemId);
boolean found = versionMatcher.find();
if (found) {
String buildVersion = LiquibaseUtil.getBuildVersion();
if (!buildVersion.equals("DEV")) {
String xsdVersion = versionMatcher.group("version");
if (!buildVersion.startsWith(xsdVersion)) {
hasWarnedAboutMismatchedXsdVersion = true;
String msg = "INFO: An older version of the XSD is specified in one or more changelog's <databaseChangeLog> header. This can lead to unexpected outcomes. If a specific XSD is not required, please replace all XSD version references with \"-latest\". Learn more at https://docs.liquibase.com/concepts/changelogs/xml-format.html";
Scope.getCurrentScope().getLog(getClass()).info(msg);
Scope.getCurrentScope().getUI().sendMessage(msg);
}
}
}
} catch (Exception e) {
Scope.getCurrentScope().getLog(getClass()).fine("Failed to compare XSD version with build version.", e);
}
}
@Override
public InputSource getExternalSubset(String name, String baseURI) throws SAXException, IOException {
return null;
}
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
Scope.getCurrentScope().getLog(getClass()).warning("The current XML parser does not seems to not support EntityResolver2. External entities may not be correctly loaded");
return resolveEntity(null, publicId, null, systemId);
}
/**
* When set to true, a warning will be printed to the console if the XSD version used does not match the version
* of Liquibase. If "latest" is used as the XSD version, no warning is printed.
*/
public void setShouldWarnOnMismatchedXsdVersion(boolean shouldWarnOnMismatchedXsdVersion) {
this.shouldWarnOnMismatchedXsdVersion = shouldWarnOnMismatchedXsdVersion;
}
/**
* Only currently implementing getResource() since that's the only method used by our logic
*/
private static class CombinedClassLoader extends ClassLoader {
private final List<ClassLoader> classLoaders;
public CombinedClassLoader() {
this.classLoaders = Arrays.asList(Thread.currentThread().getContextClassLoader(), getClass().getClassLoader());
}
@Override
public URL getResource(String name) {
for (ClassLoader classLoader : classLoaders) {
URL resource = classLoader.getResource(name);
if (resource != null) {
return resource;
}
}
return null;
}
}
}
|
Logger log = Scope.getCurrentScope().getLog(getClass());
log.fine("Resolving XML entity name='" + name + "', publicId='" + publicId + "', baseURI='" + baseURI + "', systemId='" + systemId + "'");
if (systemId == null) {
log.fine("Cannot determine systemId for name=" + name + ", publicId=" + publicId + ". Will load from network.");
return null;
}
String path = systemId.toLowerCase()
.replace("http://www.liquibase.org/xml/ns/migrator/", "http://www.liquibase.org/xml/ns/dbchangelog/")
.replaceFirst("https?://", "");
if (shouldWarnOnMismatchedXsdVersion && !hasWarnedAboutMismatchedXsdVersion) {
warnForMismatchedXsdVersion(systemId);
}
InputStream stream = null;
URL resourceUri = getSearchClassloader().getResource(path);
if (resourceUri == null) {
Resource resource = Scope.getCurrentScope().getResourceAccessor().get(path);
if (resource.exists()) {
stream = resource.openInputStream();
}
} else {
stream = resourceUri.openStream();
}
if (stream == null) {
if (GlobalConfiguration.SECURE_PARSING.getCurrentValue()) {
String errorMessage = "Unable to resolve xml entity " + systemId + ". " +
GlobalConfiguration.SECURE_PARSING.getKey() + " is set to 'true' which does not allow remote lookups. " +
"Check for spelling or capitalization errors and missing extensions such as liquibase-commercial in your XSD definition. Or, set it to 'false' to allow remote lookups of xsd files.";
throw new XSDLookUpException(errorMessage);
} else {
log.fine("Unable to resolve XML entity locally. Will load from network.");
return null;
}
}
org.xml.sax.InputSource source = new org.xml.sax.InputSource(stream);
source.setPublicId(publicId);
source.setSystemId(systemId);
return source;
| 1,048
| 577
| 1,625
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/parser/core/xml/XMLChangeLogSAXHandler.java
|
XMLChangeLogSAXHandler
|
startElement
|
class XMLChangeLogSAXHandler extends DefaultHandler {
private final ChangeFactory changeFactory;
private final PreconditionFactory preconditionFactory;
private final SqlVisitorFactory sqlVisitorFactory;
private final ChangeLogParserFactory changeLogParserFactory;
protected Logger log;
private final DatabaseChangeLog databaseChangeLog;
private final ResourceAccessor resourceAccessor;
private final ChangeLogParameters changeLogParameters;
private final Stack<ParsedNode> nodeStack = new Stack<>();
private final Stack<StringBuilder> textStack = new Stack<>();
private ParsedNode databaseChangeLogTree;
protected XMLChangeLogSAXHandler(String physicalChangeLogLocation, ResourceAccessor resourceAccessor, ChangeLogParameters changeLogParameters) {
log = Scope.getCurrentScope().getLog(getClass());
this.resourceAccessor = resourceAccessor;
databaseChangeLog = new DatabaseChangeLog();
databaseChangeLog.setPhysicalFilePath(physicalChangeLogLocation);
databaseChangeLog.setChangeLogParameters(changeLogParameters);
if (changeLogParameters == null) {
this.changeLogParameters = new ChangeLogParameters();
} else {
this.changeLogParameters = changeLogParameters;
}
changeFactory = Scope.getCurrentScope().getSingleton(ChangeFactory.class);
preconditionFactory = PreconditionFactory.getInstance();
sqlVisitorFactory = SqlVisitorFactory.getInstance();
changeLogParserFactory = ChangeLogParserFactory.getInstance();
}
public DatabaseChangeLog getDatabaseChangeLog() {
return databaseChangeLog;
}
public ParsedNode getDatabaseChangeLogTree() {
return databaseChangeLogTree;
}
@Override
public void characters(char ch[], int start, int length) {
textStack.peek().append(new String(ch, start, length));
}
@Override
public void startElement(String uri, String localName, String qualifiedName, Attributes attributes) throws SAXException {<FILL_FUNCTION_BODY>}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
ParsedNode node = nodeStack.pop();
try {
String seenText = this.textStack.pop().toString();
if (!"".equals(StringUtil.trimToEmpty(seenText))) {
node.setValue(seenText.trim());
}
} catch (ParsedNodeException e) {
throw new SAXException(e);
}
}
}
|
ParsedNode node = new ParsedNode(null, localName);
try {
if (attributes != null) {
for (int i=0; i< attributes.getLength(); i++) {
try {
node.addChild(null, attributes.getLocalName(i), attributes.getValue(i));
} catch (NullPointerException e) {
throw e;
}
}
}
if (!nodeStack.isEmpty()) {
nodeStack.peek().addChild(node);
}
if (nodeStack.isEmpty()) {
databaseChangeLogTree = node;
}
nodeStack.push(node);
textStack.push(new StringBuilder());
} catch (ParsedNodeException e) {
throw new SAXException(e);
}
| 625
| 202
| 827
|
<methods>public void <init>() ,public void characters(char[], int, int) throws org.xml.sax.SAXException,public void endDocument() throws org.xml.sax.SAXException,public void endElement(java.lang.String, java.lang.String, java.lang.String) throws org.xml.sax.SAXException,public void endPrefixMapping(java.lang.String) throws org.xml.sax.SAXException,public void error(org.xml.sax.SAXParseException) throws org.xml.sax.SAXException,public void fatalError(org.xml.sax.SAXParseException) throws org.xml.sax.SAXException,public void ignorableWhitespace(char[], int, int) throws org.xml.sax.SAXException,public void notationDecl(java.lang.String, java.lang.String, java.lang.String) throws org.xml.sax.SAXException,public void processingInstruction(java.lang.String, java.lang.String) throws org.xml.sax.SAXException,public org.xml.sax.InputSource resolveEntity(java.lang.String, java.lang.String) throws java.io.IOException, org.xml.sax.SAXException,public void setDocumentLocator(org.xml.sax.Locator) ,public void skippedEntity(java.lang.String) throws org.xml.sax.SAXException,public void startDocument() throws org.xml.sax.SAXException,public void startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) throws org.xml.sax.SAXException,public void startPrefixMapping(java.lang.String, java.lang.String) throws org.xml.sax.SAXException,public void unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String) throws org.xml.sax.SAXException,public void warning(org.xml.sax.SAXParseException) throws org.xml.sax.SAXException<variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/parser/core/xml/XMLChangeLogSAXParser.java
|
XMLChangeLogSAXParser
|
parseToNode
|
class XMLChangeLogSAXParser extends AbstractChangeLogParser {
public static final String LIQUIBASE_SCHEMA_VERSION;
private final SAXParserFactory saxParserFactory;
static {
LIQUIBASE_SCHEMA_VERSION = computeSchemaVersion(LiquibaseUtil.getBuildVersion());
}
private final LiquibaseEntityResolver resolver = new LiquibaseEntityResolver();
public XMLChangeLogSAXParser() {
saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setValidating(GlobalConfiguration.VALIDATE_XML_CHANGELOG_FILES.getCurrentValue());
saxParserFactory.setNamespaceAware(true);
if (GlobalConfiguration.SECURE_PARSING.getCurrentValue()) {
try {
saxParserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
} catch (Throwable e) {
Scope.getCurrentScope().getLog(getClass()).fine("Cannot enable FEATURE_SECURE_PROCESSING: " + e.getMessage(), e);
}
}
}
@Override
public int getPriority() {
return PRIORITY_DEFAULT;
}
public static String getSchemaVersion() {
return LIQUIBASE_SCHEMA_VERSION;
}
@Override
public boolean supports(String changeLogFile, ResourceAccessor resourceAccessor) {
return changeLogFile.toLowerCase().endsWith("xml");
}
protected SAXParserFactory getSaxParserFactory() {
return saxParserFactory;
}
/**
* When set to true, a warning will be printed to the console if the XSD version used does not match the version
* of Liquibase. If "latest" is used as the XSD version, no warning is printed.
*/
public void setShouldWarnOnMismatchedXsdVersion(boolean shouldWarnOnMismatchedXsdVersion) {
resolver.setShouldWarnOnMismatchedXsdVersion(shouldWarnOnMismatchedXsdVersion);
}
@Override
protected ParsedNode parseToNode(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException {<FILL_FUNCTION_BODY>}
/**
* Attempts to set the "schemaLanguage" property of the given parser, but ignores any errors that may occur if the parser
* does not recognize this property.
*
* @param parser the parser to configure
* @todo Investigate why we set this property if we don't mind if the parser does not recognize it.
*/
private void trySetSchemaLanguageProperty(SAXParser parser) {
try {
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
} catch (SAXNotRecognizedException | SAXNotSupportedException ignored) {
//ok, parser need not support it
}
}
static String computeSchemaVersion(String version) {
String finalVersion = null;
if (version != null && version.contains(".")) {
String[] splitVersion = version.split("\\.");
finalVersion = splitVersion[0] + "." + splitVersion[1];
}
if (finalVersion == null) {
finalVersion = "latest";
}
return finalVersion;
}
}
|
try {
Resource resource = resourceAccessor.get(physicalChangeLogLocation);
SAXParser parser = saxParserFactory.newSAXParser();
if (GlobalConfiguration.SECURE_PARSING.getCurrentValue()) {
try {
parser.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "http,https"); //need to allow external schemas on http/https to support the liquibase.org xsd files
} catch (SAXException e) {
Scope.getCurrentScope().getLog(getClass()).fine("Cannot enable ACCESS_EXTERNAL_SCHEMA: " + e.getMessage(), e);
}
}
trySetSchemaLanguageProperty(parser);
XMLReader xmlReader = parser.getXMLReader();
xmlReader.setEntityResolver(resolver);
xmlReader.setErrorHandler(new ErrorHandler() {
@Override
public void warning(SAXParseException exception) throws SAXException {
Scope.getCurrentScope().getLog(getClass()).warning(exception.getMessage());
throw exception;
}
@Override
public void error(SAXParseException exception) throws SAXException {
Scope.getCurrentScope().getLog(getClass()).severe(exception.getMessage());
throw exception;
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
Scope.getCurrentScope().getLog(getClass()).severe(exception.getMessage());
throw exception;
}
});
if (!resource.exists()) {
if (physicalChangeLogLocation.startsWith("WEB-INF/classes/")) {
// Correct physicalChangeLogLocation and try again.
return parseToNode(
physicalChangeLogLocation.replaceFirst("WEB-INF/classes/", ""),
changeLogParameters, resourceAccessor);
} else {
throw new ChangeLogParseException(FileUtil.getFileNotFoundMessage(physicalChangeLogLocation));
}
}
XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters);
xmlReader.setContentHandler(contentHandler);
try (InputStream stream = resource.openInputStream()) {
xmlReader.parse(new InputSource(new BomAwareInputStream(stream)));
}
return contentHandler.getDatabaseChangeLogTree();
} catch (ChangeLogParseException e) {
throw e;
} catch (IOException e) {
throw new ChangeLogParseException("Error Reading Changelog File: " + e.getMessage(), e);
} catch (SAXParseException e) {
throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation + ": " + e.getMessage(), e);
} catch (SAXException e) {
Throwable parentCause = e.getException();
while (parentCause != null) {
if (parentCause instanceof ChangeLogParseException) {
throw ((ChangeLogParseException) parentCause);
}
parentCause = parentCause.getCause();
}
String reason = e.getMessage();
String causeReason = null;
if (e.getCause() != null) {
causeReason = e.getCause().getMessage();
}
if (reason == null) {
if (causeReason != null) {
reason = causeReason;
} else {
reason = "Unknown Reason";
}
}
throw new ChangeLogParseException("Invalid Migration File: " + reason, e);
} catch (Exception e) {
throw new ChangeLogParseException(e);
}
| 872
| 924
| 1,796
|
<methods>public non-sealed void <init>() ,public liquibase.changelog.DatabaseChangeLog parse(java.lang.String, liquibase.changelog.ChangeLogParameters, liquibase.resource.ResourceAccessor) throws liquibase.exception.ChangeLogParseException<variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/parser/core/yaml/CustomConstructYamlTimestamp.java
|
CustomConstructYamlTimestamp
|
construct
|
class CustomConstructYamlTimestamp extends SafeConstructor.ConstructYamlTimestamp {
private final static Pattern TIMESTAMP_REGEXP = Pattern.compile(
"^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:(?:[Tt]|[ \t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \t]*(?:Z|([-+][0-9][0-9]?)(?::([0-9][0-9])?)?))?)?$");
private final static Pattern YMD_REGEXP =
Pattern.compile("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)$");
private Calendar calendar;
@Override
public Object construct(Node node) {<FILL_FUNCTION_BODY>}
}
|
ScalarNode scalar = (ScalarNode) node;
String nodeValue = scalar.getValue();
Matcher match = YMD_REGEXP.matcher(nodeValue);
if (match.matches()) {
String year_s = match.group(1);
String month_s = match.group(2);
String day_s = match.group(3);
calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
calendar.set(Calendar.YEAR, Integer.parseInt(year_s));
// Java's months are zero-based...
calendar.set(Calendar.MONTH, Integer.parseInt(month_s) - 1); // x
calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day_s));
return calendar.getTime();
} else {
match = TIMESTAMP_REGEXP.matcher(nodeValue);
if (!match.matches()) {
throw new YAMLException("Unexpected timestamp: " + nodeValue);
}
String year_s = match.group(1);
String month_s = match.group(2);
String day_s = match.group(3);
String hour_s = match.group(4);
String min_s = match.group(5);
// seconds and milliseconds
String seconds = match.group(6);
String millis = match.group(7);
if (millis != null) {
seconds = seconds + "." + millis;
}
double fractions = Double.parseDouble(seconds);
int sec_s = (int) Math.round(Math.floor(fractions));
int usec = (int) Math.round((fractions - sec_s) * 1000);
// timezone
String timezoneh_s = match.group(8);
String timezonem_s = match.group(9);
TimeZone timeZone = null;
if (timezoneh_s != null) {
String time = timezonem_s != null ? ":" + timezonem_s : "00";
timeZone = TimeZone.getTimeZone("GMT" + timezoneh_s + time);
calendar = Calendar.getInstance(timeZone);
;
} else {
calendar = Calendar.getInstance();
}
calendar.set(Calendar.YEAR, Integer.parseInt(year_s));
// Java's months are zero-based...
calendar.set(Calendar.MONTH, Integer.parseInt(month_s) - 1);
calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day_s));
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour_s));
calendar.set(Calendar.MINUTE, Integer.parseInt(min_s));
calendar.set(Calendar.SECOND, sec_s);
calendar.set(Calendar.MILLISECOND, usec);
if (timeZone == null) {
return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
} else {
return calendar.getTime().toString();
}
}
| 278
| 815
| 1,093
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/parser/core/yaml/YamlChangeLogParser.java
|
YamlChangeLogParser
|
parse
|
class YamlChangeLogParser extends YamlParser implements ChangeLogParser {
private static final String DATABASE_CHANGE_LOG = "databaseChangeLog";
@Override
public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException {<FILL_FUNCTION_BODY>}
private Map parseYamlStream(String physicalChangeLogLocation, Yaml yaml, InputStream changeLogStream) throws ChangeLogParseException {
Map parsedYaml;
try {
parsedYaml = yaml.load(changeLogStream);
} catch (Exception e) {
throw new ChangeLogParseException("Syntax error in file " + physicalChangeLogLocation + ": " + e.getMessage(), e);
}
return parsedYaml;
}
private void loadChangeLogParametersFromFile(ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor, DatabaseChangeLog changeLog, Map property, ContextExpression context, Labels labels, Boolean global) throws IOException, LiquibaseException {
Properties props = new Properties();
Boolean relativeToChangelogFile = (Boolean) property.get("relativeToChangelogFile");
Boolean errorIfMissing = (Boolean) property.get("errorIfMissing");
String file = (String) property.get("file");
if (relativeToChangelogFile == null) {
relativeToChangelogFile = false;
}
if (errorIfMissing == null) {
errorIfMissing = true;
}
Resource resource;
if (relativeToChangelogFile) {
resource = resourceAccessor.get(changeLog.getPhysicalFilePath()).resolveSibling(file);
} else {
resource = resourceAccessor.get(file);
}
if (!resource.exists()) {
if (errorIfMissing) {
throw new UnexpectedLiquibaseException(FileUtil.getFileNotFoundMessage(file));
}
else {
Scope.getCurrentScope().getLog(getClass()).warning(FileUtil.getFileNotFoundMessage(file));
}
} else {
try (InputStream stream = resource.openInputStream()) {
props.load(stream);
}
for (Map.Entry entry : props.entrySet()) {
changeLogParameters.set(entry.getKey().toString(), entry.getValue().toString(), context, labels, (String) property.get("dbms"), global, changeLog);
}
}
}
/**
* Extract the global parameter from the properties.
*
* @param property the map of props
* @return the global param
*/
private Boolean getGlobalParam(Map property) {
Boolean global = null;
Object globalObj = property.get("global");
if (globalObj == null) {
global = true;
} else {
global = (Boolean) globalObj;
}
return global;
}
protected void replaceParameters(Object obj, ChangeLogParameters changeLogParameters, DatabaseChangeLog changeLog) throws ChangeLogParseException {
if (obj instanceof Map) {
for (Map.Entry entry : (Set<Map.Entry>) ((Map) obj).entrySet()) {
if ((entry.getValue() instanceof Map) || (entry.getValue() instanceof Collection)) {
replaceParameters(entry.getValue(), changeLogParameters, changeLog);
} else if (entry.getValue() instanceof String) {
entry.setValue(changeLogParameters.expandExpressions((String) entry.getValue(), changeLog));
}
}
} else if (obj instanceof Collection) {
ListIterator iterator = ((List) obj).listIterator();
while (iterator.hasNext()) {
Object child = iterator.next();
if ((child instanceof Map) || (child instanceof Collection)) {
replaceParameters(child, changeLogParameters, changeLog);
} else if (child instanceof String) {
iterator.set(changeLogParameters.expandExpressions((String) child, changeLog));
}
}
}
}
static class CustomSafeConstructor extends SafeConstructor {
/**
* Create an instance
*
* @param loaderOptions - the configuration options
*/
public CustomSafeConstructor(LoaderOptions loaderOptions) {
super(loaderOptions);
this.yamlConstructors.put(Tag.TIMESTAMP, new CustomConstructYamlTimestamp());
}
}
}
|
Yaml yaml = new Yaml(new CustomSafeConstructor(createLoaderOptions()));
try {
Resource changelog = resourceAccessor.get(physicalChangeLogLocation);
if (!changelog.exists()) {
throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist");
}
Map parsedYaml;
try (InputStream changeLogStream = changelog.openInputStream()) {
parsedYaml = parseYamlStream(physicalChangeLogLocation, yaml, changeLogStream);
}
if ((parsedYaml == null) || parsedYaml.isEmpty()) {
throw new ChangeLogParseException("Empty file " + physicalChangeLogLocation);
}
DatabaseChangeLog changeLog = new DatabaseChangeLog(DatabaseChangeLog.normalizePath(physicalChangeLogLocation));
if (!parsedYaml.containsKey(DATABASE_CHANGE_LOG)) {
throw new ChangeLogParseException("Could not find databaseChangeLog node");
}
Object rootList = parsedYaml.get(DATABASE_CHANGE_LOG);
if (rootList == null) {
changeLog.setChangeLogParameters(changeLogParameters);
return changeLog;
}
if (!(rootList instanceof List)) {
throw new ChangeLogParseException("databaseChangeLog does not contain a list of entries. Each changeSet must begin ' - changeSet:'");
}
for (Object obj : (List) rootList) {
if (obj instanceof Map) {
if (((Map<?, ?>) obj).containsKey("property")) {
Map property = (Map) ((Map<?, ?>) obj).get("property");
ContextExpression context = new ContextExpression((String) property.get("context"));
Labels labels = new Labels((String) property.get("labels"));
Boolean global = getGlobalParam(property);
if (property.containsKey("name")) {
Object value = property.get("value");
changeLogParameters.set((String) property.get("name"), value, context, labels, (String) property.get("dbms"), global, changeLog);
} else if (property.containsKey("file")) {
loadChangeLogParametersFromFile(changeLogParameters, resourceAccessor, changeLog, property,
context, labels, global);
}
}
}
}
replaceParameters(parsedYaml, changeLogParameters, changeLog);
changeLog.setChangeLogParameters(changeLogParameters);
ParsedNode databaseChangeLogNode = new ParsedNode(null, DATABASE_CHANGE_LOG);
databaseChangeLogNode.setValue(rootList);
changeLog.load(databaseChangeLogNode, resourceAccessor);
return changeLog;
} catch (ChangeLogParseException e) {
throw e;
} catch (Exception e) {
throw new ChangeLogParseException("Error parsing " + physicalChangeLogLocation + " : " + e.getMessage(), e);
}
| 1,078
| 728
| 1,806
|
<methods>public non-sealed void <init>() ,public static LoaderOptions createLoaderOptions() ,public int getPriority() ,public boolean supports(java.lang.String, liquibase.resource.ResourceAccessor) <variables>protected liquibase.logging.Logger log
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/parser/core/yaml/YamlParser.java
|
YamlParser
|
supports
|
class YamlParser implements LiquibaseParser {
protected Logger log = Scope.getCurrentScope().getLog(getClass());
public static LoaderOptions createLoaderOptions() {
LoaderOptions options = new LoaderOptions();
SnakeYamlUtil.setCodePointLimitSafely(options, Integer.MAX_VALUE);
SnakeYamlUtil.setProcessCommentsSafely(options, false);
options.setAllowRecursiveKeys(false);
return options;
}
public boolean supports(String changeLogFile, ResourceAccessor resourceAccessor) {<FILL_FUNCTION_BODY>}
protected String[] getSupportedFileExtensions() {
return new String[] {"yaml", "yml"};
}
@Override
public int getPriority() {
return PRIORITY_DEFAULT;
}
}
|
for (String extension : getSupportedFileExtensions()) {
if (changeLogFile.toLowerCase().endsWith("." + extension)) {
return true;
}
}
return false;
| 217
| 54
| 271
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/parser/core/yaml/YamlSnapshotParser.java
|
YamlSnapshotParser
|
initDumperOptions
|
class YamlSnapshotParser extends YamlParser implements SnapshotParser {
public static final int CODE_POINT_LIMIT = Integer.MAX_VALUE;
@SuppressWarnings("java:S2095")
@Override
public DatabaseSnapshot parse(String path, ResourceAccessor resourceAccessor) throws LiquibaseParseException {
Yaml yaml = createYaml();
try {
Resource resource = resourceAccessor.get(path);
if (resource == null) {
throw new LiquibaseParseException(path + " does not exist");
}
Map parsedYaml;
try (InputStream stream = resource.openInputStream()) {
parsedYaml = getParsedYamlFromInputStream(yaml, stream);
}
Map rootList = (Map) parsedYaml.get("snapshot");
if (rootList == null) {
throw new LiquibaseParseException("Could not find root snapshot node");
}
String shortName = (String) ((Map<?, ?>) rootList.get("database")).get("shortName");
Database database = DatabaseFactory.getInstance().getDatabase(shortName).getClass().getConstructor().newInstance();
database.setConnection(new OfflineConnection("offline:" + shortName, null));
DatabaseSnapshot snapshot = new RestoredDatabaseSnapshot(database);
ParsedNode snapshotNode = new ParsedNode(null, "snapshot");
snapshotNode.setValue(rootList);
Map metadata = (Map) rootList.get("metadata");
if (metadata != null) {
snapshot.getMetadata().putAll(metadata);
}
snapshot.load(snapshotNode, resourceAccessor);
return snapshot;
} catch (LiquibaseParseException e) {
throw e;
}
catch (Exception e) {
throw new LiquibaseParseException(e);
}
}
private Yaml createYaml() {
LoaderOptions loaderOptions = new LoaderOptions();
SnakeYamlUtil.setCodePointLimitSafely(loaderOptions, CODE_POINT_LIMIT);
Representer representer = new Representer(new DumperOptions());
DumperOptions dumperOptions = initDumperOptions(representer);
return new Yaml(new SafeConstructor(loaderOptions), representer, dumperOptions, loaderOptions, new Resolver());
}
private static DumperOptions initDumperOptions(Representer representer) {<FILL_FUNCTION_BODY>}
private Map getParsedYamlFromInputStream(Yaml yaml, InputStream stream) throws LiquibaseParseException {
Map parsedYaml;
try (
InputStreamReader inputStreamReader = new InputStreamReader(
stream, GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue()
)
) {
parsedYaml = (Map) yaml.load(inputStreamReader);
} catch (Exception e) {
throw new LiquibaseParseException("Syntax error in " + getSupportedFileExtensions()[0] + ": " + e.getMessage(), e);
}
return parsedYaml;
}
}
|
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(representer.getDefaultFlowStyle());
dumperOptions.setDefaultScalarStyle(representer.getDefaultScalarStyle());
dumperOptions
.setAllowReadOnlyProperties(representer.getPropertyUtils().isAllowReadOnlyProperties());
dumperOptions.setTimeZone(representer.getTimeZone());
return dumperOptions;
| 783
| 108
| 891
|
<methods>public non-sealed void <init>() ,public static LoaderOptions createLoaderOptions() ,public int getPriority() ,public boolean supports(java.lang.String, liquibase.resource.ResourceAccessor) <variables>protected liquibase.logging.Logger log
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/plugin/AbstractPluginFactory.java
|
AbstractPluginFactory
|
getForcedPluginIfAvailable
|
class AbstractPluginFactory<T extends Plugin> implements PluginFactory {
private Collection<T> allInstances;
protected AbstractPluginFactory() {
}
protected abstract Class<T> getPluginClass();
/**
* Returns the priority of the given object based on the passed args array.
* The args are created as part of the custom public getPlugin method in implementations are passed through {@link #getPlugin(Object...)}
*/
protected abstract int getPriority(T obj, Object... args);
/**
* Finds the plugin for which {@link #getPriority(Plugin, Object...)} returns the highest value for the given scope and args.
* This method is called by a public implementation-specific methods.
* Normally this does not need to be overridden, instead override {@link #getPriority(Plugin, Object...)} to compute the priority of each object for the scope and arguments passed to this method.
* <p>
* However, if there is a {@link Scope} key of "liquibase.plugin.${plugin.interface.class.Name}", an instance of that class will always be ran first.
*
* @return null if no plugins are found or have a priority greater than zero.
*/
protected T getPlugin(final Object... args) {
Set<T> applicable = this.getPlugins(args);
if (applicable.isEmpty()) {
return null;
}
return applicable.iterator().next();
}
protected Set<T> getPlugins(final Object... args) {
Optional<T> forcedPlugin = this.getForcedPluginIfAvailable();
if (forcedPlugin.isPresent()) {
return new HashSet<>(Collections.singletonList(forcedPlugin.get()));
}
TreeSet<T> applicable = new TreeSet<>((o1, o2) -> {
Integer o1Priority = getPriority(o1, args);
Integer o2Priority = getPriority(o2, args);
int i = o2Priority.compareTo(o1Priority);
if (i == 0) {
return o1.getClass().getName().compareTo(o2.getClass().getName());
}
return i;
});
for (T plugin : findAllInstances()) {
if (getPriority(plugin, args) >= 0) {
applicable.add(plugin);
}
}
return applicable;
}
private Optional<T> getForcedPluginIfAvailable() {<FILL_FUNCTION_BODY>}
public synchronized void register(T plugin) {
this.findAllInstances();
this.allInstances.add(plugin);
}
/**
* Finds implementations of the given interface or class and returns instances of them.
* Standard implementation uses {@link ServiceLoader} to find implementations and caches results in {@link #allInstances} which means the same objects are always returned.
* If the instances should not be treated as singletons, clone the objects before returning them from {@link #getPlugin(Object...)}.
*/
protected synchronized Collection<T> findAllInstances() {
if (this.allInstances == null) {
this.allInstances = new ArrayList<>();
ServiceLocator serviceLocator = Scope.getCurrentScope().getServiceLocator();
this.allInstances.addAll(serviceLocator.findInstances(getPluginClass()));
}
return this.allInstances;
}
protected synchronized void removeInstance(T instance) {
if (this.allInstances == null) {
return;
}
this.allInstances.remove(instance);
}
}
|
final String pluginClassName = getPluginClass().getName();
final Class<?> forcedPlugin = Scope.getCurrentScope().get("liquibase.plugin." + pluginClassName, Class.class);
if (forcedPlugin != null) {
for (T plugin : findAllInstances()) {
if (plugin.getClass().equals(forcedPlugin)) {
return Optional.of(plugin);
}
}
throw new UnexpectedLiquibaseException("No registered " + pluginClassName + " plugin " + forcedPlugin.getName());
}
return Optional.empty();
| 904
| 146
| 1,050
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/CustomPreconditionWrapper.java
|
CustomPreconditionWrapper
|
check
|
class CustomPreconditionWrapper extends AbstractPrecondition {
private String className;
private final SortedSet<String> params = new TreeSet<>();
private final Map<String, String> paramValues = new LinkedHashMap<>();
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public void setClass(String className) {
this.className = className;
}
public String getParamValue(String key) {
return paramValues.get(key);
}
public void setParam(String name, String value) {
this.params.add(name);
this.paramValues.put(name, value);
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public ValidationErrors validate(Database database) {
return new ValidationErrors();
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {<FILL_FUNCTION_BODY>}
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@Override
public Set<String> getSerializableFields() {
return new LinkedHashSet<>(Arrays.asList("className", "param"));
}
@Override
public Object getSerializableFieldValue(String field) {
return field.equals("param") ? paramValues
: super.getSerializableFieldValue(field);
}
@Override
public String getName() {
return "customPrecondition";
}
@Override
protected boolean shouldAutoLoad(ParsedNode node) {
if ("params".equals(node.getName()) || "param".equals(node.getName())) {
return false;
}
return super.shouldAutoLoad(node);
}
@Override
public void load(ParsedNode parsedNode, ResourceAccessor resourceAccessor) throws ParsedNodeException {
setClassName(parsedNode.getChildValue(null, "className", String.class));
ParsedNode paramsNode = parsedNode.getChild(null, "params");
if (paramsNode == null) {
paramsNode = parsedNode;
}
for (ParsedNode child : paramsNode.getChildren(null, "param")) {
Object value = child.getValue();
if (value == null) {
value = child.getChildValue(null, "value");
}
if (value != null) {
value = value.toString();
}
this.setParam(child.getChildValue(null, "name", String.class), (String) value);
}
super.load(parsedNode, resourceAccessor);
}
}
|
CustomPrecondition customPrecondition;
try {
// System.out.println(classLoader.toString());
try {
customPrecondition = (CustomPrecondition) Class.forName(className, true, Scope.getCurrentScope().getClassLoader()).getConstructor().newInstance();
} catch (ClassCastException e) { //fails in Ant in particular
customPrecondition = (CustomPrecondition) Class.forName(className).getConstructor().newInstance();
}
} catch (Exception e) {
throw new PreconditionFailedException("Could not open custom precondition class "+className, changeLog, this);
}
for (String param : params) {
try {
ObjectUtil.setProperty(customPrecondition, param, paramValues.get(param));
} catch (Exception e) {
throw new PreconditionFailedException("Error setting parameter "+param+" on custom precondition "+className, changeLog, this);
}
}
try {
customPrecondition.check(database);
} catch (CustomPreconditionFailedException e) {
throw new PreconditionFailedException(new FailedPrecondition("Custom Precondition Failed: "+e.getMessage(), changeLog, this));
} catch (CustomPreconditionErrorException e) {
throw new PreconditionErrorException(new ErrorPrecondition(e, changeLog, this));
}
| 740
| 329
| 1,069
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/ErrorPrecondition.java
|
ErrorPrecondition
|
toString
|
class ErrorPrecondition {
private final Throwable cause;
private final Precondition precondition;
private final DatabaseChangeLog changeLog;
public ErrorPrecondition(Throwable exception, DatabaseChangeLog changeLog, Precondition precondition) {
this.cause = exception;
this.changeLog = changeLog;
this.precondition = precondition;
}
public Throwable getCause() {
return cause;
}
public Precondition getPrecondition() {
return precondition;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
Throwable cause = this.cause;
while (cause.getCause() != null) {
cause = cause.getCause();
}
String causeMessage = cause.getMessage();
if (causeMessage == null) {
causeMessage = this.cause.getMessage();
}
if (changeLog == null) {
return causeMessage;
} else {
return changeLog +" : "+ precondition.toString()+" : "+causeMessage;
}
| 159
| 124
| 283
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/FailedPrecondition.java
|
FailedPrecondition
|
toString
|
class FailedPrecondition {
private final String message;
private final Precondition precondition;
private final DatabaseChangeLog changeLog;
public FailedPrecondition(String message, DatabaseChangeLog changeLog, Precondition precondition) {
this.message = message;
this.changeLog = changeLog;
this.precondition = precondition;
}
public String getMessage() {
return message;
}
public Precondition getPrecondition() {
return precondition;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
if (changeLog == null) {
return message;
} else {
return changeLog +" : "+message;
}
| 153
| 38
| 191
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/PreconditionFactory.java
|
PreconditionFactory
|
create
|
class PreconditionFactory {
@SuppressWarnings("unchecked")
private final Map<String, Class<? extends Precondition>> preconditions;
private static PreconditionFactory instance;
@SuppressWarnings("unchecked")
private PreconditionFactory() {
preconditions = new HashMap<>();
try {
for (Precondition precondition : Scope.getCurrentScope().getServiceLocator().findInstances(Precondition.class)) {
register(precondition);
}
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
}
public static synchronized PreconditionFactory getInstance() {
if (instance == null) {
instance = new PreconditionFactory();
}
return instance;
}
public static synchronized void reset() {
instance = new PreconditionFactory();
}
public Map<String, Class<? extends Precondition>> getPreconditions() {
return preconditions;
}
public void register(Precondition precondition) {
try {
preconditions.put(precondition.getName(), precondition.getClass());
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
}
public void unregister(String name) {
preconditions.remove(name);
}
/**
* Create a new Precondition subclass based on the given tag name.
*/
public Precondition create(String tagName) {<FILL_FUNCTION_BODY>}
}
|
Class<?> aClass = preconditions.get(tagName);
if (aClass == null) {
return null;
}
try {
return (Precondition) aClass.getConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
| 386
| 79
| 465
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/PreconditionLogic.java
|
PreconditionLogic
|
toPrecondition
|
class PreconditionLogic extends AbstractPrecondition {
private final List<Precondition> nestedPreconditions = new ArrayList<>();
public List<Precondition> getNestedPreconditions() {
return this.nestedPreconditions;
}
public void addNestedPrecondition(Precondition precondition) {
if (precondition != null) {
nestedPreconditions.add(precondition);
}
}
@Override
public ValidationErrors validate(Database database) {
final ValidationErrors validationErrors = new ValidationErrors();
for (Precondition precondition : getNestedPreconditions()) {
validationErrors.addAll(precondition.validate(database));
}
return validationErrors;
}
@Override
public void load(ParsedNode parsedNode, ResourceAccessor resourceAccessor) throws ParsedNodeException {
super.load(parsedNode, resourceAccessor);
for (ParsedNode child : parsedNode.getChildren()) {
addNestedPrecondition(toPrecondition(child, resourceAccessor));
}
}
protected Precondition toPrecondition(ParsedNode node, ResourceAccessor resourceAccessor) throws ParsedNodeException {<FILL_FUNCTION_BODY>}
}
|
Precondition precondition = PreconditionFactory.getInstance().create(node.getName());
if (precondition == null) {
if (node.getChildren() != null && node.getChildren().size() > 0 && ChangeLogParserConfiguration.CHANGELOG_PARSE_MODE.getCurrentValue().equals(ChangeLogParserConfiguration.ChangelogParseMode.STRICT)) {
throw new ParsedNodeException("Unknown precondition '" + node.getName() + "'. Check for spelling or capitalization errors and missing extensions such as liquibase-commercial.");
}
return null;
}
precondition.load(node, resourceAccessor);
return precondition;
| 309
| 164
| 473
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/AndPrecondition.java
|
AndPrecondition
|
check
|
class AndPrecondition extends PreconditionLogic {
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "and";
}
}
|
boolean allPassed = true;
List<FailedPrecondition> failures = new ArrayList<>();
for (Precondition precondition : getNestedPreconditions()) {
try {
precondition.check(database, changeLog, changeSet, changeExecListener);
} catch (PreconditionFailedException e) {
failures.addAll(e.getFailedPreconditions());
allPassed = false;
break;
}
}
if (!allPassed) {
throw new PreconditionFailedException(failures);
}
| 156
| 133
| 289
|
<methods>public non-sealed void <init>() ,public void addNestedPrecondition(liquibase.precondition.Precondition) ,public List<liquibase.precondition.Precondition> getNestedPreconditions() ,public void load(liquibase.parser.core.ParsedNode, liquibase.resource.ResourceAccessor) throws liquibase.parser.core.ParsedNodeException,public liquibase.exception.ValidationErrors validate(liquibase.database.Database) <variables>private final List<liquibase.precondition.Precondition> nestedPreconditions
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/ChangeLogPropertyDefinedPrecondition.java
|
ChangeLogPropertyDefinedPrecondition
|
check
|
class ChangeLogPropertyDefinedPrecondition extends AbstractPrecondition {
private String property;
private String value;
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@Override
public String getName() {
return "changeLogPropertyDefined";
}
public void setProperty(String property) {
this.property = property;
}
public void setValue(String value) {
this.value = value;
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public ValidationErrors validate(Database database) {
return new ValidationErrors();
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {<FILL_FUNCTION_BODY>}
}
|
ChangeLogParameters changeLogParameters = changeLog.getChangeLogParameters();
if (changeLogParameters == null) {
throw new PreconditionFailedException("No Changelog properties were set", changeLog, this);
}
Object propertyValue = changeLogParameters.getValue(property, changeLog);
if (propertyValue == null) {
throw new PreconditionFailedException("Changelog property '"+ property +"' was not set", changeLog, this);
}
if ((value != null) && !propertyValue.toString().equals(value)) {
throw new PreconditionFailedException("Expected changelog property '"+ property +"' to have a value of '"+value+"'. Got '"+propertyValue+"'", changeLog, this);
}
| 250
| 181
| 431
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/ChangeSetExecutedPrecondition.java
|
ChangeSetExecutedPrecondition
|
check
|
class ChangeSetExecutedPrecondition extends AbstractPrecondition {
private String changeLogFile;
private String id;
private String author;
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public ValidationErrors validate(Database database) {
return new ValidationErrors();
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "changeSetExecuted";
}
}
|
ObjectQuotingStrategy objectQuotingStrategy;
if (changeSet == null) {
objectQuotingStrategy = ObjectQuotingStrategy.LEGACY;
} else {
objectQuotingStrategy = changeSet.getObjectQuotingStrategy();
}
String changeLogFile = getChangeLogFile();
if (changeLogFile == null) {
changeLogFile = changeLog.getLogicalFilePath();
}
ChangeSet interestedChangeSet = new ChangeSet(getId(), getAuthor(), false, false, changeLogFile, null, null, false, objectQuotingStrategy, changeLog);
RanChangeSet ranChangeSet;
try {
ranChangeSet = database.getRanChangeSet(interestedChangeSet);
} catch (Exception e) {
throw new PreconditionErrorException(e, changeLog, this);
}
if ((ranChangeSet == null) || (ranChangeSet.getExecType() == null) || !ranChangeSet.getExecType().ran) {
throw new PreconditionFailedException("Changeset '"+interestedChangeSet.toString(false)+"' has not been run", changeLog, this);
}
| 210
| 280
| 490
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/ColumnExistsPrecondition.java
|
ColumnExistsPrecondition
|
checkUsingSnapshot
|
class ColumnExistsPrecondition extends AbstractPrecondition {
private String catalogName;
private String schemaName;
private String tableName;
private String columnName;
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
public String getCatalogName() {
return catalogName;
}
public void setCatalogName(String catalogName) {
this.catalogName = catalogName;
}
public String getSchemaName() {
return schemaName;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public ValidationErrors validate(Database database) {
return new ValidationErrors();
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {
if (canCheckFast(database)) {
checkFast(database, changeLog);
} else {
checkUsingSnapshot(database, changeLog);
}
}
private void checkUsingSnapshot(Database database, DatabaseChangeLog changeLog) throws PreconditionFailedException, PreconditionErrorException {<FILL_FUNCTION_BODY>}
private boolean canCheckFast(Database database) {
if (getCatalogName() != null)
return false;
if (!(database.getConnection() instanceof JdbcConnection))
return false;
if (getColumnName() == null)
return false;
if (!getColumnName().matches("(?i)[a-z][a-z_0-9]*"))
return false;
return (getSchemaName() != null) || (database.getDefaultSchemaName() != null);
}
private void checkFast(Database database, DatabaseChangeLog changeLog)
throws PreconditionFailedException, PreconditionErrorException {
try {
String schemaName = getSchemaName();
if (schemaName == null) {
schemaName = database.getDefaultSchemaName();
}
String tableName = getTableName();
String columnName = getColumnName();
if (database instanceof PostgresDatabase) {
makeSureColumnExistsInPostgres(database, changeLog, schemaName, tableName, columnName);
} else {
makeSureColumnExistsInOtherDBs(database, changeLog, schemaName, tableName, columnName);
}
} catch (DatabaseException e) {
throw new PreconditionErrorException(e, changeLog, this);
}
}
private void makeSureColumnExistsInOtherDBs(Database database, DatabaseChangeLog changeLog, String schemaName, String tableName, String columnName) throws PreconditionFailedException {
String sql;
if (database instanceof FirebirdDatabase) {
sql = format("select t.%s from %s t where 0=1",
database.escapeColumnNameList(columnName),
database.escapeObjectName(tableName, Table.class));
} else {
sql = format("select t.%s from %s.%s t where 0=1",
database.escapeColumnNameList(columnName),
database.escapeObjectName(schemaName, Schema.class),
database.escapeObjectName(tableName, Table.class));
}
try (PreparedStatement statement2 = ((JdbcConnection) database.getConnection()).prepareStatement(sql);
ResultSet rs = statement2.executeQuery()
){
// column exists
} catch (SQLException | DatabaseException e) {
// column or table does not exist
throw new PreconditionFailedException(format(
"Column %s.%s.%s does not exist", schemaName,
tableName, columnName), changeLog, this);
}
}
private void makeSureColumnExistsInPostgres(Database database, DatabaseChangeLog changeLog, String schemaName, String tableName, String columnName) throws PreconditionFailedException, PreconditionErrorException, DatabaseException {
String sql = "SELECT 1 FROM pg_attribute a WHERE EXISTS (SELECT 1 FROM pg_class JOIN pg_catalog.pg_namespace ns ON ns.oid = pg_class.relnamespace WHERE lower(ns.nspname) = ? AND lower(relname) = lower(?) AND pg_class.oid = a.attrelid) AND lower(a.attname) = lower(?);";
try (PreparedStatement statement = ((JdbcConnection) database.getConnection())
.prepareStatement(sql)){
statement.setString(1, schemaName.toLowerCase());
statement.setString(2, tableName);
statement.setString(3, columnName);
try (ResultSet rs = statement.executeQuery()) {
if (rs.next()) {
return;
} else {
// column or table does not exist
throw new PreconditionFailedException(format("Column %s.%s.%s does not exist", schemaName, tableName, columnName), changeLog, this);
}
}
} catch (SQLException e) {
throw new PreconditionErrorException(e, changeLog, this);
}
}
@Override
public String getName() {
return "columnExists";
}
}
|
Column example = new Column();
if (StringUtil.trimToNull(getTableName()) != null) {
example.setRelation(new Table().setName(database.correctObjectName(getTableName(), Table.class)).setSchema(new Schema(getCatalogName(), getSchemaName())));
}
example.setName(database.correctObjectName(getColumnName(), Column.class));
try {
if (!SnapshotGeneratorFactory.getInstance().has(example, database)) {
throw new PreconditionFailedException("Column '" + database.escapeColumnName(catalogName, schemaName, getTableName(), getColumnName()) + "' does not exist", changeLog, this);
}
} catch (LiquibaseException e) {
throw new PreconditionErrorException(e, changeLog, this);
}
| 1,426
| 201
| 1,627
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/DBMSPrecondition.java
|
DBMSPrecondition
|
setType
|
class DBMSPrecondition extends AbstractPrecondition {
private String type;
public DBMSPrecondition() {
}
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
public String getType() {
return type;
}
public void setType(String atype) {<FILL_FUNCTION_BODY>}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public ValidationErrors validate(Database database) {
return new ValidationErrors();
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {
try {
String dbType = database.getShortName();
if (!DatabaseList.definitionMatches(this.type, database, false)) {
throw new PreconditionFailedException("DBMS Precondition failed: expected "+type+", got "+dbType, changeLog, this);
}
} catch (PreconditionFailedException e) {
throw e;
} catch (Exception e) {
throw new PreconditionErrorException(e, changeLog, this);
}
}
@Override
public String getName() {
return "dbms";
}
}
|
if (atype == null) {
this.type = null;
} else {
this.type = atype.toLowerCase();
}
| 356
| 42
| 398
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/ForeignKeyExistsPrecondition.java
|
ForeignKeyExistsPrecondition
|
check
|
class ForeignKeyExistsPrecondition extends AbstractPrecondition {
private String catalogName;
private String schemaName;
private String foreignKeyTableName;
private String foreignKeyName;
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
public String getCatalogName() {
return catalogName;
}
public void setCatalogName(String catalogName) {
this.catalogName = catalogName;
}
public String getSchemaName() {
return schemaName;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
public String getForeignKeyTableName() {
return foreignKeyTableName;
}
public void setForeignKeyTableName(String foreignKeyTableName) {
this.foreignKeyTableName = foreignKeyTableName;
}
public String getForeignKeyName() {
return foreignKeyName;
}
public void setForeignKeyName(String foreignKeyName) {
this.foreignKeyName = foreignKeyName;
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public ValidationErrors validate(Database database) {
return new ValidationErrors();
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener) throws PreconditionFailedException, PreconditionErrorException {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "foreignKeyConstraintExists";
}
}
|
try {
ForeignKey example = new ForeignKey();
example.setName(getForeignKeyName());
example.setForeignKeyTable(new Table());
if (StringUtil.trimToNull(getForeignKeyTableName()) != null) {
example.getForeignKeyTable().setName(getForeignKeyTableName());
}
example.getForeignKeyTable().setSchema(new Schema(getCatalogName(), getSchemaName()));
if (!SnapshotGeneratorFactory.getInstance().has(example, database)) {
throw new PreconditionFailedException("Foreign Key " +
database.escapeIndexName(catalogName, schemaName, foreignKeyName) + " does not exist",
changeLog,
this
);
}
} catch (PreconditionFailedException e) {
throw e;
} catch (Exception e) {
throw new PreconditionErrorException(e, changeLog, this);
}
| 428
| 231
| 659
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/IndexExistsPrecondition.java
|
IndexExistsPrecondition
|
toString
|
class IndexExistsPrecondition extends AbstractPrecondition {
private String catalogName;
private String schemaName;
private String tableName;
private String columnNames;
private String indexName;
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
public String getCatalogName() {
return catalogName;
}
public void setCatalogName(String catalogName) {
this.catalogName = catalogName;
}
public String getSchemaName() {
return schemaName;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getIndexName() {
return indexName;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
public String getColumnNames() {
return columnNames;
}
public void setColumnNames(String columnNames) {
this.columnNames = columnNames;
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public ValidationErrors validate(Database database) {
ValidationErrors validationErrors = new ValidationErrors();
if (getIndexName() == null && (getTableName() == null || getColumnNames() == null)) {
validationErrors.addError("indexName OR (tableName and columnNames) is required");
}
return validationErrors;
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {
try {
Schema schema = new Schema(getCatalogName(), getSchemaName());
Index example = new Index();
String tableName = StringUtil.trimToNull(getTableName());
if (tableName != null) {
example.setRelation(new Table()
.setName(database.correctObjectName(getTableName(), Table.class))
.setSchema(schema));
}
example.setName(database.correctObjectName(getIndexName(), Index.class));
if (StringUtil.trimToNull(getColumnNames()) != null) {
for (String column : getColumnNames().split("\\s*,\\s*")) {
example.addColumn(new Column(database.correctObjectName(column, Column.class)));
}
}
if (!SnapshotGeneratorFactory.getInstance().has(example, database)) {
String name = "";
if (getIndexName() != null) {
name += database.escapeObjectName(getIndexName(), Index.class);
}
if (tableName != null) {
name += " on "+database.escapeObjectName(getTableName(), Table.class);
if (StringUtil.trimToNull(getColumnNames()) != null) {
name += " columns "+getColumnNames();
}
}
throw new PreconditionFailedException("Index "+ name +" does not exist", changeLog, this);
}
} catch (Exception e) {
if (e instanceof PreconditionFailedException) {
throw (((PreconditionFailedException) e));
}
throw new PreconditionErrorException(e, changeLog, this);
}
}
@Override
public String getName() {
return "indexExists";
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
String string = "Index Exists Precondition: ";
if (getIndexName() != null) {
string += getIndexName();
}
if (tableName != null) {
string += " on "+getTableName();
if (StringUtil.trimToNull(getColumnNames()) != null) {
string += " columns "+getColumnNames();
}
}
return string;
| 934
| 110
| 1,044
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/NotPrecondition.java
|
NotPrecondition
|
check
|
class NotPrecondition extends PreconditionLogic {
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "not";
}
}
|
for (Precondition precondition : getNestedPreconditions()) {
boolean threwException = false;
try {
precondition.check(database, changeLog, changeSet, changeExecListener);
} catch (PreconditionFailedException e) {
//that's what we want with a Not precondition
threwException = true;
}
if (!threwException) {
throw new PreconditionFailedException("Not precondition failed", changeLog, this);
}
}
| 155
| 121
| 276
|
<methods>public non-sealed void <init>() ,public void addNestedPrecondition(liquibase.precondition.Precondition) ,public List<liquibase.precondition.Precondition> getNestedPreconditions() ,public void load(liquibase.parser.core.ParsedNode, liquibase.resource.ResourceAccessor) throws liquibase.parser.core.ParsedNodeException,public liquibase.exception.ValidationErrors validate(liquibase.database.Database) <variables>private final List<liquibase.precondition.Precondition> nestedPreconditions
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/ObjectQuotingStrategyPrecondition.java
|
ObjectQuotingStrategyPrecondition
|
check
|
class ObjectQuotingStrategyPrecondition extends AbstractPrecondition {
private ObjectQuotingStrategy strategy;
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@Override
public String getName() {
return "expectedQuotingStrategy";
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public ValidationErrors validate(Database database) {
return new ValidationErrors();
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {<FILL_FUNCTION_BODY>}
public void setStrategy(String strategy) {
this.strategy = ObjectQuotingStrategy.valueOf(strategy);
}
}
|
try {
if (changeLog.getObjectQuotingStrategy() != strategy) {
throw new PreconditionFailedException("Quoting strategy Precondition failed: expected "
+ strategy +", got "+changeSet.getObjectQuotingStrategy(), changeLog, this);
}
} catch (PreconditionFailedException e) {
throw e;
} catch (Exception e) {
throw new PreconditionErrorException(e, changeLog, this);
}
| 230
| 114
| 344
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/OrPrecondition.java
|
OrPrecondition
|
check
|
class OrPrecondition extends PreconditionLogic {
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "or";
}
}
|
boolean onePassed = false;
List<FailedPrecondition> failures = new ArrayList<>();
for (Precondition precondition : getNestedPreconditions()) {
try {
precondition.check(database, changeLog, changeSet, changeExecListener);
onePassed = true;
break;
} catch (PreconditionFailedException e) {
failures.addAll(e.getFailedPreconditions());
}
}
if (!onePassed) {
throw new PreconditionFailedException(failures);
}
| 155
| 133
| 288
|
<methods>public non-sealed void <init>() ,public void addNestedPrecondition(liquibase.precondition.Precondition) ,public List<liquibase.precondition.Precondition> getNestedPreconditions() ,public void load(liquibase.parser.core.ParsedNode, liquibase.resource.ResourceAccessor) throws liquibase.parser.core.ParsedNodeException,public liquibase.exception.ValidationErrors validate(liquibase.database.Database) <variables>private final List<liquibase.precondition.Precondition> nestedPreconditions
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/PrimaryKeyExistsPrecondition.java
|
PrimaryKeyExistsPrecondition
|
check
|
class PrimaryKeyExistsPrecondition extends AbstractPrecondition {
private String catalogName;
private String schemaName;
private String primaryKeyName;
private String tableName;
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public ValidationErrors validate(Database database) {
ValidationErrors validationErrors = new ValidationErrors();
if ((getPrimaryKeyName() == null) && (getTableName() == null)) {
validationErrors.addError("Either primaryKeyName or tableName must be set");
}
return validationErrors;
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {<FILL_FUNCTION_BODY>}
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@Override
public String getName() {
return "primaryKeyExists";
}
}
|
try {
PrimaryKey example = new PrimaryKey();
Table table = new Table();
table.setSchema(new Schema(getCatalogName(), getSchemaName()));
if (StringUtil.trimToNull(getTableName()) != null) {
table.setName(getTableName());
} else if (database instanceof H2Database || database instanceof MySQLDatabase || database instanceof HsqlDatabase
|| database instanceof SQLiteDatabase || database instanceof DB2Database) {
throw new DatabaseException("Database driver requires a table name to be specified in order to search for a primary key.");
}
example.setTable(table);
example.setName(getPrimaryKeyName());
if (!SnapshotGeneratorFactory.getInstance().has(example, database)) {
if (tableName != null) {
throw new PreconditionFailedException("Primary Key does not exist on " + database.escapeObjectName(getTableName(), Table.class), changeLog, this);
} else {
throw new PreconditionFailedException("Primary Key " + database.escapeObjectName(getPrimaryKeyName(), PrimaryKey.class) + " does not exist", changeLog, this);
}
}
} catch (PreconditionFailedException e) {
throw e;
} catch (Exception e) {
throw new PreconditionErrorException(e, changeLog, this);
}
| 272
| 324
| 596
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/RowCountPrecondition.java
|
RowCountPrecondition
|
check
|
class RowCountPrecondition extends AbstractPrecondition {
private String catalogName;
private String schemaName;
private String tableName;
private Long expectedRows;
public String getCatalogName() {
return catalogName;
}
public void setCatalogName(String catalogName) {
this.catalogName = catalogName;
}
public String getSchemaName() {
return schemaName;
}
public void setSchemaName(String schemaName) {
this.schemaName = StringUtil.trimToNull(schemaName);
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public Long getExpectedRows() {
return expectedRows;
}
public void setExpectedRows(Long expectedRows) {
this.expectedRows = expectedRows;
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public ValidationErrors validate(Database database) {
ValidationErrors validationErrors = new ValidationErrors();
validationErrors.checkRequiredField("tableName", tableName);
validationErrors.checkRequiredField("expectedRows", expectedRows);
return validationErrors;
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {<FILL_FUNCTION_BODY>}
protected String getFailureMessage(long result, long expectedRows) {
return "Table "+tableName+" does not have the expected row count of "+expectedRows+". It contains "+result+" rows";
}
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@Override
public String getName() {
return "rowCount";
}
}
|
try {
TableRowCountStatement statement = new TableRowCountStatement(catalogName, schemaName, tableName);
long result = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database).queryForLong(statement);
if (result != expectedRows) {
throw new PreconditionFailedException(getFailureMessage(result, expectedRows), changeLog, this);
}
} catch (PreconditionFailedException e) {
throw e;
} catch (Exception e) {
throw new PreconditionErrorException(e, changeLog, this);
}
| 504
| 150
| 654
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/RunningAsPrecondition.java
|
RunningAsPrecondition
|
check
|
class RunningAsPrecondition extends AbstractPrecondition {
private String username;
public RunningAsPrecondition() {
username = "";
}
public void setUsername(String aUserName) {
username = aUserName;
}
public String getUsername() {
return username;
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public ValidationErrors validate(Database database) {
return new ValidationErrors();
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {<FILL_FUNCTION_BODY>}
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@Override
public String getName() {
return "runningAs";
}
}
|
String loggedusername = database.getConnection().getConnectionUserName();
if ((loggedusername != null) && (loggedusername.indexOf('@') >= 0)) {
loggedusername = loggedusername.substring(0, loggedusername.indexOf('@'));
}
if (!username.equalsIgnoreCase(loggedusername)) {
throw new PreconditionFailedException("RunningAs Precondition failed: expected "+username+", was "+loggedusername, changeLog, this);
}
| 254
| 118
| 372
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/SequenceExistsPrecondition.java
|
SequenceExistsPrecondition
|
checkPostgresSequence
|
class SequenceExistsPrecondition extends AbstractPrecondition {
private String catalogName;
private String schemaName;
private String sequenceName;
private static final String SQL_CHECK_POSTGRES_SEQUENCE_EXISTS = "SELECT c.relname FROM pg_class c JOIN pg_namespace ns on c.relnamespace = ns.oid WHERE c.relkind = 'S' AND ns.nspname = ? and c.relname = ?";
public String getCatalogName() {
return catalogName;
}
public void setCatalogName(String catalogName) {
this.catalogName = catalogName;
}
public String getSchemaName() {
return schemaName;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
public String getSequenceName() {
return sequenceName;
}
public void setSequenceName(String sequenceName) {
this.sequenceName = sequenceName;
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public ValidationErrors validate(Database database) {
return new ValidationErrors();
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {
try {
if (database instanceof PostgresDatabase) {
checkPostgresSequence(database, changeLog);
} else {
Schema schema = new Schema(getCatalogName(), getSchemaName());
if (!SnapshotGeneratorFactory.getInstance().has(new Sequence().setName(getSequenceName()).setSchema(schema), database)) {
throw new PreconditionFailedException("Sequence " + database.escapeSequenceName(getCatalogName(), getSchemaName(), getSequenceName()) + " does not exist", changeLog, this);
}
}
} catch (LiquibaseException | SQLException e) {
throw new PreconditionErrorException(e, changeLog, this);
}
}
private void checkPostgresSequence(Database database, DatabaseChangeLog changeLog) throws DatabaseException, SQLException, PreconditionFailedException, PreconditionErrorException {<FILL_FUNCTION_BODY>}
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@Override
public String getName() {
return "sequenceExists";
}
}
|
try (PreparedStatement statement = ((JdbcConnection) database.getConnection()).prepareStatement(SQL_CHECK_POSTGRES_SEQUENCE_EXISTS)) {
statement.setString(1, getSchemaName() != null ? getSchemaName() : database.getDefaultSchemaName());
statement.setString(2, getSequenceName());
try (ResultSet rs = statement.executeQuery()) {
if (!rs.next()) {
throw new PreconditionFailedException("Sequence " + database.escapeSequenceName(getCatalogName(), getSchemaName(), getSequenceName()) + " does not exist", changeLog, this);
}
} catch (SQLException e) {
throw new PreconditionErrorException(e, changeLog, this);
}
}
| 625
| 185
| 810
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/SqlPrecondition.java
|
SqlPrecondition
|
check
|
class SqlPrecondition extends AbstractPrecondition {
private String expectedResult;
private String sql;
public String getExpectedResult() {
return expectedResult;
}
public void setExpectedResult(String expectedResult) {
this.expectedResult = expectedResult;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public ValidationErrors validate(Database database) {
return new ValidationErrors();
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {<FILL_FUNCTION_BODY>}
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@Override
public String getName() {
return "sqlCheck";
}
@Override
public SerializationType getSerializableFieldType(String field) {
if ("sql".equals(field)) {
return SerializationType.DIRECT_VALUE;
}
return super.getSerializableFieldType(field);
}
}
|
try {
Object oResult = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database).queryForObject(new RawSqlStatement(getSql().replaceFirst(";$","")), String.class);
if (oResult == null) {
throw new PreconditionFailedException("No rows returned from SQL Precondition", changeLog, this);
}
String result = oResult.toString();
String expectedResult = getExpectedResult();
if (!expectedResult.equals(result)) {
throw new PreconditionFailedException("SQL Precondition failed. Expected '"+ expectedResult +"' got '"+result+"'", changeLog, this);
}
} catch (DatabaseException e) {
throw new PreconditionErrorException(e, changeLog, this);
}
| 347
| 196
| 543
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/TableExistsPrecondition.java
|
TableExistsPrecondition
|
check
|
class TableExistsPrecondition extends AbstractPrecondition {
private String catalogName;
private String schemaName;
private String tableName;
public String getCatalogName() {
return catalogName;
}
public void setCatalogName(String catalogName) {
this.catalogName = catalogName;
}
public String getSchemaName() {
return schemaName;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public ValidationErrors validate(Database database) {
return new ValidationErrors();
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {<FILL_FUNCTION_BODY>}
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@Override
public String getName() {
return "tableExists";
}
}
|
try {
String correctedTableName = database.correctObjectName(getTableName(), Table.class);
if (!SnapshotGeneratorFactory.getInstance().has(new Table().setName(correctedTableName).setSchema(new Schema(getCatalogName(), getSchemaName())), database)) {
throw new PreconditionFailedException("Table "+database.escapeTableName(getCatalogName(), getSchemaName(), getTableName())+" does not exist", changeLog, this);
}
} catch (PreconditionFailedException e) {
throw e;
} catch (Exception e) {
throw new PreconditionErrorException(e, changeLog, this);
}
| 345
| 162
| 507
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/TableIsEmptyPrecondition.java
|
TableIsEmptyPrecondition
|
validate
|
class TableIsEmptyPrecondition extends AbstractPrecondition {
private String catalogName;
private String schemaName;
private String tableName;
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener) throws PreconditionFailedException, PreconditionErrorException {
try {
TableIsEmptyStatement statement = new TableIsEmptyStatement(getCatalogName(), getSchemaName(), getTableName());
int result = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database).queryForInt(statement);
if (result > 0) {
throw new PreconditionFailedException("Table " + getTableName() + " is not empty.", changeLog, this);
}
} catch (PreconditionFailedException e) {
throw e;
} catch (Exception e) {
throw new PreconditionErrorException(e, changeLog, this);
}
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public ValidationErrors validate(Database database) {<FILL_FUNCTION_BODY>}
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@Override
public String getName() {
return "tableIsEmpty";
}
}
|
ValidationErrors validationErrors = new ValidationErrors();
validationErrors.checkRequiredField("tableName", tableName);
return validationErrors;
| 354
| 38
| 392
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/UniqueConstraintExistsPrecondition.java
|
UniqueConstraintExistsPrecondition
|
check
|
class UniqueConstraintExistsPrecondition extends AbstractPrecondition {
private String catalogName;
private String schemaName;
private String tableName;
private String columnNames;
private String constraintName;
public String getConstraintName() {
return constraintName;
}
public void setConstraintName(String constraintName) {
this.constraintName = constraintName;
}
public String getCatalogName() {
return catalogName;
}
public void setCatalogName(String catalogName) {
this.catalogName = catalogName;
}
public String getSchemaName() {
return schemaName;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getColumnNames() {
return columnNames;
}
public void setColumnNames(String columnNames) {
this.columnNames = columnNames;
}
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@Override
public String getName() {
return "uniqueConstraintExists";
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public ValidationErrors validate(Database database) {
ValidationErrors validationErrors = new ValidationErrors(this);
validationErrors.checkRequiredField("tableName", getTableName());
if (StringUtil.trimToNull(getConstraintName()) == null && StringUtil.trimToNull(getColumnNames()) == null) {
validationErrors.addError("constraintName OR columnNames is required for "+getName());
}
return validationErrors;
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {<FILL_FUNCTION_BODY>}
private List<Column> toColumns(Database database, String columnNames) {
return Arrays.stream(columnNames.split("\\s*,\\s*"))
.map(columnName -> database.correctObjectName(columnName, Column.class))
.map(Column::new)
.collect(Collectors.toList());
}
@Override
public String toString() {
String string = "Unique Constraint Exists Precondition: ";
if (getConstraintName() != null) {
string += getConstraintName();
}
if (tableName != null) {
string += " on "+getTableName();
if (StringUtil.trimToNull(getColumnNames()) != null) {
string += " columns "+getColumnNames();
}
}
return string;
}
}
|
UniqueConstraint example = new UniqueConstraint(
StringUtil.trimToNull(getConstraintName()),
StringUtil.trimToNull(getCatalogName()),
StringUtil.trimToNull(getSchemaName()),
StringUtil.trimToNull(getTableName()));
String columnNames = StringUtil.trimToNull(getColumnNames());
if (columnNames != null) {
example.setColumns(toColumns(database, columnNames));
}
try {
if (!SnapshotGeneratorFactory.getInstance().has(example, database)) {
throw new PreconditionFailedException(String.format("%s does not exist", example), changeLog, this);
}
} catch (DatabaseException | InvalidExampleException e) {
throw new PreconditionErrorException(e, changeLog, this);
}
| 714
| 204
| 918
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/precondition/core/ViewExistsPrecondition.java
|
ViewExistsPrecondition
|
check
|
class ViewExistsPrecondition extends AbstractPrecondition {
private String catalogName;
private String schemaName;
private String viewName;
public String getCatalogName() {
return catalogName;
}
public void setCatalogName(String catalogName) {
this.catalogName = catalogName;
}
public String getSchemaName() {
return schemaName;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
public String getViewName() {
return viewName;
}
public void setViewName(String viewName) {
this.viewName = viewName;
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public ValidationErrors validate(Database database) {
return new ValidationErrors();
}
@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet, ChangeExecListener changeExecListener)
throws PreconditionFailedException, PreconditionErrorException {<FILL_FUNCTION_BODY>}
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@Override
public String getName() {
return "viewExists";
}
}
|
String currentSchemaName;
String currentCatalogName;
try {
currentCatalogName = getCatalogName();
currentSchemaName = getSchemaName();
if (!SnapshotGeneratorFactory.getInstance().has(new View().setName(database.correctObjectName(getViewName(), View.class)).setSchema(new Schema(currentCatalogName, currentSchemaName)), database)) {
throw new PreconditionFailedException("View "+database.escapeTableName(currentCatalogName, currentSchemaName, getViewName())+" does not exist", changeLog, this);
}
} catch (PreconditionFailedException e) {
throw e;
} catch (Exception e) {
throw new PreconditionErrorException(e, changeLog, this);
}
| 346
| 186
| 532
|
<methods>public non-sealed void <init>() ,public java.lang.String getSerializedObjectName() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/report/ChangesetInfo.java
|
ChangesetInfo
|
addAllToPendingChangesetInfoList
|
class ChangesetInfo {
/**
* The number of deployed (aka executed) changesets
*/
private int changesetCount;
/**
* The number of pending (aka skipped) changesets
*/
private int pendingChangesetCount;
private int failedChangesetCount;
private final List<IndividualChangesetInfo> changesetInfoList = new ArrayList<>();
private final List<PendingChangesetInfo> pendingChangesetInfoList = new ArrayList<>();
public void addAllToChangesetInfoList(List<ChangeSet> changeSets, boolean isRollback) {
if (changeSets != null) {
for (ChangeSet deployedChangeSet : changeSets) {
String changesetOutcome;
if (isRollback) {
changesetOutcome = deployedChangeSet.getRollbackExecType() == null ? "" : deployedChangeSet.getRollbackExecType().toString();
} else {
changesetOutcome = deployedChangeSet.getExecType() == null ? "" : deployedChangeSet.getExecType().toString();
}
boolean success = true;
// If the changeset fails, the exec type it has is null, but if there's an error message, then it failed, and we want to indicate that it failed.
String errorMsg = deployedChangeSet.getErrorMsg();
if (StringUtil.isNotEmpty(errorMsg)) {
changesetOutcome = ChangeSet.ExecType.FAILED.value;
success = false;
}
// This list assumes that the generated sql is only related to the current operation's generated sql.
List<String> generatedSql = deployedChangeSet.getGeneratedSql()
.stream()
.filter(sql -> sql != null && !sql.isEmpty())
.collect(Collectors.toList());
changesetInfoList.add(new IndividualChangesetInfo(
changesetInfoList.size() + 1,
deployedChangeSet.getAuthor(),
deployedChangeSet.getId(),
deployedChangeSet.getFilePath(),
deployedChangeSet.getComments(),
success,
changesetOutcome,
errorMsg,
deployedChangeSet.getLabels() == null ? null : deployedChangeSet.getLabels().toString(),
deployedChangeSet.getContextFilter() == null ? null : deployedChangeSet.getContextFilter().getOriginalString(),
buildAttributesString(deployedChangeSet),
generatedSql
));
}
}
}
private static List<String> buildAttributesString(ChangeSet changeSet) {
List<String> attributes = new ArrayList<>();
if (changeSet.getFailOnError() != null && !changeSet.getFailOnError()) {
attributes.add("failOnError = false");
}
if (changeSet.isAlwaysRun()) {
attributes.add("alwaysRun");
}
if (changeSet.isRunOnChange()) {
attributes.add("runOnChange");
}
if (!changeSet.isRunInTransaction()) {
attributes.add("runInTransaction = false");
}
if (StringUtil.isNotEmpty(changeSet.getRunOrder())) {
attributes.add("runOrder = " + changeSet.getRunOrder());
}
if (StringUtil.isNotEmpty(changeSet.getRunWith())) {
attributes.add("runWith = " + changeSet.getRunWith());
}
if (StringUtil.isNotEmpty(changeSet.getRunWithSpoolFile())) {
attributes.add("runWithSpoolFile = " + changeSet.getRunWithSpoolFile());
}
if (!CollectionUtil.createIfNull(changeSet.getDbmsSet()).isEmpty()) {
attributes.add("dbms = " + StringUtil.join(changeSet.getDbmsSet(), ", "));
}
return attributes;
}
/**
* Map all changeset status and reason for skipping to a PendingChangesetInfo object and add to the list.
*
* @param pendingChanges the map of ChangeSetStatus and their reason for being skipped.
*/
public void addAllToPendingChangesetInfoList(Map<ChangeSet, String> pendingChanges) {<FILL_FUNCTION_BODY>}
}
|
if (pendingChanges != null) {
pendingChanges.forEach((changeSet, reason) -> {
PendingChangesetInfo pendingChangesetInfo = new PendingChangesetInfo(
changeSet.getAuthor(),
changeSet.getId(),
changeSet.getFilePath(),
changeSet.getComments(),
changeSet.getLabels() == null ? null : changeSet.getLabels().toString(),
changeSet.getContextFilter() == null ? null : changeSet.getContextFilter().getOriginalString(),
reason,
changeSet);
pendingChangesetInfoList.add(pendingChangesetInfo);
});
}
| 1,050
| 166
| 1,216
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/report/DatabaseInfo.java
|
DatabaseInfo
|
getVisibleUrl
|
class DatabaseInfo {
private static final int CONNECTION_URL_MAX_LENGTH = 128;
public static final List<String> DB_URL_VISIBLE_KEYS = Arrays.asList("servername", "database", "databaseName");
private String databaseType;
private String version;
private String databaseUrl;
/**
* Used in mustache template.
*
* @return the visible url string.
*/
public String getVisibleDatabaseUrl() {
return getVisibleUrl(this.databaseUrl);
}
/**
* Builds a simpler version of the jdbc url if the url is longer than {@link CONNECTION_URL_MAX_LENGTH}
* If the original url was "jdbc:sqlserver://localhost:1433;someParam=nothing;databaseName=blah;someParam2=nothing;someParam3=nothing;..." (greater than CONNECTION_URL_MAX_LENGTH chars)
* will be shuffled to read "jdbc:sqlserver://localhost:1433;databaseName=blah..." for presentation
*
* @param originalUrl the original jdbc url
* @return the modified url if longer than {@link CONNECTION_URL_MAX_LENGTH}
*/
protected String getVisibleUrl(String originalUrl) {<FILL_FUNCTION_BODY>}
/**
* If the url is longer than 128 characters, remove the remaining characters
*
* @param url the url to modify
* @return the modified url if over 128 characters
*/
private String hideConnectionUrlLength(String url) {
if (url.length() >= CONNECTION_URL_MAX_LENGTH) {
return url.substring(0, 127);
}
return url;
}
private String appendEllipsisIfDifferent(String originalUrl, String maybeModifiedUrl) {
if (!originalUrl.equalsIgnoreCase(maybeModifiedUrl)) {
return String.format("%s...", maybeModifiedUrl);
}
return originalUrl;
}
}
|
if (originalUrl == null) {
return "";
}
final String modifiedUrl = originalUrl.length() >= CONNECTION_URL_MAX_LENGTH ? handleSqlServerDbUrlParameters(DB_URL_VISIBLE_KEYS, originalUrl) : originalUrl;
return appendEllipsisIfDifferent(originalUrl, hideConnectionUrlLength(modifiedUrl));
| 520
| 94
| 614
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/report/RollbackReportParameters.java
|
ChangesetDetails
|
setRollbackException
|
class ChangesetDetails {
private String id;
private String author;
private String path;
}
public void setRollbackException(ExceptionDetails exceptionDetails) {<FILL_FUNCTION_BODY>
|
// Set the exception similar to how it is formatted in the console.
// The double newline is intentional.
this.getOperationInfo().setException(String.format("%s\n%s\n%s\n\n%s",
exceptionDetails.getFormattedPrimaryException(),
exceptionDetails.getFormattedPrimaryExceptionReason(),
exceptionDetails.getFormattedPrimaryExceptionSource(),
// Intentionally not using the formatted version for this last item.
exceptionDetails.getPrimaryExceptionReason()));
| 56
| 122
| 178
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/resource/AbstractPathResourceAccessor.java
|
AbstractPathResourceAccessor
|
search
|
class AbstractPathResourceAccessor extends AbstractResourceAccessor {
abstract protected Path getRootPath();
@Override
public String toString() {
return getClass().getName() + " (" + getRootPath() + ")";
}
@Override
public List<String> describeLocations() {
return Collections.singletonList(getRootPath().toString());
}
@Override
public List<Resource> getAll(String path) throws IOException {
if (path == null) {
throw new IllegalArgumentException("Path must not be null");
}
final List<Resource> returnList = new ArrayList<>();
Logger log = Scope.getCurrentScope().getLog(getClass());
path = standardizePath(path);
if (path == null) {
return returnList;
}
Path finalPath = getRootPath().resolve(path);
if (Files.exists(finalPath)) {
returnList.add(createResource(finalPath, path));
} else {
log.fine("Path " + path + " in " + getRootPath() + " does not exist (" + this + ")");
}
return returnList;
}
private String standardizePath(String path) {
try {
//
// Flip the separators to Linux-style and replace the first separator
// If then root path is the absolute path for Linux or Windows then return that result
//
String rootPath = getRootPath().toString();
String result = new File(path).toPath().normalize().toString().replace("\\", "/").replaceFirst("^/", "");
if (rootPath.equals("/") || rootPath.equals("\\")) {
return result;
}
//
// Strip off any Windows drive prefix and return the result
//
return result.replaceFirst("^\\w:/","");
} catch (InvalidPathException e) {
Scope.getCurrentScope().getLog(getClass()).warning("Failed to standardize path " + path, e);
return path;
}
}
@Override
public List<Resource> search(String startPath, SearchOptions searchOptions) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public List<Resource> search(String startPath, boolean recursive) throws IOException {
SearchOptions searchOptions = new SearchOptions();
searchOptions.setRecursive(recursive);
return search(startPath, searchOptions);
}
protected abstract Resource createResource(Path file, String pathToAdd);
}
|
final int minDepth = searchOptions.getMinDepth();
final int maxDepth = searchOptions.getMaxDepth();
final boolean endsWithFilterIsSet = searchOptions.endsWithFilterIsSet();
final String endsWithFilter = searchOptions.getEndsWithFilter();
if (startPath == null) {
throw new IllegalArgumentException("Path must not be null");
}
startPath = startPath
.replaceFirst("^file:/+", "")
.replaceFirst("^/", "");
Logger log = Scope.getCurrentScope().getLog(getClass());
Path rootPath = getRootPath();
Path basePath = rootPath.resolve(startPath);
final List<Resource> returnSet = new ArrayList<>();
if (!Files.exists(basePath)) {
log.fine("Path " + startPath + " in " + rootPath + " does not exist (" + this + ")");
return returnSet;
}
if (!Files.isDirectory(basePath)) {
throw new IOException("'" + startPath + "' is a file, not a directory");
}
SimpleFileVisitor<Path> fileVisitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (attrs.isRegularFile() && meetsSearchCriteria(file)) {
addToReturnList(file);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
private boolean meetsSearchCriteria(Path file) {
final int depth = file.getParent().getNameCount() - rootPath.getNameCount();
if (depth < minDepth) {
return false;
}
if (endsWithFilterIsSet) {
if (!file.toString().toLowerCase().endsWith(endsWithFilter.toLowerCase())) {
return false;
}
}
return true;
}
private void addToReturnList(Path file) {
String pathToAdd = rootPath.relativize(file).normalize().toString().replace("\\", "/");
pathToAdd = pathToAdd.replaceFirst("/$", "");
returnSet.add(createResource(file, pathToAdd));
}
};
Files.walkFileTree(basePath, Collections.singleton(FileVisitOption.FOLLOW_LINKS), maxDepth, fileVisitor);
return returnSet;
| 633
| 643
| 1,276
|
<methods>public non-sealed void <init>() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/resource/AbstractResource.java
|
AbstractResource
|
equals
|
class AbstractResource implements Resource {
private final String path;
private final URI uri;
public AbstractResource(String path, URI uri) {
this.path = path
.replace("\\", "/")
.replaceFirst("^classpath\\*?:", "")
.replaceFirst("^/", "");
if (uri != null) {
this.uri = uri.normalize();
} else {
this.uri = null;
}
}
@Override
public String getPath() {
return path;
}
@Override
public URI getUri() {
return uri;
}
@Override
public boolean isWritable() {
return false;
}
@Override
public OutputStream openOutputStream(OpenOptions openOptions) throws IOException {
if (!isWritable()) {
throw new IOException("Read only");
}
throw new IOException("Write not implemented");
}
@Override
public String toString() {
return getPath();
}
@Override
public int hashCode() {
return this.getUri().hashCode();
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
/**
* Convenience method for computing the relative path in {@link #resolve(String)} implementations
*/
protected String resolvePath(String other) {
if (getPath().endsWith("/")) {
return getPath() + other;
}
return getPath() + "/" + other;
}
/**
* Convenience method for computing the relative path in {@link #resolveSibling(String)} implementations.
*/
protected String resolveSiblingPath(String other) {
if (getPath().contains("/")) {
return getPath().replaceFirst("/[^/]*$", "") + "/" + other;
} else {
return "/" + other;
}
}
}
|
if (!(obj instanceof Resource)) {
return false;
}
return this.getUri().equals(((Resource) obj).getUri());
| 498
| 39
| 537
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/resource/ClassLoaderResourceAccessor.java
|
ClassLoaderResourceAccessor
|
search
|
class ClassLoaderResourceAccessor extends AbstractResourceAccessor {
private final ClassLoader classLoader;
private CompositeResourceAccessor additionalResourceAccessors;
protected SortedSet<String> description;
public ClassLoaderResourceAccessor() {
this(Thread.currentThread().getContextClassLoader());
}
public ClassLoaderResourceAccessor(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
public List<String> describeLocations() {
init();
return additionalResourceAccessors.describeLocations();
}
@Override
public void close() throws Exception {
if (additionalResourceAccessors != null) {
additionalResourceAccessors.close();
}
}
/**
* Performs the configuration of this resourceAccessor.
* Not done in the constructor for performance reasons, but can be called at the beginning of every public method.
*/
protected synchronized void init() {
if (additionalResourceAccessors == null) {
this.description = new TreeSet<>();
this.additionalResourceAccessors = new CompositeResourceAccessor();
configureAdditionalResourceAccessors(classLoader);
}
}
/**
* The classloader search logic in {@link #search(String, boolean)} does not handle jar files well.
* This method is called by that method to configure an internal {@link ResourceAccessor} with paths to search.
*/
protected void configureAdditionalResourceAccessors(ClassLoader classLoader) {
if (classLoader instanceof URLClassLoader) {
final URL[] urls = ((URLClassLoader) classLoader).getURLs();
if (urls != null) {
PathHandlerFactory pathHandlerFactory = Scope.getCurrentScope().getSingleton(PathHandlerFactory.class);
for (URL url : urls) {
try {
if (url.getProtocol().equals("file")) {
additionalResourceAccessors.addResourceAccessor(pathHandlerFactory.getResourceAccessor(url.toExternalForm()));
}
} catch (FileNotFoundException e) {
//classloaders often have invalid paths specified on purpose. Just log them as fine level.
Scope.getCurrentScope().getLog(getClass()).fine("Classloader URL " + url.toExternalForm() + " does not exist", e);
} catch (Throwable e) {
Scope.getCurrentScope().getLog(getClass()).warning("Cannot handle classloader url " + url.toExternalForm() + ": " + e.getMessage()+". Operations that need to list files from this location may not work as expected", e);
}
}
}
}
final ClassLoader parent = classLoader.getParent();
if (parent != null) {
configureAdditionalResourceAccessors(parent);
}
}
@Override
public List<Resource> search(String path, SearchOptions searchOptions) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public List<Resource> search(String path, boolean recursive) throws IOException {
SearchOptions searchOptions = new SearchOptions();
searchOptions.setRecursive(recursive);
return search(path, searchOptions);
}
@Override
public List<Resource> getAll(String path) throws IOException {
//using a hash because sometimes the same resource gets included multiple times.
LinkedHashSet<Resource> returnList = new LinkedHashSet<>();
path = path.replace("\\", "/").replaceFirst("^/", "");
Enumeration<URL> all = classLoader.getResources(path);
try {
while (all.hasMoreElements()) {
URI uri = all.nextElement().toURI();
if (uri.getScheme().equals("file")) {
returnList.add(new PathResource(path, Paths.get(uri)));
} else {
returnList.add(new URIResource(path, uri));
}
}
} catch (URISyntaxException e) {
throw new IOException(e.getMessage(), e);
}
if (returnList.size() == 0) {
return null;
}
return new ArrayList<>(returnList);
}
}
|
init();
final LinkedHashSet<Resource> returnList = new LinkedHashSet<>();
PathHandlerFactory pathHandlerFactory = Scope.getCurrentScope().getSingleton(PathHandlerFactory.class);
final Enumeration<URL> resources;
try {
resources = classLoader.getResources(path);
} catch (IOException e) {
throw new IOException("Cannot list resources in path " + path + ": " + e.getMessage(), e);
}
while (resources.hasMoreElements()) {
final URL url = resources.nextElement();
String urlExternalForm = url.toExternalForm();
urlExternalForm = urlExternalForm.replaceFirst(Pattern.quote(path) + "/?$", "");
try (ResourceAccessor resourceAccessor = pathHandlerFactory.getResourceAccessor(urlExternalForm)) {
returnList.addAll(resourceAccessor.search(path, searchOptions));
} catch (Exception e) {
throw new IOException(e.getMessage(), e);
}
}
returnList.addAll(additionalResourceAccessors.search(path, searchOptions));
return new ArrayList<>(returnList);
| 1,037
| 286
| 1,323
|
<methods>public non-sealed void <init>() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/resource/CompositeResourceAccessor.java
|
CompositeResourceAccessor
|
close
|
class CompositeResourceAccessor extends AbstractResourceAccessor {
private final List<ResourceAccessor> resourceAccessors;
public CompositeResourceAccessor(ResourceAccessor... resourceAccessors) {
this.resourceAccessors = new ArrayList<>(); //Arrays.asList(CollectionUtil.createIfNull(resourceAccessors));
this.resourceAccessors.addAll(Arrays.asList(resourceAccessors));
}
public CompositeResourceAccessor(Collection<ResourceAccessor> resourceAccessors) {
this.resourceAccessors = new ArrayList<>(resourceAccessors);
}
@Override
public void close() throws Exception {<FILL_FUNCTION_BODY>}
public CompositeResourceAccessor addResourceAccessor(ResourceAccessor resourceAccessor) {
this.resourceAccessors.add(resourceAccessor);
return this;
}
public void removeResourceAccessor(ResourceAccessor resourceAccessor) {
this.resourceAccessors.remove(resourceAccessor);
}
@Override
public List<Resource> search(String path, SearchOptions searchOptions) throws IOException {
LinkedHashSet<Resource> returnList = new LinkedHashSet<>();
for (ResourceAccessor accessor : resourceAccessors) {
returnList.addAll(CollectionUtil.createIfNull(accessor.search(path, searchOptions)));
}
return new ArrayList<>(returnList);
}
@Override
public List<Resource> search(String path, boolean recursive) throws IOException {
LinkedHashSet<Resource> returnList = new LinkedHashSet<>();
for (ResourceAccessor accessor : resourceAccessors) {
returnList.addAll(CollectionUtil.createIfNull(accessor.search(path, recursive)));
}
return new ArrayList<>(returnList);
}
@Override
public List<Resource> getAll(String path) throws IOException {
LinkedHashSet<Resource> returnList = new LinkedHashSet<>();
for (ResourceAccessor accessor : resourceAccessors) {
returnList.addAll(CollectionUtil.createIfNull(accessor.getAll(path)));
}
return new ArrayList<>(returnList);
}
@Override
public List<String> describeLocations() {
LinkedHashSet<String> returnSet = new LinkedHashSet<>();
for (ResourceAccessor accessor : resourceAccessors) {
returnSet.addAll(CollectionUtil.createIfNull(accessor.describeLocations()));
}
return new ArrayList<>(returnSet);
}
}
|
for (ResourceAccessor accessor : resourceAccessors) {
try {
accessor.close();
} catch (Exception e) {
Scope.getCurrentScope().getLog(getClass()).fine("Error closing " + accessor.getClass().getName() + ": " + e.getMessage(), e);
}
}
| 629
| 85
| 714
|
<methods>public non-sealed void <init>() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/resource/DirectoryPathHandler.java
|
DirectoryPathHandler
|
getPriority
|
class DirectoryPathHandler extends AbstractPathHandler {
/**
* Returns {@link #PRIORITY_DEFAULT} for all paths except for ones that are for a non-"file:" protocol.
*/
@Override
public int getPriority(String root) {<FILL_FUNCTION_BODY>}
@Override
public ResourceAccessor getResourceAccessor(String root) throws FileNotFoundException {
root = root
.replace("file:", "")
.replace("\\", "/");
try {
// Because this method is passed a URL from liquibase.resource.ClassLoaderResourceAccessor.configureAdditionalResourceAccessors,
// it should be decoded from its URL-encoded form.
root = decode(root, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
Scope.getCurrentScope().getLog(getClass()).fine("Failed to decode path " + root + "; continuing without decoding.", e);
}
return new DirectoryResourceAccessor(new File(root));
}
@Override
public Resource getResource(String path) throws IOException {
return new PathResource(path, Paths.get(path));
}
@Override
public OutputStream createResource(String path) throws IOException {
Path path1 = Paths.get(path);
// Need to create parent directories, because Files.newOutputStream won't create them.
Path parent = path1.getParent();
if (parent != null && !Files.exists(parent)) {
Files.createDirectories(parent);
}
return Files.newOutputStream(path1, StandardOpenOption.CREATE_NEW);
}
}
|
if (root == null) {
return PRIORITY_NOT_APPLICABLE;
}
if (root.startsWith("/") || !root.contains(":")) {
return PRIORITY_DEFAULT;
}
if (root.startsWith("file:") || root.matches("^[A-Za-z]:.*")) {
return PRIORITY_DEFAULT;
} else {
return PRIORITY_NOT_APPLICABLE;
}
| 411
| 129
| 540
|
<methods>public non-sealed void <init>() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/resource/FileSystemResourceAccessor.java
|
FileSystemResourceAccessor
|
addRootPath
|
class FileSystemResourceAccessor extends CompositeResourceAccessor {
/**
* Creates a FileSystemResourceAccessor with the given directories/files as the roots.
*/
public FileSystemResourceAccessor(File... baseDirsAndFiles) {
for (File base : CollectionUtil.createIfNull(baseDirsAndFiles)) {
addRootPath(base);
}
}
/**
* @deprecated use {@link FileSystemResourceAccessor#FileSystemResourceAccessor(File...)}
*/
public FileSystemResourceAccessor(String file) {
this(new File(file));
}
protected void addRootPath(Path path) {
if (path == null) {
return;
}
addRootPath(path.toFile());
}
protected void addRootPath(File base) {<FILL_FUNCTION_BODY>}
}
|
if (base == null) {
return;
}
try {
if (!base.exists()) {
Scope.getCurrentScope().getLog(getClass()).warning("Non-existent path: " + base.getAbsolutePath());
} else if (base.isDirectory()) {
addResourceAccessor(new DirectoryResourceAccessor(base));
} else if (base.getName().endsWith(".jar") || base.getName().toLowerCase().endsWith("zip")) {
addResourceAccessor(new ZipResourceAccessor(base));
} else {
throw new IllegalArgumentException(base.getAbsolutePath() + " must be a directory, jar or zip");
}
} catch (FileNotFoundException e) {
throw new UnexpectedLiquibaseException(e);
}
| 221
| 200
| 421
|
<methods>public transient void <init>(liquibase.resource.ResourceAccessor[]) ,public void <init>(Collection<liquibase.resource.ResourceAccessor>) ,public liquibase.resource.CompositeResourceAccessor addResourceAccessor(liquibase.resource.ResourceAccessor) ,public void close() throws java.lang.Exception,public List<java.lang.String> describeLocations() ,public List<liquibase.resource.Resource> getAll(java.lang.String) throws java.io.IOException,public void removeResourceAccessor(liquibase.resource.ResourceAccessor) ,public List<liquibase.resource.Resource> search(java.lang.String, liquibase.resource.ResourceAccessor.SearchOptions) throws java.io.IOException,public List<liquibase.resource.Resource> search(java.lang.String, boolean) throws java.io.IOException<variables>private final non-sealed List<liquibase.resource.ResourceAccessor> resourceAccessors
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/resource/InputStreamList.java
|
InputStreamList
|
alreadySaw
|
class InputStreamList implements Iterable<InputStream>, AutoCloseable {
private final LinkedHashMap<URI, InputStream> streams = new LinkedHashMap<>();
public InputStreamList() {
}
public InputStreamList(URI uri, InputStream stream) {
this.streams.put(uri, stream);
}
public boolean add(URI uri, InputStream inputStream) {
Logger log = Scope.getCurrentScope().getLog(getClass());
boolean duplicate = alreadySaw(uri);
if (duplicate) {
log.fine("Closing duplicate stream for " + uri);
try {
inputStream.close();
} catch (IOException e) {
log.warning("Cannot close stream for " + uri, e);
}
} else {
streams.put(uri, inputStream);
}
return duplicate;
}
protected boolean alreadySaw(URI uri) {<FILL_FUNCTION_BODY>}
public void addAll(InputStreamList streams) {
if (streams == null) {
return;
}
for (Map.Entry<URI, InputStream> entry : streams.streams.entrySet()) {
add(entry.getKey(), entry.getValue());
}
}
/**
* Close the streams in this collection.
*/
@Override
public void close() throws IOException {
for (InputStream stream : this) {
try {
stream.close();
} catch (IOException e) {
Scope.getCurrentScope().getLog(getClass()).severe("Error closing stream. Logging error and continuing", e);
}
}
}
@Override
public Iterator<InputStream> iterator() {
return streams.values().iterator();
}
@Override
public void forEach(Consumer<? super InputStream> action) {
streams.values().forEach(action);
}
@Override
public Spliterator<InputStream> spliterator() {
return streams.values().spliterator();
}
public int size() {
return streams.size();
}
public boolean isEmpty() {
return streams.isEmpty();
}
public List<URI> getURIs() {
return new ArrayList<>(streams.keySet());
}
}
|
if (streams.isEmpty()) {
return false;
}
if (streams.containsKey(uri)) {
return true;
}
//standardize url strings between file:// and jar:file:
String thisUriStringBase = uri.toString()
.replaceFirst("^file://", "")
.replaceFirst("^jar:file:", "")
.replaceFirst("!/", "!");
for (URI seenURI : streams.keySet()) {
if (seenURI.toString()
.replaceFirst("^file://", "")
.replaceFirst("^jar:file:", "")
.replaceFirst("!/", "!")
.equals(thisUriStringBase)) {
return true;
}
}
return false;
| 579
| 196
| 775
|
<no_super_class>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/resource/PathHandlerFactory.java
|
PathHandlerFactory
|
getResourceAccessor
|
class PathHandlerFactory extends AbstractPluginFactory<PathHandler> {
private PathHandlerFactory() {
}
@Override
protected Class<PathHandler> getPluginClass() {
return PathHandler.class;
}
@Override
protected int getPriority(PathHandler obj, Object... args) {
return obj.getPriority((String) args[0]);
}
/**
* Creates a {@link ResourceAccessor} for the given path.
*/
public ResourceAccessor getResourceAccessor(String root) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Creates a new resource at the specified path and returns an OutputStream for writing to it.
*
* @throws java.nio.file.FileAlreadyExistsException if the file already exists
* @throws IOException if the path cannot be written to
*/
public OutputStream createResource(String resourcePath) throws IOException {
final PathHandler plugin = getPlugin(resourcePath);
if (plugin == null) {
throw new IOException("Cannot parse resource location: '" + resourcePath + "'");
}
return plugin.createResource(resourcePath);
}
/**
* Return the resource for the given path.
*
* @return A resource, regardless of whether it exists or not.
* @throws IOException if the path cannot be understood or if there is a problem parsing the path
* @throws IOException if the path exists as both a direct resourcePath and also in the resourceAccessor (if included). Unless {@link liquibase.GlobalConfiguration#DUPLICATE_FILE_MODE} overrides that behavior.
*/
@SuppressWarnings("java:S2095")
public Resource getResource(String resourcePath) throws IOException {
final PathHandler plugin = getPlugin(resourcePath);
if (plugin == null) {
throw new IOException("Cannot parse resource location: '" + resourcePath + "'");
}
return plugin.getResource(resourcePath);
}
/**
* Returns the outputStream from {@link #getResource(String)} if it exists, and the outputStream from {@link #createResource(String)} if it does not.
*
* @return null if resourcePath does not exist and createIfNotExists is false
* @throws IOException if there is an error opening the stream
*
* @deprecated use {@link #openResourceOutputStream(String, OpenOptions)}
*/
@Deprecated
public OutputStream openResourceOutputStream(String resourcePath, boolean createIfNotExists) throws IOException {
return openResourceOutputStream(resourcePath, new OpenOptions().setCreateIfNeeded(createIfNotExists));
}
/**
* Returns the outputStream from {@link #getResource(String)}, using settings from the passed {@link OpenOptions}.
*
* @return null if resourcePath does not exist and {@link OpenOptions#isCreateIfNeeded()} is false
* @throws IOException if there is an error opening the stream
*/
public OutputStream openResourceOutputStream(String resourcePath, OpenOptions openOptions) throws IOException {
Resource resource = getResource(resourcePath);
if (!resource.exists()) {
if (openOptions.isCreateIfNeeded()) {
return createResource(resourcePath);
} else {
return null;
}
}
return resource.openOutputStream(openOptions);
}
/**
* Adapts a resource found by the PathHandlerFactory to the ResourceAccessor interface so it can be used
* with the standard "duplicate file logic" in the ResourceAccessors
*
*/
private static class FoundResourceAccessor implements ResourceAccessor {
private final Resource foundResource;
private final String location;
public FoundResourceAccessor(String location, Resource foundResource) {
this.location = location;
this.foundResource = foundResource;
}
@Override
public List<Resource> search(String path, SearchOptions searchOptions) throws IOException {
throw new UnexpectedLiquibaseException("Method not implemented");
}
@Override
public List<Resource> search(String path, boolean recursive) throws IOException {
throw new UnexpectedLiquibaseException("Method not implemented");
}
@Override
public List<Resource> getAll(String path) throws IOException {
if (foundResource == null || !foundResource.exists()) {
return null;
}
return Collections.singletonList(foundResource);
}
@Override
public List<String> describeLocations() {
return Collections.singletonList(location);
}
@Override
public void close() throws Exception {
}
}
}
|
final PathHandler plugin = getPlugin(root);
if (plugin == null) {
throw new IOException("Cannot parse resource location: '" + root + "'");
}
return plugin.getResourceAccessor(root);
| 1,140
| 56
| 1,196
|
<methods>public synchronized void register(liquibase.resource.PathHandler) <variables>private Collection<liquibase.resource.PathHandler> allInstances
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/resource/PathResource.java
|
PathResource
|
openOutputStream
|
class PathResource extends AbstractResource {
private final Path path;
public PathResource(String logicalPath, Path path) {
super(logicalPath, path.normalize().toUri());
this.path = path.normalize();
}
@SuppressWarnings("java:S2095")
@Override
public InputStream openInputStream() throws IOException {
if (!Files.exists(this.path)) {
throw new FileNotFoundException(this.path + " does not exist");
} else if (Files.isDirectory(this.path)) {
throw new FileNotFoundException(this.path + " is a directory");
} else {
InputStream stream = Files.newInputStream(this.path);
if (this.path.getFileName().toString().toLowerCase().endsWith(".gz")) {
stream = new GZIPInputStream(stream);
}
return stream;
}
}
@Override
public boolean exists() {
return Files.exists(path);
}
@Override
public Resource resolve(String other) {
return new PathResource(resolvePath(other), path.resolve(other));
}
@Override
public Resource resolveSibling(String other) {
return new PathResource(resolveSiblingPath(other), path.resolveSibling(other));
}
@Override
public boolean isWritable() {
return !Files.isDirectory(this.path) && Files.isWritable(path);
}
@Override
public OutputStream openOutputStream(OpenOptions openOptions) throws IOException {<FILL_FUNCTION_BODY>}
}
|
if (!exists()) {
if (openOptions.isCreateIfNeeded()) {
Path parent = path.getParent();
if (parent != null && !parent.toFile().exists()) {
boolean mkdirs = parent.toFile().mkdirs();
if (!mkdirs) {
Scope.getCurrentScope().getLog(getClass()).warning("Failed to create parent directories for file " + path);
}
}
} else {
throw new IOException("File " + this.getUri() + " does not exist");
}
}
if (Files.isDirectory(this.path)) {
throw new FileNotFoundException(this.getPath() + " is a directory");
} else {
List<StandardOpenOption> options = new ArrayList<>();
if (openOptions.isCreateIfNeeded()) {
options.add(StandardOpenOption.CREATE);
}
if (openOptions.isTruncate()) {
options.addAll(Arrays.asList(StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE));
} else {
options.add(StandardOpenOption.APPEND);
}
return Files.newOutputStream(this.path, options.toArray(new OpenOption[0]));
}
| 409
| 321
| 730
|
<methods>public void <init>(java.lang.String, java.net.URI) ,public boolean equals(java.lang.Object) ,public java.lang.String getPath() ,public java.net.URI getUri() ,public int hashCode() ,public boolean isWritable() ,public java.io.OutputStream openOutputStream(liquibase.resource.OpenOptions) throws java.io.IOException,public java.lang.String toString() <variables>private final non-sealed java.lang.String path,private final non-sealed java.net.URI uri
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/resource/URIResource.java
|
URIResource
|
resolveSibling
|
class URIResource extends AbstractResource {
public URIResource(String path, URI uri) {
super(path, uri);
}
/**
* Cannot determine if the URI exists, return true
*/
@Override
public boolean exists() {
return true;
}
@Override
public Resource resolve(String other) {
return new URIResource(resolvePath(other), URI.create(getUri().toString() + "/" + other));
}
@Override
public Resource resolveSibling(String other) {<FILL_FUNCTION_BODY>}
@Override
public InputStream openInputStream() throws IOException {
return getUri().toURL().openStream();
}
}
|
return new URIResource(resolveSiblingPath(other), URI.create(getUri().toString().replaceFirst("/[^/]*$", "") + "/" + other));
| 179
| 45
| 224
|
<methods>public void <init>(java.lang.String, java.net.URI) ,public boolean equals(java.lang.Object) ,public java.lang.String getPath() ,public java.net.URI getUri() ,public int hashCode() ,public boolean isWritable() ,public java.io.OutputStream openOutputStream(liquibase.resource.OpenOptions) throws java.io.IOException,public java.lang.String toString() <variables>private final non-sealed java.lang.String path,private final non-sealed java.net.URI uri
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/resource/ZipPathHandler.java
|
ZipPathHandler
|
getResourceAccessor
|
class ZipPathHandler extends AbstractPathHandler {
/**
* Returns {@link #PRIORITY_SPECIALIZED} for all "jar:file:" or files that end in ".jar" or ".zip"
*/
@Override
public int getPriority(String root) {
if (root == null) {
return PRIORITY_NOT_APPLICABLE;
}
if (root.toLowerCase().endsWith(".zip") || root.toLowerCase().endsWith(".jar")) {
return PRIORITY_SPECIALIZED;
}
if (root.startsWith("jar:") && root.endsWith("!/")) { //only can handle `jar:` urls for the entire jar
return PRIORITY_SPECIALIZED;
}
return PRIORITY_NOT_APPLICABLE;
}
@Override
public ResourceAccessor getResourceAccessor(String root) throws FileNotFoundException {<FILL_FUNCTION_BODY>}
@Override
public Resource getResource(String path) throws IOException {
return new PathResource(path, Paths.get(path));
}
@Override
public OutputStream createResource(String path) throws IOException {
return Files.newOutputStream(Paths.get(path), StandardOpenOption.CREATE_NEW);
}
}
|
int startIndex = root.startsWith("jar:") ? 4 : 0;
int endIndex = root.lastIndexOf('!');
root = root.substring(startIndex, endIndex > 4 ? endIndex : root.length());
if (root.matches("^\\w\\w+:.*")) {
String[] paths = root.split("!");
Path rootPath = Paths.get(URI.create(paths[0]));
// check for embedded jar files
if (paths.length > 1) {
return new ZipResourceAccessor(rootPath, Arrays.copyOfRange(paths, 1, paths.length));
}
else {
return new ZipResourceAccessor(rootPath);
}
}
return new ZipResourceAccessor(new File(root));
| 339
| 206
| 545
|
<methods>public non-sealed void <init>() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/resource/ZipResourceAccessor.java
|
ZipResourceAccessor
|
toString
|
class ZipResourceAccessor extends AbstractPathResourceAccessor {
private FileSystem fileSystem;
/**
* Creates a FileSystemResourceAccessor with the given directories/files as the roots.
*/
public ZipResourceAccessor(File file) throws FileNotFoundException {
this(file.toPath());
}
public ZipResourceAccessor(Path file) throws FileNotFoundException {
this(file, new String[0]);
}
protected ZipResourceAccessor(Path file, String[] embeddedPaths) throws FileNotFoundException {
if (file == null) {
throw new IllegalArgumentException("File must not be null");
}
Scope.getCurrentScope().getLog(getClass()).fine("Creating resourceAccessor for file " + file);
if (!Files.exists(file)) {
throw new FileNotFoundException("Non-existent file: " + file.toAbsolutePath());
}
if (!Files.isRegularFile(file)) {
throw new IllegalArgumentException("Not a regular file: " + file.toAbsolutePath());
}
String lowerCaseName = file.toString().toLowerCase();
if (!(lowerCaseName.endsWith(".jar") || lowerCaseName.endsWith(".zip"))) {
throw new IllegalArgumentException("Not a jar or zip file: " + file.toAbsolutePath());
}
URI finalUri = URI.create("jar:" + file.toUri());
try {
try {
this.fileSystem = FileSystems.getFileSystem(finalUri);
} catch (FileSystemNotFoundException e) {
try {
this.fileSystem = FileSystems.newFileSystem(finalUri, Collections.emptyMap(), Scope.getCurrentScope().getClassLoader());
} catch (FileSystemAlreadyExistsException ex) {
this.fileSystem = FileSystems.getFileSystem(finalUri);
}
}
for (String embeddedPath : embeddedPaths) {
Path innerPath = fileSystem.getPath(embeddedPath);
try {
this.fileSystem = FileSystems.newFileSystem(innerPath, null);
} catch (FileSystemNotFoundException e) {
this.fileSystem = FileSystems.newFileSystem(innerPath, Scope.getCurrentScope().getClassLoader());
}
}
} catch (Throwable e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
@Override
public void close() throws Exception {
//can't close the filesystem because they often get reused and/or are being used by other things
}
@Override
protected Path getRootPath() {
return this.fileSystem.getPath("/");
}
@Override
protected Resource createResource(Path file, String pathToAdd) {
return new PathResource(pathToAdd, file);
}
@Override
public List<String> describeLocations() {
return Collections.singletonList(fileSystem.toString());
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getName() + " (" + getRootPath() + ") (" + fileSystem.toString() + ")";
| 766
| 31
| 797
|
<methods>public non-sealed void <init>() ,public List<java.lang.String> describeLocations() ,public List<liquibase.resource.Resource> getAll(java.lang.String) throws java.io.IOException,public List<liquibase.resource.Resource> search(java.lang.String, liquibase.resource.ResourceAccessor.SearchOptions) throws java.io.IOException,public List<liquibase.resource.Resource> search(java.lang.String, boolean) throws java.io.IOException,public java.lang.String toString() <variables>
|
liquibase_liquibase
|
liquibase/liquibase-standard/src/main/java/liquibase/sdk/resource/MockResource.java
|
MockResource
|
resolve
|
class MockResource extends AbstractResource {
private final String content;
public MockResource(String path, String content) {
super(path, URI.create("mock:" + path));
this.content = content;
}
@Override
public boolean exists() {
return true;
}
@Override
public Resource resolve(String other) {<FILL_FUNCTION_BODY>}
@Override
public Resource resolveSibling(String other) {
return new MockResource(resolveSiblingPath(other), "Sibling resource to " + getPath());
}
@Override
public InputStream openInputStream() throws IOException {
return new ByteArrayInputStream(content.getBytes());
}
}
|
return new MockResource(resolvePath(other), "Resource relative to " + getPath());
| 184
| 24
| 208
|
<methods>public void <init>(java.lang.String, java.net.URI) ,public boolean equals(java.lang.Object) ,public java.lang.String getPath() ,public java.net.URI getUri() ,public int hashCode() ,public boolean isWritable() ,public java.io.OutputStream openOutputStream(liquibase.resource.OpenOptions) throws java.io.IOException,public java.lang.String toString() <variables>private final non-sealed java.lang.String path,private final non-sealed java.net.URI uri
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.