_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q165500
Type.getArgumentTypes
validation
public static Type[] getArgumentTypes(final String methodDescriptor) { char[] buf = methodDescriptor.toCharArray(); int off = 1; int size = 0; while (true) { char car = buf[off++]; if (car == ')') { break; } else if (car == 'L') { while (buf[off++] != ';') { } ++size; } else if (car != '[') { ++size; } } Type[] args = new Type[size]; off = 1; size = 0; while (buf[off] != ')') { args[size] = getType(buf, off); off += args[size].len + (args[size].sort == OBJECT ? 2 : 0); size += 1; } return args; }
java
{ "resource": "" }
q165501
Type.getReturnType
validation
public static Type getReturnType(final String methodDescriptor) { char[] buf = methodDescriptor.toCharArray(); int off = 1; while (true) { char car = buf[off++]; if (car == ')') { return getType(buf, off); } else if (car == 'L') { while (buf[off++] != ';') { } } } }
java
{ "resource": "" }
q165502
Type.getArgumentsAndReturnSizes
validation
public static int getArgumentsAndReturnSizes(final String desc) { int n = 1; int c = 1; while (true) { char car = desc.charAt(c++); if (car == ')') { car = desc.charAt(c); return n << 2 | (car == 'V' ? 0 : (car == 'D' || car == 'J' ? 2 : 1)); } else if (car == 'L') { while (desc.charAt(c++) != ';') { } n += 1; } else if (car == '[') { while ((car = desc.charAt(c)) == '[') { ++c; } if (car == 'D' || car == 'J') { n -= 1; } } else if (car == 'D' || car == 'J') { n += 2; } else { n += 1; } } }
java
{ "resource": "" }
q165503
Type.getType
validation
private static Type getType(final char[] buf, final int off) { int len; switch (buf[off]) { case 'V': return VOID_TYPE; case 'Z': return BOOLEAN_TYPE; case 'C': return CHAR_TYPE; case 'B': return BYTE_TYPE; case 'S': return SHORT_TYPE; case 'I': return INT_TYPE; case 'F': return FLOAT_TYPE; case 'J': return LONG_TYPE; case 'D': return DOUBLE_TYPE; case '[': len = 1; while (buf[off + len] == '[') { ++len; } if (buf[off + len] == 'L') { ++len; while (buf[off + len] != ';') { ++len; } } return new Type(ARRAY, buf, off, len + 1); case 'L': len = 1; while (buf[off + len] != ';') { ++len; } return new Type(OBJECT, buf, off + 1, len - 1); // case '(': default: return new Type(METHOD, buf, off, buf.length - off); } }
java
{ "resource": "" }
q165504
Type.getDescriptor
validation
private void getDescriptor(final StringBuilder buf) { if (this.buf == null) { // descriptor is in byte 3 of 'off' for primitive types (buf == // null) buf.append((char) ((off & 0xFF000000) >>> 24)); } else if (sort == OBJECT) { buf.append('L'); buf.append(this.buf, off, len); buf.append(';'); } else { // sort == ARRAY || sort == METHOD buf.append(this.buf, off, len); } }
java
{ "resource": "" }
q165505
Type.getDescriptor
validation
public static String getDescriptor(final Class<?> c) { StringBuilder buf = new StringBuilder(); getDescriptor(buf, c); return buf.toString(); }
java
{ "resource": "" }
q165506
Type.getOpcode
validation
public int getOpcode(final int opcode) { if (opcode == Opcodes.IALOAD || opcode == Opcodes.IASTORE) { // the offset for IALOAD or IASTORE is in byte 1 of 'off' for // primitive types (buf == null) return opcode + (buf == null ? (off & 0xFF00) >> 8 : 4); } else { // the offset for other instructions is in byte 2 of 'off' for // primitive types (buf == null) return opcode + (buf == null ? (off & 0xFF0000) >> 16 : 4); } }
java
{ "resource": "" }
q165507
ByteVector.putByte
validation
public ByteVector putByte(final int b) { int length = this.length; if (length + 1 > data.length) { enlarge(1); } data[length++] = (byte) b; this.length = length; return this; }
java
{ "resource": "" }
q165508
ByteVector.put11
validation
ByteVector put11(final int b1, final int b2) { int length = this.length; if (length + 2 > data.length) { enlarge(2); } byte[] data = this.data; data[length++] = (byte) b1; data[length++] = (byte) b2; this.length = length; return this; }
java
{ "resource": "" }
q165509
ByteVector.putShort
validation
public ByteVector putShort(final int s) { int length = this.length; if (length + 2 > data.length) { enlarge(2); } byte[] data = this.data; data[length++] = (byte) (s >>> 8); data[length++] = (byte) s; this.length = length; return this; }
java
{ "resource": "" }
q165510
ByteVector.put12
validation
ByteVector put12(final int b, final int s) { int length = this.length; if (length + 3 > data.length) { enlarge(3); } byte[] data = this.data; data[length++] = (byte) b; data[length++] = (byte) (s >>> 8); data[length++] = (byte) s; this.length = length; return this; }
java
{ "resource": "" }
q165511
ByteVector.putInt
validation
public ByteVector putInt(final int i) { int length = this.length; if (length + 4 > data.length) { enlarge(4); } byte[] data = this.data; data[length++] = (byte) (i >>> 24); data[length++] = (byte) (i >>> 16); data[length++] = (byte) (i >>> 8); data[length++] = (byte) i; this.length = length; return this; }
java
{ "resource": "" }
q165512
ByteVector.putLong
validation
public ByteVector putLong(final long l) { int length = this.length; if (length + 8 > data.length) { enlarge(8); } byte[] data = this.data; int i = (int) (l >>> 32); data[length++] = (byte) (i >>> 24); data[length++] = (byte) (i >>> 16); data[length++] = (byte) (i >>> 8); data[length++] = (byte) i; i = (int) l; data[length++] = (byte) (i >>> 24); data[length++] = (byte) (i >>> 16); data[length++] = (byte) (i >>> 8); data[length++] = (byte) i; this.length = length; return this; }
java
{ "resource": "" }
q165513
ByteVector.putUTF8
validation
public ByteVector putUTF8(final String s) { int charLength = s.length(); if (charLength > 65535) { throw new IllegalArgumentException(); } int len = length; if (len + 2 + charLength > data.length) { enlarge(2 + charLength); } byte[] data = this.data; // optimistic algorithm: instead of computing the byte length and then // serializing the string (which requires two loops), we assume the byte // length is equal to char length (which is the most frequent case), and // we start serializing the string right away. During the serialization, // if we find that this assumption is wrong, we continue with the // general method. data[len++] = (byte) (charLength >>> 8); data[len++] = (byte) charLength; for (int i = 0; i < charLength; ++i) { char c = s.charAt(i); if (c >= '\001' && c <= '\177') { data[len++] = (byte) c; } else { length = len; return encodeUTF8(s, i, 65535); } } length = len; return this; }
java
{ "resource": "" }
q165514
ByteVector.putByteArray
validation
public ByteVector putByteArray(final byte[] b, final int off, final int len) { if (length + len > data.length) { enlarge(len); } if (b != null) { System.arraycopy(b, off, data, length, len); } length += len; return this; }
java
{ "resource": "" }
q165515
ByteVector.enlarge
validation
private void enlarge(final int size) { int length1 = 2 * data.length; int length2 = length + size; byte[] newData = new byte[length1 > length2 ? length1 : length2]; System.arraycopy(data, 0, newData, 0, length); data = newData; }
java
{ "resource": "" }
q165516
HeaderColumnNameTranslateMappingStrategy.getColumnName
validation
@Override public String getColumnName(int col) { return (col < header.length) ? columnMapping.get(header[col].toUpperCase()) : null; }
java
{ "resource": "" }
q165517
HeaderColumnNameTranslateMappingStrategy.setColumnMapping
validation
public void setColumnMapping(Map<String, String> columnMapping) { this.columnMapping.clear(); for (Map.Entry<String, String> entry : columnMapping.entrySet()) { this.columnMapping.put(entry.getKey().toUpperCase(), entry.getValue()); } }
java
{ "resource": "" }
q165518
AbstractConfigurationContainer.getValue
validation
@Override public <T> T getValue(String propertyName, Class<T> returnType) { return getContainer().getValue(propertyName, returnType); }
java
{ "resource": "" }
q165519
AbstractConfigurationContainer.init
validation
@Override public void init(ConfigurationValueProvider... configurationValueProviders) { if (configurationValueProviders != null) { for (ConfigurationProperty property : getContainer().properties.values()) { property.init(configurationValueProviders); } } }
java
{ "resource": "" }
q165520
IOCase.forName
validation
public static IOCase forName(String name) { if (IOCase.SENSITIVE.name.equals(name)){ return IOCase.SENSITIVE; } if (IOCase.INSENSITIVE.name.equals(name)){ return IOCase.INSENSITIVE; } if (IOCase.SYSTEM.name.equals(name)){ return IOCase.SYSTEM; } throw new IllegalArgumentException("Invalid IOCase name: " + name); }
java
{ "resource": "" }
q165521
IOCase.convertCase
validation
String convertCase(String str) { if (str == null) { return null; } return isSensitive ? str : str.toLowerCase(); }
java
{ "resource": "" }
q165522
ChangeParameterMetaData.getCurrentValue
validation
public Object getCurrentValue(Change change) { try { for (PropertyDescriptor descriptor : PropertyUtils.getInstance().getDescriptors(change.getClass())) { if (descriptor.getDisplayName().equals(this.parameterName)) { Method readMethod = descriptor.getReadMethod(); if (readMethod == null) { readMethod = change.getClass().getMethod( "is" + StringUtil.upperCaseFirst(descriptor.getName()) ); } return readMethod.invoke(change); } } throw new RuntimeException("Could not find readMethod for " + this.parameterName); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } }
java
{ "resource": "" }
q165523
ChangeParameterMetaData.setValue
validation
public void setValue(Change change, Object value) { if ((value instanceof String) && (!"string".equals(dataType))) { try { switch (dataType) { case "bigInteger": value = new BigInteger((String) value); break; case "databaseFunction": value = new DatabaseFunction((String) value); break; default: throw new UnexpectedLiquibaseException("Unknown data type: " + dataType); } } catch (Exception e) { throw new UnexpectedLiquibaseException("Cannot convert string value '" + value + "' to " + dataType + ": " + e.getMessage()); } } try { for (PropertyDescriptor descriptor : PropertyUtils.getInstance().getDescriptors(change.getClass())) { if (descriptor.getDisplayName().equals(this.parameterName)) { Method writeMethod = descriptor.getWriteMethod(); if (writeMethod == null) { throw new UnexpectedLiquibaseException("Could not find writeMethod for " + this.parameterName); } Class<?> expectedWriteType = writeMethod.getParameterTypes()[0]; if ((value != null) && !expectedWriteType.isAssignableFrom(value.getClass())) { if (expectedWriteType.equals(String.class)) { value = value.toString(); } else { throw new UnexpectedLiquibaseException( "Could not convert " + value.getClass().getName() + " to " + expectedWriteType.getName() ); } } writeMethod.invoke(change, value); } } } catch (Exception e) { throw new UnexpectedLiquibaseException("Error setting " + this.parameterName + " to " + value, e); } }
java
{ "resource": "" }
q165524
CollectionUtil.createIfNull
validation
public static <T> T[] createIfNull(T[] arguments) { if (arguments == null) { return (T[]) new Object[0]; } else { return arguments; } }
java
{ "resource": "" }
q165525
CollectionUtil.createIfNull
validation
public static <T> Set<T> createIfNull(Set<T> currentValue) { if (currentValue == null) { return new HashSet<>(); } else { return currentValue; } }
java
{ "resource": "" }
q165526
YamlChangeLogParser.getGlobalParam
validation
private Boolean getGlobalParam(Map property) { Boolean global = null; Object globalObj = property.get("global"); if (globalObj == null) { // default behaviour before liquibase 3.4 global = true; } else { global = (Boolean) globalObj; } return global; }
java
{ "resource": "" }
q165527
ExecutablePreparedStatementBase.attachParams
validation
protected void attachParams(List<ColumnConfig> cols, PreparedStatement stmt) throws SQLException, DatabaseException { int i = 1; // index starts from 1 for (ColumnConfig col : cols) { LOG.fine(LogType.LOG, "Applying column parameter = " + i + " for column " + col.getName()); applyColumnParameter(stmt, i, col); i++; } }
java
{ "resource": "" }
q165528
ExecutablePreparedStatementBase.getAbsolutePath
validation
public String getAbsolutePath(String path) { String p = path; File f = new File(p); if (!f.isAbsolute()) { String basePath = FilenameUtils.getFullPath(changeSet.getChangeLog().getPhysicalFilePath()); p = FilenameUtils.normalize(basePath + p); } return p; }
java
{ "resource": "" }
q165529
CheckSum.parse
validation
public static CheckSum parse(String checksumValue) { if (checksumValue == null) { return null; } // The general layout of a checksum is: // <1 digit: algorithm version number>:<1..n characters alphanumeric checksum> // Example: 7:2cdf9876e74347162401315d34b83746 Matcher matcher = CHECKSUM_PATTERN.matcher(checksumValue); if (matcher.find()) { return new CheckSum(matcher.group(2), Integer.parseInt(matcher.group(1))); } else { // No version information found return new CheckSum(checksumValue, 1); } }
java
{ "resource": "" }
q165530
CheckSum.compute
validation
public static CheckSum compute(String valueToChecksum) { return new CheckSum(MD5Util.computeMD5( //remove "Unknown" unicode char 65533 Normalizer.normalize( StringUtil.standardizeLineEndings(valueToChecksum) .replace("\uFFFD", "") , Normalizer.Form.NFC) ), getCurrentVersion()); }
java
{ "resource": "" }
q165531
AbstractLiquibaseMojo.getClassLoaderIncludingProjectClasspath
validation
protected ClassLoader getClassLoaderIncludingProjectClasspath() throws MojoExecutionException { try { List classpathElements = project.getCompileClasspathElements(); classpathElements.add(project.getBuild().getOutputDirectory()); URL urls[] = new URL[classpathElements.size()]; for (int i = 0; i < classpathElements.size(); ++i) { urls[i] = new File((String) classpathElements.get(i)).toURI().toURL(); } return new URLClassLoader(urls, getMavenArtifactClassLoader()); } catch (Exception e) { throw new MojoExecutionException("Failed to create project classloader", e); } }
java
{ "resource": "" }
q165532
AbstractLiquibaseMojo.printSettings
validation
protected void printSettings(String indent) { if (indent == null) { indent = ""; } getLog().info(indent + "driver: " + driver); getLog().info(indent + "url: " + url); getLog().info(indent + "username: " + username); getLog().info(indent + "password: " + "*****"); getLog().info(indent + "use empty password: " + emptyPassword); getLog().info(indent + "properties file: " + propertyFile); getLog().info(indent + "properties file will override? " + propertyFileWillOverride); getLog().info(indent + "prompt on non-local database? " + promptOnNonLocalDatabase); getLog().info(indent + "clear checksums? " + clearCheckSums); }
java
{ "resource": "" }
q165533
AbstractLiquibaseMojo.parsePropertiesFile
validation
protected void parsePropertiesFile(InputStream propertiesInputStream) throws MojoExecutionException { if (propertiesInputStream == null) { throw new MojoExecutionException("Properties file InputStream is null."); } Properties props = new Properties(); try { props.load(propertiesInputStream); } catch (IOException e) { throw new MojoExecutionException("Could not load the properties Liquibase file", e); } for (Iterator it = props.keySet().iterator(); it.hasNext(); ) { String key = null; try { key = (String) it.next(); Field field = MavenUtils.getDeclaredField(this.getClass(), key); if (propertyFileWillOverride) { getLog().debug(" properties file setting value: " + field.getName()); setFieldValue(field, props.get(key).toString()); } else { if (!isCurrentFieldValueSpecified(field)) { getLog().debug(" properties file setting value: " + field.getName()); setFieldValue(field, props.get(key).toString()); } } } catch (Exception e) { getLog().info(" '" + key + "' in properties file is not being used by this " + "task."); } } }
java
{ "resource": "" }
q165534
AbstractLiquibaseMojo.isCurrentFieldValueSpecified
validation
private boolean isCurrentFieldValueSpecified(Field f) throws IllegalAccessException { Object currentValue = f.get(this); if (currentValue == null) { return false; } Object defaultValue = getDefaultValue(f); if (defaultValue == null) { return currentValue != null; } else { // There is a default value, check to see if the user has selected something other // than the default return !defaultValue.equals(f.get(this)); } }
java
{ "resource": "" }
q165535
CSVWriter.writeNext
validation
public void writeNext(String[] nextLine, boolean applyQuotesToAll) { if (nextLine == null) { return; } StringBuilder sb = new StringBuilder(nextLine.length * 2); // This is for the worse case where all elements have to be escaped. for (int i = 0; i < nextLine.length; i++) { if (i != 0) { sb.append(separator); } String nextElement = nextLine[i]; if (nextElement == null) { continue; } Boolean stringContainsSpecialCharacters = stringContainsSpecialCharacters(nextElement); if ((applyQuotesToAll || stringContainsSpecialCharacters) && (quotechar != NO_QUOTE_CHARACTER)) { sb.append(quotechar); } if (stringContainsSpecialCharacters) { sb.append(processLine(nextElement)); } else { sb.append(nextElement); } if ((applyQuotesToAll || stringContainsSpecialCharacters) && (quotechar != NO_QUOTE_CHARACTER)) { sb.append(quotechar); } } sb.append(lineEnd); pw.write(sb.toString()); }
java
{ "resource": "" }
q165536
CSVWriter.stringContainsSpecialCharacters
validation
protected boolean stringContainsSpecialCharacters(String line) { return (line.indexOf(quotechar) != -1) || (line.indexOf(escapechar) != -1) || (line.indexOf(separator) != -1) || line.contains(DEFAULT_LINE_END) || line.contains("\r"); }
java
{ "resource": "" }
q165537
CSVWriter.processLine
validation
protected StringBuilder processLine(String nextElement) { StringBuilder sb = new StringBuilder(nextElement.length() * 2); // this is for the worse case where all elements have to be escaped. for (int j = 0; j < nextElement.length(); j++) { char nextChar = nextElement.charAt(j); processCharacter(sb, nextChar); } return sb; }
java
{ "resource": "" }
q165538
CSVWriter.processCharacter
validation
private void processCharacter(StringBuilder sb, char nextChar) { if ((escapechar != NO_ESCAPE_CHARACTER) && checkCharactersToEscape(nextChar)) { sb.append(escapechar).append(nextChar); } else { sb.append(nextChar); } }
java
{ "resource": "" }
q165539
LiquibaseServletListener.executeUpdate
validation
private void executeUpdate(ServletContext servletContext, InitialContext ic) throws NamingException, SQLException, LiquibaseException { setDataSource((String) servletValueContainer.getValue(LIQUIBASE_DATASOURCE)); if (getDataSource() == null) { throw new RuntimeException("Cannot run Liquibase, " + LIQUIBASE_DATASOURCE + " is not set"); } setChangeLogFile((String) servletValueContainer.getValue(LIQUIBASE_CHANGELOG)); if (getChangeLogFile() == null) { throw new RuntimeException("Cannot run Liquibase, " + LIQUIBASE_CHANGELOG + " is not set"); } setContexts((String) servletValueContainer.getValue(LIQUIBASE_CONTEXTS)); setLabels((String) servletValueContainer.getValue(LIQUIBASE_LABELS)); this.defaultSchema = StringUtil.trimToNull((String) servletValueContainer.getValue(LIQUIBASE_SCHEMA_DEFAULT)); Connection connection = null; Database database = null; try { DataSource dataSource = (DataSource) ic.lookup(this.dataSourceName); connection = dataSource.getConnection(); Thread currentThread = Thread.currentThread(); ClassLoader contextClassLoader = currentThread.getContextClassLoader(); ResourceAccessor threadClFO = new ClassLoaderResourceAccessor(contextClassLoader); ResourceAccessor clFO = new ClassLoaderResourceAccessor(); ResourceAccessor fsFO = new FileSystemResourceAccessor(); database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection)); database.setDefaultSchemaName(getDefaultSchema()); Liquibase liquibase = new Liquibase(getChangeLogFile(), new CompositeResourceAccessor(clFO, fsFO, threadClFO), database); @SuppressWarnings("unchecked") Enumeration<String> initParameters = servletContext.getInitParameterNames(); while (initParameters.hasMoreElements()) { String name = initParameters.nextElement().trim(); if (name.startsWith(LIQUIBASE_PARAMETER + ".")) { liquibase.setChangeLogParameter(name.substring(LIQUIBASE_PARAMETER.length() + 1), servletValueContainer.getValue(name)); } } liquibase.update(new Contexts(getContexts()), new LabelExpression(getLabels())); } finally { if (database != null) { database.close(); } else if (connection != null) { connection.close(); } } }
java
{ "resource": "" }
q165540
ConfigurationProperty.valueOf
validation
protected Object valueOf(Object value) { if (value == null) { return value; } else if (type.isAssignableFrom(value.getClass())) { return value; } else if (value instanceof String) { if (type.equals(Boolean.class)) { return Boolean.valueOf((String) value); } else if (type.equals(Integer.class)) { return Integer.valueOf((String) value); } else if (type.equals(BigDecimal.class)) { return new BigDecimal((String) value); } else if (type.equals(Long.class)) { return Long.valueOf((String) value); } else if (type.equals(List.class)) { return StringUtil.splitAndTrim((String) value, ","); } else { throw new UnexpectedLiquibaseException("Cannot parse property "+value.getClass().getSimpleName()+" to a "+type.getSimpleName()); } } else { throw new UnexpectedLiquibaseException("Could not convert "+value.getClass().getSimpleName()+" to a "+type.getSimpleName()); } }
java
{ "resource": "" }
q165541
ConfigurationProperty.getValue
validation
public <T> T getValue(Class<T> type) { if (!this.type.isAssignableFrom(type)) { throw new UnexpectedLiquibaseException("Property "+name+" on is of type "+this.type.getSimpleName()+", not "+type.getSimpleName()); } return (T) value; }
java
{ "resource": "" }
q165542
ConfigurationProperty.setValue
validation
public void setValue(Object value) { if ((value != null) && !type.isAssignableFrom(value.getClass())) { throw new UnexpectedLiquibaseException("Property "+name+" on is of type "+type.getSimpleName()+", not "+value.getClass().getSimpleName()); } this.value = value; wasOverridden = true; }
java
{ "resource": "" }
q165543
ConfigurationProperty.addAlias
validation
public ConfigurationProperty addAlias(String... aliases) { if (aliases != null) { this.aliases.addAll(Arrays.asList(aliases)); } return this; }
java
{ "resource": "" }
q165544
ConfigurationProperty.setDefaultValue
validation
public ConfigurationProperty setDefaultValue(Object defaultValue) { if ((defaultValue != null) && !type.isAssignableFrom(defaultValue.getClass())) { if ((type == Long.class) && (defaultValue instanceof Integer)) { return setDefaultValue(((Integer) defaultValue).longValue()); } throw new UnexpectedLiquibaseException("Property "+name+" on is of type "+type.getSimpleName()+", not "+defaultValue.getClass().getSimpleName()); } this.defaultValue = defaultValue; return this; }
java
{ "resource": "" }
q165545
CreateIndexGeneratorFirebird.generateSql
validation
@Override public Sql[] generateSql(CreateIndexStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { /* * According to https://firebirdsql.org/refdocs/langrefupd20-create-table.html#langrefupd20-ct-using-index , * Firebird automatically creates indexes for PRIMARY KEY, UNIQUE KEY and FOREIGN KEY constraints, * so we should not duplicate that functionality (=we should not issue CREATE INDEX statements for them) */ List<String> associatedWith = StringUtil.splitAndTrim(statement.getAssociatedWith(), ","); if ((associatedWith != null) && (associatedWith.contains(Index.MARK_PRIMARY_KEY) || associatedWith.contains (Index.MARK_UNIQUE_CONSTRAINT) || associatedWith.contains(Index.MARK_FOREIGN_KEY))) { return new Sql[0]; } StringBuffer buffer = new StringBuffer(); buffer.append("CREATE "); // If the statement wants a UNIQUE index, issue a CREATE UNIQUE ... INDEX statement. if ((statement.isUnique() != null) && statement.isUnique()) { buffer.append("UNIQUE "); } /* * Examine the direction (ASCending or DESCending) of all columns of the planned index. If _all_ of them * are DESC, issue a CREATE DESCENDING INDEX statement. If all of them are ASC, we do not need to do anything * special (ASCENDING is the default). However, since Firebird does not seem to support mixed ASC/DESC * columns within a single index, we must error out. * * The syntax we want to create is this: * CREATE [UNIQUE] [ASC[ENDING] | DESC[ENDING]] INDEX index_name ON table_name * {(col [, col …]) | COMPUTED BY (<expression>)}; */ ColumnAnalysisResult result = analyseColumns(statement, database); if (result.isFoundDescColumns()) buffer.append("DESCENDING "); buffer.append("INDEX "); if (statement.getIndexName() != null) { String indexSchema = statement.getTableSchemaName(); buffer.append(database.escapeIndexName(statement.getTableCatalogName(), indexSchema, statement.getIndexName())).append(" "); } buffer.append("ON "); // append table name buffer.append(database.escapeTableName(statement.getTableCatalogName(), statement.getTableSchemaName(), statement.getTableName())); if (result.getNumComputedCols() > 0) buffer.append("COMPUTED BY "); buffer.append(String.format("(%s)", result.getColumnExpression())); return new Sql[]{new UnparsedSql(buffer.toString(), getAffectedIndex(statement))}; }
java
{ "resource": "" }
q165546
CreateIndexGeneratorFirebird.applyIsComputedExpressionHeuristic
validation
private boolean applyIsComputedExpressionHeuristic(ColumnConfig column, Database database) { String expr = column.getName(); /* * https://firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-structure-identifiers.html * says the following about what makes a valid identifier in Firebird: * - At most 31 chars * - Starts with a 7-bit character * - After that, letters, digits, underscores or dollar signs are valid characters */ String regex = "^(?i)[ABCDEFGHIJKLMNOPQRSTUVWXYZ]" // Starting character + "[ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$]{0,30}$"; // following characters if (!expr.matches(regex)) return true; /* At this point, we know that expr at least has the form of an identifier. If it is a function, it must * be in the list of database functions. */ if (database.isFunction(expr)) return true; else return false; }
java
{ "resource": "" }
q165547
Liquibase.tag
validation
public void tag(String tagString) throws LiquibaseException { LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId(); checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); getDatabase().tag(tagString); } finally { try { lockService.releaseLock(); } catch (LockException e) { LOG.severe(LogType.LOG, MSG_COULD_NOT_RELEASE_LOCK, e); } } }
java
{ "resource": "" }
q165548
Liquibase.listLocks
validation
public DatabaseChangeLogLock[] listLocks() throws LiquibaseException { checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); return LockServiceFactory.getInstance().getLockService(database).listLocks(); }
java
{ "resource": "" }
q165549
Liquibase.getChangeSetStatuses
validation
public List<ChangeSetStatus> getChangeSetStatuses(Contexts contexts, LabelExpression labelExpression, boolean checkLiquibaseTables) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); DatabaseChangeLog changeLog = getDatabaseChangeLog(); if (checkLiquibaseTables) { checkLiquibaseTables(true, changeLog, contexts, labelExpression); } changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = getStandardChangelogIterator(contexts, labelExpression, changeLog); StatusVisitor visitor = new StatusVisitor(database); logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labelExpression)); return visitor.getStatuses(); }
java
{ "resource": "" }
q165550
Liquibase.clearCheckSums
validation
public void clearCheckSums() throws LiquibaseException { LOG.info(LogType.LOG, "Clearing database change log checksums"); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); UpdateStatement updateStatement = new UpdateStatement( getDatabase().getLiquibaseCatalogName(), getDatabase().getLiquibaseSchemaName(), getDatabase().getDatabaseChangeLogTableName() ); updateStatement.addNewColumnValue("MD5SUM", null); ExecutorService.getInstance().getExecutor(database).execute(updateStatement); getDatabase().commit(); } finally { try { lockService.releaseLock(); } catch (LockException e) { LOG.severe(LogType.LOG, MSG_COULD_NOT_RELEASE_LOCK, e); } } resetServices(); }
java
{ "resource": "" }
q165551
CsvToBean.parse
validation
public List<T> parse(MappingStrategy<T> mapper, Reader reader) { return parse(mapper, new CSVReader(reader)); }
java
{ "resource": "" }
q165552
CsvToBean.processLine
validation
protected T processLine(MappingStrategy<T> mapper, String[] line) throws ReflectiveOperationException, IntrospectionException { T bean = mapper.createBean(); for (int col = 0; col < line.length; col++) { if (mapper.isAnnotationDriven()) { processField(mapper, line, bean, col); } else { processProperty(mapper, line, bean, col); } } return bean; }
java
{ "resource": "" }
q165553
CsvToBean.getPropertyEditor
validation
protected PropertyEditor getPropertyEditor(PropertyDescriptor desc) throws ReflectiveOperationException { Class<?> cls = desc.getPropertyEditorClass(); if (null != cls) { return (PropertyEditor) cls.getConstructor().newInstance(); } return getPropertyEditorValue(desc.getPropertyType()); }
java
{ "resource": "" }
q165554
DefaultPackageScanClassResolver.loadImplementationsInJar
validation
protected void loadImplementationsInJar( String parentPackage, InputStream parentFileStream, ClassLoader loader, String parentFileName, String grandparentFileName) throws IOException { Set<String> classFiles = classFilesByLocation.get(parentFileName); if (classFiles == null) { classFiles = new HashSet<String>(); classFilesByLocation.put(parentFileName, classFiles); Set<String> grandparentClassFiles = classFilesByLocation.get(grandparentFileName); if (grandparentClassFiles == null) { grandparentClassFiles = new HashSet<String>(); classFilesByLocation.put(grandparentFileName, grandparentClassFiles); } JarInputStream jarStream; if (parentFileStream instanceof JarInputStream) { jarStream = (JarInputStream) parentFileStream; } else { jarStream = new JarInputStream(parentFileStream); } JarEntry entry; while ((entry = jarStream.getNextJarEntry()) != null) { String name = entry.getName(); if (name != null) { if (name.endsWith(".jar")) { //in a nested jar log.fine(LogType.LOG, "Found nested jar " + name); // To avoid needing to unzip 'parentFile' in its entirety, as that // may take a very long time (see CORE-2115) or not even be possible // (see CORE-2595), we load the nested JAR from the classloader and // read it as a zip. // // It is safe to assume that the nested JAR is readable by the classloader // as a resource stream, because we have reached this point by scanning // through packages located from `classloader` by using `getResource`. // If loading this nested JAR as a resource fails, then certainly loading // classes from inside it with `classloader` would fail and we are safe // to exclude it form the PackageScan. InputStream nestedJarResourceStream = loader.getResourceAsStream(name); if (nestedJarResourceStream != null) { JarInputStream nestedJarStream = new JarInputStream(nestedJarResourceStream); try { loadImplementationsInJar( parentPackage, nestedJarStream, loader, parentFileName + "!" + name, parentFileName); } finally { nestedJarStream.close(); } } } else if (!entry.isDirectory() && name.endsWith(".class")) { classFiles.add(name.trim()); grandparentClassFiles.add(name.trim()); } } } } for (String name : classFiles) { if (name.contains(parentPackage)) { loadClass(name, loader); } } }
java
{ "resource": "" }
q165555
DefaultPackageScanClassResolver.addIfMatching
validation
protected void addIfMatching(PackageScanFilter test, String fqn, Set<Class<?>> classes) { try { String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.'); Set<ClassLoader> set = getClassLoaders(); boolean found = false; for (ClassLoader classLoader : set) { log.fine(LogType.LOG, "Testing that class " + externalName + " matches criteria [" + test + "] using classloader:" + classLoader); try { Class<?> type = classLoader.loadClass(externalName); log.fine(LogType.LOG, "Loaded the class: " + type + " in classloader: " + classLoader); if (test.matches(type)) { log.fine(LogType.LOG, "Found class: " + type + " which matches the filter in classloader: " + classLoader); classes.add(type); } found = true; break; } catch (ClassNotFoundException e) { log.fine(LogType.LOG, "Cannot find class '" + fqn + "' in classloader: " + classLoader + ". Reason: " + e, e); } catch (LinkageError e) { log.fine(LogType.LOG, "Cannot find the class definition '" + fqn + "' in classloader: " + classLoader + ". Reason: " + e, e); } catch (Exception e) { log.severe(LogType.LOG, "Cannot load class '"+fqn+"' in classloader: "+classLoader+". Reason: "+e, e); } } if (!found) { // use debug to avoid being noisy in logs log.fine(LogType.LOG, "Cannot find class '" + fqn + "' in any classloaders: " + set); } } catch (Exception e) { log.warning(LogType.LOG, "Cannot examine class '" + fqn + "' due to a " + e.getClass().getName() + " with message: " + e.getMessage(), e); } }
java
{ "resource": "" }
q165556
ObjectUtil.getPropertyType
validation
public static Class getPropertyType(Object object, String propertyName) { Method readMethod = getReadMethod(object, propertyName); if (readMethod == null) { return null; } return readMethod.getReturnType(); }
java
{ "resource": "" }
q165557
ObjectUtil.hasProperty
validation
public static boolean hasProperty(Object object, String propertyName) { return hasReadProperty(object, propertyName) && hasWriteProperty(object, propertyName); }
java
{ "resource": "" }
q165558
ObjectUtil.setProperty
validation
public static void setProperty(Object object, String propertyName, String propertyValue) { Method method = getWriteMethod(object, propertyName); if (method == null) { throw new UnexpectedLiquibaseException ( String.format("Property [%s] was not found for object type [%s]", propertyName, object.getClass().getName() )); } Class<?> parameterType = method.getParameterTypes()[0]; Object finalValue = propertyValue; if (parameterType.equals(Boolean.class) || parameterType.equals(boolean.class)) { finalValue = Boolean.valueOf(propertyValue); } else if (parameterType.equals(Integer.class)) { finalValue = Integer.valueOf(propertyValue); } else if (parameterType.equals(Long.class)) { finalValue = Long.valueOf(propertyValue); } else if (parameterType.equals(BigInteger.class)) { finalValue = new BigInteger(propertyValue); } else if (parameterType.equals(BigDecimal.class)) { finalValue = new BigDecimal(propertyValue); } else if (parameterType.equals(DatabaseFunction.class)) { finalValue = new DatabaseFunction(propertyValue); } else if (parameterType.equals(SequenceNextValueFunction.class)) { finalValue = new SequenceNextValueFunction(propertyValue); } else if (parameterType.equals(SequenceCurrentValueFunction.class)) { finalValue = new SequenceCurrentValueFunction(propertyValue); } else if (Enum.class.isAssignableFrom(parameterType)) { finalValue = Enum.valueOf((Class<Enum>) parameterType, propertyValue); } try { method.invoke(object, finalValue); } catch (IllegalAccessException | InvocationTargetException e) { throw new UnexpectedLiquibaseException(e); } catch (IllegalArgumentException e) { throw new UnexpectedLiquibaseException("Cannot call " + method.toString() + " with value of type " + finalValue.getClass().getName()); } }
java
{ "resource": "" }
q165559
ObjectUtil.getReadMethod
validation
private static Method getReadMethod(Object object, String propertyName) { String getMethodName = "get" + propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH) + propertyName.substring(1); String isMethodName = "is" + propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH) + propertyName.substring(1); Method[] methods = getMethods(object); for (Method method : methods) { if ((method.getName().equals(getMethodName) || method.getName().equals(isMethodName)) && (method .getParameterTypes().length == 0)) { return method; } } return null; }
java
{ "resource": "" }
q165560
ObjectUtil.getWriteMethod
validation
private static Method getWriteMethod(Object object, String propertyName) { String methodName = "set" + propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH) + propertyName.substring(1); Method[] methods = getMethods(object); for (Method method : methods) { if (method.getName().equals(methodName) && (method.getParameterTypes().length == 1)) { return method; } } return null; }
java
{ "resource": "" }
q165561
ObjectUtil.getMethods
validation
private static Method[] getMethods(Object object) { Method[] methods = methodCache.get(object.getClass()); if (methods == null) { methods = object.getClass().getMethods(); methodCache.put(object.getClass(), methods); } return methods; }
java
{ "resource": "" }
q165562
ObjectDifferences.undoCollection
validation
protected Object undoCollection(Object potentialCollection, Object otherObject) { if ((potentialCollection != null) && (otherObject != null) && (potentialCollection instanceof Collection) && !(otherObject instanceof Collection)) { if ((((Collection) potentialCollection).size() == 1) && ((Collection) potentialCollection).iterator() .next().getClass().equals(otherObject.getClass())) { potentialCollection = ((Collection) potentialCollection).iterator().next(); } } return potentialCollection; }
java
{ "resource": "" }
q165563
Table.getOutgoingForeignKeys
validation
public List<ForeignKey> getOutgoingForeignKeys() { List<ForeignKey> fkList = getAttribute("outgoingForeignKeys", List.class); return ((fkList == null) ? new ArrayList<ForeignKey>(0) : fkList); }
java
{ "resource": "" }
q165564
SchemesCDIConfigBuilder.createCDILiquibaseConfig
validation
public CDILiquibaseConfig createCDILiquibaseConfig() { final String id = UUID.randomUUID().toString(); log.fine(LogType.LOG, String.format("[id = %s] createConfig(). Date: '%s'", id, new Date())); final InputStream is = SchemesCDIConfigBuilder.class.getResourceAsStream(SCHEMA_NAME); try { return jvmLocked(id, new Callable<CDILiquibaseConfig>() { public CDILiquibaseConfig call() throws Exception { return createCDILiquibaseConfig(id, is); } }); } catch (Exception ex) { log.warning(LogType.LOG, String.format("[id = %s] Unable to initialize liquibase where '%s'.", id, ex.getMessage()), ex); return null; } finally { try { is.close(); } catch (IOException ioe) { log.warning(LogType.LOG, String.format("[id = %s] IOException during closing an input stream '%s'.", id, ioe.getMessage()), ioe); } } }
java
{ "resource": "" }
q165565
SchemesCDIConfigBuilder.fileLocked
validation
CDILiquibaseConfig fileLocked(final String id, Callable<CDILiquibaseConfig> action) throws Exception { log.info(LogType.LOG, String.format("[id = %s] JVM lock acquired, acquiring file lock", id)); String lockPath = String.format("%s/schema.liquibase.lock", ROOT_PATH); File lockFile = new File(lockPath); if (!lockFile.exists() && lockFile.createNewFile()) { log.info(LogType.LOG, String.format("[id = %s] Created lock file [path='%s'].", id, lockPath)); } log.info(LogType.LOG, String.format("[id = %s] Trying to acquire the file lock [file='%s']...", id, lockPath)); CDILiquibaseConfig actionResult = null; FileLock lock = null; try ( FileOutputStream fileStream = new FileOutputStream(lockPath); FileChannel fileChannel = fileStream.getChannel(); ) { while (null == lock) { try { lock = fileChannel.tryLock(); } catch (OverlappingFileLockException e) { log.fine(LogType.LOG, String.format("[id = %s] Lock already acquired, waiting for the lock...", id)); } if (null == lock) { log.fine(LogType.LOG, String.format("[id = %s] Waiting for the lock...", id)); Thread.sleep(FILE_LOCK_TIMEOUT); } } log.info(LogType.LOG, String.format("[id = %s] File lock acquired, running liquibase...", id)); actionResult = action.call(); lock.release(); } catch (Exception e) { log.warning(LogType.LOG, e.getMessage(), e); } return actionResult; }
java
{ "resource": "" }
q165566
SpringBootFatJar.getSimplePathForResources
validation
public static String getSimplePathForResources(String entryName, String path) { String[] components = path.split("!"); if (components.length == 3) { if (components[1].endsWith(".jar")) { return components[2].substring(1); } else { return entryName.replaceFirst(components[1], "").substring(1); } } return entryName; }
java
{ "resource": "" }
q165567
ChangeSetStatus.isFilteredBy
validation
public boolean isFilteredBy(Class<? extends ChangeSetFilter> filterType) { if (!willRun) { return false; } if (filterResults == null) { return false; } for (ChangeSetFilterResult result : filterResults) { if (result.getFilter().equals(filterType)) { return true; } } return false; }
java
{ "resource": "" }
q165568
JdbcUtils.getValueForColumn
validation
public static String getValueForColumn(ResultSet rs, String columnNameToCheck, Database database) throws SQLException { ResultSetMetaData metadata = rs.getMetaData(); int numberOfColumns = metadata.getColumnCount(); String correctedColumnName = database.correctObjectName(columnNameToCheck, Column.class); // get the column names; column indexes start from 1 for (int i = 1; i < (numberOfColumns + 1); i++) { String columnName = metadata.getColumnLabel(i); // Get the name of the column's table name if (correctedColumnName.equalsIgnoreCase(columnName)) { return rs.getString(columnName); } } return null; }
java
{ "resource": "" }
q165569
LiquibaseConfiguration.init
validation
public void init(ConfigurationValueProvider... configurationValueProviders) { if (configurationValueProviders == null) { configurationValueProviders = new ConfigurationValueProvider[0]; } this.configurationValueProviders = configurationValueProviders; this.reset(); }
java
{ "resource": "" }
q165570
CommandLineUtils.initializeDatabase
validation
public static void initializeDatabase(String username, String defaultCatalogName, String defaultSchemaName, Database database) throws DatabaseException { if (((defaultCatalogName != null) || (defaultSchemaName != null)) && !(database.getConnection() instanceof OfflineConnection)) { if (database instanceof OracleDatabase) { String schema = defaultCatalogName; if (schema == null) { schema = defaultSchemaName; } ExecutorService.getInstance().getExecutor(database).execute( new RawSqlStatement("ALTER SESSION SET CURRENT_SCHEMA=" + database.escapeObjectName(schema, Schema.class))); } else if (database instanceof PostgresDatabase && defaultSchemaName != null) { ExecutorService.getInstance().getExecutor(database).execute(new RawSqlStatement("SET SEARCH_PATH TO " + database.escapeObjectName(defaultSchemaName, Schema.class))); } else if (database instanceof AbstractDb2Database) { String schema = defaultCatalogName; if (schema == null) { schema = defaultSchemaName; } ExecutorService.getInstance().getExecutor(database).execute(new RawSqlStatement("SET CURRENT SCHEMA " + schema)); } else if (database instanceof MySQLDatabase) { String schema = defaultCatalogName; if (schema == null) { schema = defaultSchemaName; } ExecutorService.getInstance().getExecutor(database).execute(new RawSqlStatement("USE " + schema)); } } }
java
{ "resource": "" }
q165571
DefaultDatabaseObjectComparator.nameMatches
validation
public static boolean nameMatches(DatabaseObject databaseObject1, DatabaseObject databaseObject2, Database accordingTo) { String object1Name = accordingTo.correctObjectName(databaseObject1.getName(), databaseObject1.getClass()); String object2Name = accordingTo.correctObjectName(databaseObject2.getName(), databaseObject2.getClass()); if ((object1Name == null) && (object2Name == null)) { return true; } if ((object1Name == null) || (object2Name == null)) { return false; } if (accordingTo.isCaseSensitive()) { return object1Name.equals(object2Name); } else { return object1Name.equalsIgnoreCase(object2Name); } }
java
{ "resource": "" }
q165572
ForeignKeySnapshotGenerator.setValidateOptionIfAvailable
validation
private void setValidateOptionIfAvailable(Database database, ForeignKey foreignKey, CachedRow cachedRow) { if (!(database instanceof OracleDatabase)) { return; } final String constraintValidate = cachedRow.getString("FK_VALIDATE"); final String VALIDATE = "VALIDATED"; if (constraintValidate!=null && !constraintValidate.isEmpty()) { foreignKey.setShouldValidate(VALIDATE.equals(cleanNameFromDatabase(constraintValidate.trim(), database))); } }
java
{ "resource": "" }
q165573
SnapshotControl.addType
validation
public boolean addType(Class<? extends DatabaseObject> type, Database database) { boolean added = this.types.add(type); if (added) { for (Class<? extends DatabaseObject> container : SnapshotGeneratorFactory.getInstance().getContainerTypes(type, database)) { addType(container, database); } } return added; }
java
{ "resource": "" }
q165574
SpringLiquibase.afterPropertiesSet
validation
@Override public void afterPropertiesSet() throws LiquibaseException { ConfigurationProperty shouldRunProperty = LiquibaseConfiguration.getInstance() .getProperty(GlobalConfiguration.class, GlobalConfiguration.SHOULD_RUN); if (!shouldRunProperty.getValue(Boolean.class)) { Scope.getCurrentScope().getLog(getClass()).info(LogType.LOG, "Liquibase did not run because " + LiquibaseConfiguration .getInstance().describeValueLookupLogic(shouldRunProperty) + " was set to false"); return; } if (!shouldRun) { Scope.getCurrentScope().getLog(getClass()).info(LogType.LOG, "Liquibase did not run because 'shouldRun' " + "property was set " + "to false on " + getBeanName() + " Liquibase Spring bean."); return; } Connection c = null; Liquibase liquibase = null; try { c = getDataSource().getConnection(); liquibase = createLiquibase(c); generateRollbackFile(liquibase); performUpdate(liquibase); } catch (SQLException e) { throw new DatabaseException(e); } finally { Database database = null; if (liquibase != null) { database = liquibase.getDatabase(); } if (database != null) { database.close(); } } }
java
{ "resource": "" }
q165575
AbstractCSVToBean.checkForTrim
validation
protected String checkForTrim(String s, PropertyDescriptor prop) { return trimmableProperty(prop) ? s.trim() : s; }
java
{ "resource": "" }
q165576
AbstractCSVToBean.convertValue
validation
protected Object convertValue(String value, PropertyDescriptor prop) throws ReflectiveOperationException { PropertyEditor editor = getPropertyEditor(prop); Object obj = value; if (null != editor) { editor.setAsText(value); obj = editor.getValue(); } return obj; }
java
{ "resource": "" }
q165577
Main.main
validation
public static void main(String[] args) { int errorLevel = 0; try { errorLevel = run(args); } catch (Throwable e) { System.exit(-1); } System.exit(errorLevel); }
java
{ "resource": "" }
q165578
Main.splitArg
validation
@SuppressWarnings("squid:S109") private static String[] splitArg(String arg) throws CommandLineParsingException { String[] splitArg = arg.split("=", 2); if (splitArg.length < 2) { throw new CommandLineParsingException( String.format(coreBundle.getString("could.not.parse.expression"), arg) ); } splitArg[0] = splitArg[0].replaceFirst("--", ""); return splitArg; }
java
{ "resource": "" }
q165579
Main.isCommand
validation
private static boolean isCommand(String arg) { return COMMANDS.MIGRATE.equals(arg) || COMMANDS.MIGRATE_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE.equalsIgnoreCase(arg) || COMMANDS.UPDATE_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE_COUNT.equalsIgnoreCase(arg) || COMMANDS.UPDATE_COUNT_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE_TO_TAG.equalsIgnoreCase(arg) || COMMANDS.UPDATE_TO_TAG_SQL.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_TO_DATE.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_COUNT.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_SQL.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_TO_DATE_SQL.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_COUNT_SQL.equalsIgnoreCase(arg) || COMMANDS.FUTURE_ROLLBACK_SQL.equalsIgnoreCase(arg) || COMMANDS.FUTURE_ROLLBACK_COUNT_SQL.equalsIgnoreCase(arg) || COMMANDS.FUTURE_ROLLBACK_TO_TAG_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE_TESTING_ROLLBACK.equalsIgnoreCase(arg) || COMMANDS.TAG.equalsIgnoreCase(arg) || COMMANDS.TAG_EXISTS.equalsIgnoreCase(arg) || COMMANDS.LIST_LOCKS.equalsIgnoreCase(arg) || COMMANDS.DROP_ALL.equalsIgnoreCase(arg) || COMMANDS.RELEASE_LOCKS.equalsIgnoreCase(arg) || COMMANDS.STATUS.equalsIgnoreCase(arg) || COMMANDS.UNEXPECTED_CHANGESETS.equalsIgnoreCase(arg) || COMMANDS.VALIDATE.equalsIgnoreCase(arg) || COMMANDS.HELP.equalsIgnoreCase(arg) || COMMANDS.DIFF.equalsIgnoreCase(arg) || COMMANDS.DIFF_CHANGELOG.equalsIgnoreCase(arg) || COMMANDS.GENERATE_CHANGELOG.equalsIgnoreCase(arg) || COMMANDS.SNAPSHOT.equalsIgnoreCase(arg) || COMMANDS.SNAPSHOT_REFERENCE.equalsIgnoreCase(arg) || COMMANDS.EXECUTE_SQL.equalsIgnoreCase(arg) || COMMANDS.CALCULATE_CHECKSUM.equalsIgnoreCase(arg) || COMMANDS.CLEAR_CHECKSUMS.equalsIgnoreCase(arg) || COMMANDS.DB_DOC.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC_SQL.equalsIgnoreCase(arg) || COMMANDS.MARK_NEXT_CHANGESET_RAN.equalsIgnoreCase(arg) || COMMANDS.MARK_NEXT_CHANGESET_RAN_SQL.equalsIgnoreCase(arg); }
java
{ "resource": "" }
q165580
Main.isNoArgCommand
validation
private static boolean isNoArgCommand(String arg) { return COMMANDS.MIGRATE.equals(arg) || COMMANDS.MIGRATE_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE.equalsIgnoreCase(arg) || COMMANDS.UPDATE_SQL.equalsIgnoreCase(arg) || COMMANDS.FUTURE_ROLLBACK_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE_TESTING_ROLLBACK.equalsIgnoreCase(arg) || COMMANDS.LIST_LOCKS.equalsIgnoreCase(arg) || COMMANDS.DROP_ALL.equalsIgnoreCase(arg) || COMMANDS.RELEASE_LOCKS.equalsIgnoreCase(arg) || COMMANDS.VALIDATE.equalsIgnoreCase(arg) || COMMANDS.HELP.equalsIgnoreCase(arg) || COMMANDS.CLEAR_CHECKSUMS.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC_SQL.equalsIgnoreCase(arg) || COMMANDS.MARK_NEXT_CHANGESET_RAN.equalsIgnoreCase(arg) || COMMANDS.MARK_NEXT_CHANGESET_RAN_SQL.equalsIgnoreCase(arg); }
java
{ "resource": "" }
q165581
Main.extract
validation
private static File extract(JarFile jar, JarEntry entry) throws IOException { // expand to temp dir and add to list File tempFile = File.createTempFile("liquibase.tmp", null); // read from jar and write to the tempJar file try ( BufferedInputStream inStream = new BufferedInputStream(jar.getInputStream(entry)); BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(tempFile)) ) { int status; while ((status = inStream.read()) != -1) { outStream.write(status); } } return tempFile; }
java
{ "resource": "" }
q165582
Main.parseDefaultPropertyFileFromResource
validation
private void parseDefaultPropertyFileFromResource(File potentialPropertyFile) throws IOException, CommandLineParsingException { try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream (potentialPropertyFile.getAbsolutePath())) { if (resourceAsStream != null) { parsePropertiesFile(resourceAsStream); } } }
java
{ "resource": "" }
q165583
Main.fixupArgs
validation
protected String[] fixupArgs(String[] args) { List<String> fixedArgs = new ArrayList<>(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if ((arg.startsWith("--") || arg.startsWith("-D")) && !arg.contains("=")) { String nextArg = null; if ((i + 1) < args.length) { nextArg = args[i + 1]; } if ((nextArg != null) && !nextArg.startsWith("--") && !isCommand(nextArg)) { arg = arg + "=" + nextArg; i++; } } // Sometimes, commas are still escaped as \, at this point, fix it: arg = arg.replace("\\,", ","); fixedArgs.add(arg); } return fixedArgs.toArray(new String[fixedArgs.size()]); }
java
{ "resource": "" }
q165584
Main.checkSetup
validation
protected List<String> checkSetup() { List<String> messages = new ArrayList<>(); if (command == null) { messages.add(coreBundle.getString("command.not.passed")); } else if (!isCommand(command)) { messages.add(String.format(coreBundle.getString("command.unknown"), command)); } else { if (StringUtil.trimToNull(url) == null) { messages.add(String.format(coreBundle.getString("option.required"), "--" + OPTIONS.URL)); } if (isChangeLogRequired(command) && (StringUtil.trimToNull(changeLogFile) == null)) { messages.add(String.format(coreBundle.getString("option.required"), "--" + OPTIONS.CHANGELOG_FILE)); } if (isNoArgCommand(command) && !commandParams.isEmpty()) { messages.add(coreBundle.getString(ERRORMSG_UNEXPECTED_PARAMETERS) + commandParams); } else { validateCommandParameters(messages); } } return messages; }
java
{ "resource": "" }
q165585
Main.checkForMissingCommandParameters
validation
private void checkForMissingCommandParameters(final List<String> messages) { if ((commandParams.isEmpty() || commandParams.iterator().next().startsWith("-")) && (COMMANDS.CALCULATE_CHECKSUM.equalsIgnoreCase(command))) { messages.add(coreBundle.getString("changeset.identifier.missing")); } }
java
{ "resource": "" }
q165586
Main.checkForMalformedCommandParameters
validation
private void checkForMalformedCommandParameters(final List<String> messages) { if (commandParams.isEmpty()) { return; } final int CHANGESET_MINIMUM_IDENTIFIER_PARTS = 3; if (COMMANDS.CALCULATE_CHECKSUM.equalsIgnoreCase(command)) { for (final String param : commandParams) { if ((param != null) && !param.startsWith("-")) { final String[] parts = param.split("::"); if (parts.length < CHANGESET_MINIMUM_IDENTIFIER_PARTS) { messages.add(coreBundle.getString("changeset.identifier.must.have.form.filepath.id.author")); break; } } } } else if (COMMANDS.DIFF_CHANGELOG.equalsIgnoreCase(command) && (diffTypes != null) && diffTypes.toLowerCase ().contains("data")) { messages.add(String.format(coreBundle.getString("including.data.diffchangelog.has.no.effect"), OPTIONS.DIFF_TYPES, COMMANDS.GENERATE_CHANGELOG )); } }
java
{ "resource": "" }
q165587
Main.parsePropertiesFile
validation
protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); if (props.containsKey("strict")) { strict = Boolean.valueOf(props.getProperty("strict")); } for (Map.Entry entry : props.entrySet()) { try { if ("promptOnNonLocalDatabase".equals(entry.getKey())) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue ()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (NoSuchFieldException ignored) { if (strict) { throw new CommandLineParsingException( String.format(coreBundle.getString("parameter.unknown"), entry.getKey()) ); } else { Scope.getCurrentScope().getLog(getClass()).warning( LogType.LOG, String.format(coreBundle.getString("parameter.ignored"), entry.getKey()) ); } } catch (IllegalAccessException e) { throw new UnexpectedLiquibaseException( String.format(coreBundle.getString("parameter.unknown"), entry.getKey()) ); } } }
java
{ "resource": "" }
q165588
Main.printHelp
validation
protected void printHelp(List<String> errorMessages, PrintStream stream) { stream.println(coreBundle.getString("errors")); for (String message : errorMessages) { stream.println(" " + message); } stream.println(); }
java
{ "resource": "" }
q165589
Main.printHelp
validation
protected void printHelp(PrintStream stream) { String helpText = commandLineHelpBundle.getString("commandline-helptext"); stream.println(helpText); }
java
{ "resource": "" }
q165590
Main.parseOptions
validation
protected void parseOptions(String[] paramArgs) throws CommandLineParsingException { String[] args = fixupArgs(paramArgs); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase(COMMANDS.MIGRATE)) { this.command = COMMANDS.UPDATE; } else if (this.command.equalsIgnoreCase(COMMANDS.MIGRATE_SQL)) { this.command = COMMANDS.UPDATE_SQL; } seenCommand = true; } else if (seenCommand) { // ChangeLog parameter: if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); if (arg.startsWith("--")) { parseOptionArgument(arg); } } } else if (arg.startsWith("--")) { parseOptionArgument(arg); } else { throw new CommandLineParsingException( String.format(coreBundle.getString("unexpected.value"), arg)); } } // Now apply default values from the default property files. We waited with this until this point // since command line parameters might have changed the location where we will look for them. parseDefaultPropertyFiles(); }
java
{ "resource": "" }
q165591
Main.getCommandParam
validation
private String getCommandParam(String paramName, String defaultValue) throws CommandLineParsingException { for (String param : commandParams) { if (!param.contains("=")) { continue; } String[] splitArg = splitArg(param); String attributeName = splitArg[0]; String value = splitArg[1]; if (attributeName.equalsIgnoreCase(paramName)) { return value; } } return defaultValue; }
java
{ "resource": "" }
q165592
NumberUtils.readInteger
validation
public static Integer readInteger(String value) { if (value == null) { return null; } return Integer.valueOf(value); }
java
{ "resource": "" }
q165593
LabelExpression.matches
validation
public boolean matches(Labels runtimeLabels) { if ((runtimeLabels == null) || runtimeLabels.isEmpty()) { return true; } if (this.labels.isEmpty()) { return true; } for (String expression : this.labels) { if (matches(expression, runtimeLabels)) { return true; } } return false; }
java
{ "resource": "" }
q165594
SnapshotGeneratorFactory.has
validation
public boolean has(DatabaseObject example, Database database) throws DatabaseException, InvalidExampleException { // @todo I have seen duplicates in types - maybe convert the List into a Set? Need to understand it more thoroughly. List<Class<? extends DatabaseObject>> types = new ArrayList<>(getContainerTypes(example.getClass(), database)); types.add(example.getClass()); /* * Does the query concern the DATABASECHANGELOG / DATABASECHANGELOGLOCK table? If so, we do a quick & dirty * SELECT COUNT(*) on that table. If that works, we count that as confirmation of existence. */ // @todo Actually, there may be extreme cases (distorted table statistics etc.) where a COUNT(*) might not be so cheap. Maybe SELECT a dummy constant is the better way? if ((example instanceof Table) && (example.getName().equals(database.getDatabaseChangeLogTableName()) || example.getName().equals(database.getDatabaseChangeLogLockTableName()))) { try { ExecutorService.getInstance().getExecutor(database).queryForInt( new RawSqlStatement("SELECT COUNT(*) FROM " + database.escapeObjectName(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), example.getName(), Table.class))); return true; } catch (DatabaseException e) { if (database instanceof PostgresDatabase) { // throws "current transaction is aborted" unless we roll back the connection database.rollback(); } return false; } } /* * If the query is about another object, try to create a snapshot of the of the object (or used the cached * snapshot. If that works, we count that as confirmation of existence. */ SnapshotControl snapshotControl = (new SnapshotControl(database, false, types.toArray(new Class[types.size()]))); snapshotControl.setWarnIfObjectNotFound(false); if (createSnapshot(example, database,snapshotControl) != null) { return true; } CatalogAndSchema catalogAndSchema; if (example.getSchema() == null) { catalogAndSchema = database.getDefaultSchema(); } else { catalogAndSchema = example.getSchema().toCatalogAndSchema(); } DatabaseSnapshot snapshot = createSnapshot(catalogAndSchema, database, new SnapshotControl(database, false, example.getClass()).setWarnIfObjectNotFound(false) ); for (DatabaseObject obj : snapshot.get(example.getClass())) { if (DatabaseObjectComparatorFactory.getInstance().isSameObject(example, obj, null, database)) { return true; } } return false; }
java
{ "resource": "" }
q165595
SnapshotGeneratorFactory.createSnapshot
validation
public DatabaseSnapshot createSnapshot(DatabaseObject[] examples, Database database, SnapshotControl snapshotControl) throws DatabaseException, InvalidExampleException { DatabaseConnection conn = database.getConnection(); if (conn == null) { return new EmptyDatabaseSnapshot(database, snapshotControl); } if (conn instanceof OfflineConnection) { DatabaseSnapshot snapshot = ((OfflineConnection) conn).getSnapshot(examples); if (snapshot == null) { throw new DatabaseException("No snapshotFile parameter specified for offline database"); } return snapshot; } return new JdbcDatabaseSnapshot(examples, database, snapshotControl); }
java
{ "resource": "" }
q165596
SnapshotGeneratorFactory.createSnapshot
validation
public <T extends DatabaseObject> T createSnapshot(T example, Database database) throws DatabaseException, InvalidExampleException { return createSnapshot(example, database, new SnapshotControl(database)); }
java
{ "resource": "" }
q165597
DropAllForeignKeyConstraintsChange.generateChildren
validation
private List<DropForeignKeyConstraintChange> generateChildren(Database database) { // Make a new list List<DropForeignKeyConstraintChange> childDropChanges = new ArrayList<>(); try { SnapshotControl control = new SnapshotControl(database); control.getTypesToInclude().add(ForeignKey.class); CatalogAndSchema catalogAndSchema = new CatalogAndSchema(getBaseTableCatalogName(), getBaseTableSchemaName()); catalogAndSchema = catalogAndSchema.standardize(database); Table target = SnapshotGeneratorFactory.getInstance().createSnapshot( new Table(catalogAndSchema.getCatalogName(), catalogAndSchema.getSchemaName(), database.correctObjectName(getBaseTableName(), Table.class)) , database); List<ForeignKey> results = ((target == null) ? null : target.getOutgoingForeignKeys()); Set<String> handledConstraints = new HashSet<>(); if ((results != null) && (!results.isEmpty())) { for (ForeignKey fk : results) { Table baseTable = fk.getForeignKeyTable(); String constraintName = fk.getName(); if (DatabaseObjectComparatorFactory.getInstance().isSameObject( baseTable, target, null, database )) { if( !handledConstraints.contains(constraintName)) { DropForeignKeyConstraintChange dropForeignKeyConstraintChange = new DropForeignKeyConstraintChange(); dropForeignKeyConstraintChange.setBaseTableSchemaName(getBaseTableSchemaName()); dropForeignKeyConstraintChange.setBaseTableName(baseTableName); dropForeignKeyConstraintChange.setConstraintName(constraintName); childDropChanges.add(dropForeignKeyConstraintChange); handledConstraints.add(constraintName); } } else { throw new UnexpectedLiquibaseException( "Expected to return only foreign keys for base table name: " + getBaseTableName() + " and got results for table: " + baseTableName); } } } return childDropChanges; } catch (DatabaseException | InvalidExampleException e) { throw new UnexpectedLiquibaseException("Failed to find foreign keys for table: " + getBaseTableName(), e); } }
java
{ "resource": "" }
q165598
FileUtil.cleanDirectory
validation
private static void cleanDirectory(final File directory) throws IOException { if ( !directory.exists() ) { return; } if ( !directory.isDirectory() ) { return; } IOException exception = null; final File[] files = directory.listFiles(); if (files != null) { for (final File file : files) { try { cleanDirectory(file); if (!file.delete()) { throw new IOException("Cannot delete "+file.getAbsolutePath()); } } catch (final IOException ioe) { exception = ioe; } } } if ( null != exception ) { throw exception; } }
java
{ "resource": "" }
q165599
StringUtil.splitSQL
validation
public static String[] splitSQL(String multiLineSQL, String endDelimiter) { return processMutliLineSQL(multiLineSQL, false, true, endDelimiter); }
java
{ "resource": "" }