Search in sources :

Example 36 with CustomChangeException

use of liquibase.exception.CustomChangeException in project openmrs-core by openmrs.

the class MigrateDrugOrderUnitsToCodedDoseUnitsChangeset method migrateUnitsToCodedValue.

private void migrateUnitsToCodedValue(JdbcConnection connection, Set<String> uniqueUnits) throws CustomChangeException, SQLException, DatabaseException {
    PreparedStatement updateDrugOrderStatement = null;
    Boolean autoCommit = null;
    try {
        autoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        updateDrugOrderStatement = connection.prepareStatement("update drug_order set dose_units = ? where units = ?");
        updateDrugOrderStatement.setNull(1, Types.INTEGER);
        updateDrugOrderStatement.setNull(2, Types.VARCHAR);
        updateDrugOrderStatement.executeUpdate();
        updateDrugOrderStatement.clearParameters();
        for (String unit : uniqueUnits) {
            if (StringUtils.isBlank(unit)) {
                updateDrugOrderStatement.setNull(1, Types.INTEGER);
            } else {
                Integer conceptIdForUnit = UpgradeUtil.getConceptIdForUnits(unit);
                if (conceptIdForUnit == null) {
                    throw new CustomChangeException("No concept mapping found for unit: " + unit);
                }
                String dosingUnitsConceptSetUuid = UpgradeUtil.getGlobalProperty(connection.getUnderlyingConnection(), OpenmrsConstants.GP_DRUG_DOSING_UNITS_CONCEPT_UUID);
                List<Integer> dosingUnitsconceptIds = UpgradeUtil.getMemberSetIds(connection.getUnderlyingConnection(), dosingUnitsConceptSetUuid);
                if (!dosingUnitsconceptIds.contains(conceptIdForUnit)) {
                    throw new CustomChangeException("Dosing unit '" + unit + "' is not among valid concepts defined in global property " + OpenmrsConstants.GP_DRUG_DOSING_UNITS_CONCEPT_UUID);
                }
                updateDrugOrderStatement.setInt(1, conceptIdForUnit);
            }
            updateDrugOrderStatement.setString(2, unit);
            updateDrugOrderStatement.executeUpdate();
            updateDrugOrderStatement.clearParameters();
        }
        connection.commit();
    } catch (DatabaseException | SQLException e) {
        handleError(connection, e);
    } finally {
        if (autoCommit != null) {
            connection.setAutoCommit(autoCommit);
        }
        if (updateDrugOrderStatement != null) {
            updateDrugOrderStatement.close();
        }
    }
}
Also used : SQLException(java.sql.SQLException) CustomChangeException(liquibase.exception.CustomChangeException) PreparedStatement(java.sql.PreparedStatement) DatabaseException(liquibase.exception.DatabaseException)

Example 37 with CustomChangeException

use of liquibase.exception.CustomChangeException in project openmrs-core by openmrs.

the class EncryptSecretAnswersChangeSet method execute.

/**
 * @see CustomTaskChange#execute(Database)
 */
@Override
public void execute(Database database) throws CustomChangeException {
    JdbcConnection connection = (JdbcConnection) database.getConnection();
    Statement stmt = null;
    PreparedStatement pStmt = null;
    try {
        stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT user_id, salt, secret_answer FROM users WHERE secret_answer IS NOT NULL");
        pStmt = connection.prepareStatement("UPDATE users SET secret_answer = ? WHERE user_id = ?");
        while (rs.next()) {
            String answer = rs.getString("secret_answer");
            String salt = rs.getString("salt");
            String encryptedAnswer = Security.encodeString(answer.toLowerCase() + salt);
            pStmt.setString(1, encryptedAnswer);
            pStmt.setInt(2, rs.getInt("user_id"));
            pStmt.addBatch();
        }
        pStmt.executeBatch();
    } catch (DatabaseException | SQLException e) {
        throw new CustomChangeException("Failed to update secret answers: " + e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                log.warn("Failed to close the statement object");
            }
        }
        if (pStmt != null) {
            try {
                pStmt.close();
            } catch (SQLException e) {
                log.warn("Failed to close the prepared statement object");
            }
        }
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) CustomChangeException(liquibase.exception.CustomChangeException) JdbcConnection(liquibase.database.jvm.JdbcConnection) PreparedStatement(java.sql.PreparedStatement) DatabaseException(liquibase.exception.DatabaseException)

Example 38 with CustomChangeException

use of liquibase.exception.CustomChangeException in project dropwizard by dropwizard.

the class LiquibaseScopingTest method execute.

@Override
public void execute(Database database) throws CustomChangeException {
    if (!Scope.getCurrentScope().has("person")) {
        throw new CustomChangeException("No Person provided");
    }
    Person person = Scope.getCurrentScope().get("person", Person.class);
    JdbcConnection connection = (JdbcConnection) database.getConnection();
    try {
        PreparedStatement statement = connection.prepareStatement("INSERT INTO persons (name) VALUES (?);");
        statement.setString(1, person.getName());
        statement.execute();
    } catch (Exception e) {
        throw new CustomChangeException(e);
    }
}
Also used : CustomChangeException(liquibase.exception.CustomChangeException) JdbcConnection(liquibase.database.jvm.JdbcConnection) PreparedStatement(java.sql.PreparedStatement) CustomChangeException(liquibase.exception.CustomChangeException) LiquibaseException(liquibase.exception.LiquibaseException)

Example 39 with CustomChangeException

use of liquibase.exception.CustomChangeException in project keycloak by keycloak.

the class AddRealmCodeSecret method generateStatements.

@Override
public SqlStatement[] generateStatements(Database database) throws CustomChangeException {
    try {
        StringBuilder sb = new StringBuilder();
        sb.append("Generated codeSecret for realms: ");
        Connection connection = ((JdbcConnection) (database.getConnection())).getWrappedConnection();
        ArrayList<SqlStatement> statements = new ArrayList<SqlStatement>();
        String correctedTableName = database.correctObjectName("REALM", Table.class);
        String correctedSchemaName = database.escapeObjectName(database.getDefaultSchemaName(), Schema.class);
        if (SnapshotGeneratorFactory.getInstance().has(new Table().setName(correctedTableName), database)) {
            try (Statement st = connection.createStatement();
                ResultSet resultSet = st.executeQuery("SELECT ID FROM " + LiquibaseJpaUpdaterProvider.getTable(correctedTableName, correctedSchemaName) + " WHERE CODE_SECRET IS NULL")) {
                while (resultSet.next()) {
                    String id = resultSet.getString(1);
                    UpdateStatement statement = new UpdateStatement(null, null, correctedTableName).addNewColumnValue("CODE_SECRET", KeycloakModelUtils.generateCodeSecret()).setWhereClause("ID=?").addWhereParameters(id);
                    statements.add(statement);
                    if (!resultSet.isFirst()) {
                        sb.append(", ");
                    }
                    sb.append(id);
                }
                if (!statements.isEmpty()) {
                    confirmationMessage = sb.toString();
                }
            }
        }
        return statements.toArray(new SqlStatement[statements.size()]);
    } catch (Exception e) {
        throw new CustomChangeException("Failed to add realm code secret", e);
    }
}
Also used : UpdateStatement(liquibase.statement.core.UpdateStatement) Table(liquibase.structure.core.Table) UpdateStatement(liquibase.statement.core.UpdateStatement) SqlStatement(liquibase.statement.SqlStatement) Statement(java.sql.Statement) Connection(java.sql.Connection) JdbcConnection(liquibase.database.jvm.JdbcConnection) ArrayList(java.util.ArrayList) CustomChangeException(liquibase.exception.CustomChangeException) JdbcConnection(liquibase.database.jvm.JdbcConnection) CustomChangeException(liquibase.exception.CustomChangeException) SetupException(liquibase.exception.SetupException) SqlStatement(liquibase.statement.SqlStatement) ResultSet(java.sql.ResultSet)

Example 40 with CustomChangeException

use of liquibase.exception.CustomChangeException in project keycloak by keycloak.

the class ExtractRealmKeysFromRealmTable method generateStatementsImpl.

@Override
protected void generateStatementsImpl() throws CustomChangeException {
    try {
        PreparedStatement statement = jdbcConnection.prepareStatement("select ID, PRIVATE_KEY, CERTIFICATE from " + getTableName("REALM"));
        try {
            ResultSet resultSet = statement.executeQuery();
            try {
                while (resultSet.next()) {
                    String realmId = resultSet.getString(1);
                    String privateKeyPem = resultSet.getString(2);
                    String certificatePem = resultSet.getString(3);
                    String componentId = KeycloakModelUtils.generateId();
                    InsertStatement insertComponent = new InsertStatement(null, null, database.correctObjectName("COMPONENT", Table.class)).addColumnValue("ID", componentId).addColumnValue("REALM_ID", realmId).addColumnValue("PARENT_ID", realmId).addColumnValue("NAME", "rsa").addColumnValue("PROVIDER_ID", "rsa").addColumnValue("PROVIDER_TYPE", KeyProvider.class.getName());
                    statements.add(insertComponent);
                    statements.add(componentConfigStatement(componentId, "priority", "100"));
                    statements.add(componentConfigStatement(componentId, "privateKey", privateKeyPem));
                    statements.add(componentConfigStatement(componentId, "certificate", certificatePem));
                }
            } finally {
                resultSet.close();
            }
        } finally {
            statement.close();
        }
        confirmationMessage.append("Updated " + statements.size() + " records in USER_FEDERATION_PROVIDER table");
    } catch (Exception e) {
        throw new CustomChangeException(getTaskId() + ": Exception when updating data from previous version", e);
    }
}
Also used : KeyProvider(org.keycloak.keys.KeyProvider) Table(liquibase.structure.core.Table) ResultSet(java.sql.ResultSet) CustomChangeException(liquibase.exception.CustomChangeException) PreparedStatement(java.sql.PreparedStatement) InsertStatement(liquibase.statement.core.InsertStatement) CustomChangeException(liquibase.exception.CustomChangeException)

Aggregations

CustomChangeException (liquibase.exception.CustomChangeException)46 PreparedStatement (java.sql.PreparedStatement)33 ResultSet (java.sql.ResultSet)26 DatabaseException (liquibase.exception.DatabaseException)26 SQLException (java.sql.SQLException)25 JdbcConnection (liquibase.database.jvm.JdbcConnection)21 SetupException (liquibase.exception.SetupException)16 Statement (java.sql.Statement)8 ArrayList (java.util.ArrayList)6 InsertStatement (liquibase.statement.core.InsertStatement)6 Table (liquibase.structure.core.Table)6 Date (java.sql.Date)5 HashMap (java.util.HashMap)5 Map (java.util.Map)5 BatchUpdateException (java.sql.BatchUpdateException)4 Connection (java.sql.Connection)4 HashSet (java.util.HashSet)4 List (java.util.List)4 UpdateStatement (liquibase.statement.core.UpdateStatement)4 SqlStatement (liquibase.statement.SqlStatement)3