Example usage for java.sql Connection setAutoCommit

List of usage examples for java.sql Connection setAutoCommit

Introduction

In this page you can find the example usage for java.sql Connection setAutoCommit.

Prototype

void setAutoCommit(boolean autoCommit) throws SQLException;

Source Link

Document

Sets this connection's auto-commit mode to the given state.

Usage

From source file:com.tacitknowledge.util.migration.jdbc.JdbcMigrationLauncher.java

/**
 * Performs the application migration process in one go
 *
 * @param context the database context to run the patches in
 * @return the number of patches applied
 * @throws SQLException       if an unrecoverable database error occurs while working with the patches table.
 * @throws MigrationException if an unrecoverable error occurs during the migration
 *//*from w  ww  . jav  a 2 s .  c  o  m*/
protected int doMigrations(JdbcMigrationContext context) throws SQLException, MigrationException {
    PatchInfoStore patchTable = createPatchStore(context);

    lockPatchStore(context);

    // Now apply the patches
    int executedPatchCount = 0;
    try {

        // remember the auto-commit state, and turn auto-commit off
        Connection conn = context.getConnection();
        boolean commitState = conn.getAutoCommit();
        conn.setAutoCommit(false);

        // run the migrations
        try {
            executedPatchCount = migrationProcess.doMigrations(patchTable, context);
        }

        // restore autocommit state
        finally {
            if ((conn != null) && !conn.isClosed()) {
                conn.setAutoCommit(commitState);
            }
        }
    } catch (MigrationException me) {
        // If there was any kind of error, we don't want to eat it, but we do
        // want to unlock the patch store. So do that, then re-throw.
        patchTable.unlockPatchStore();
        throw me;
    }

    // Do any post-patch tasks
    try {
        migrationProcess.doPostPatchMigrations(context);
        return executedPatchCount;
    } finally {
        try {
            patchTable.unlockPatchStore();
        } catch (MigrationException e) {
            log.error("Error unlocking patch table: ", e);
        }
    }
}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.internal.jdbc.JDBCInternalStorage.java

/**
 * Updates the user in the internal storage 
 * @see IInternalStorage#update(ProvisioningUser)
 *//*from  w  ww  .  ja  v a2s  .co m*/
public void update(ProvisioningUser user) throws UserException {
    Connection oConnection = null;
    try {
        oConnection = _oDataSource.getConnection();
        oConnection.setAutoCommit(false);

        updateProfile(oConnection, user);

        oConnection.commit();
    } catch (UserException e) {
        rollback(oConnection);
        throw e;
    } catch (Exception e) {
        rollback(oConnection);
        _logger.fatal("Could not update user", e);
        throw new UserException(SystemErrors.ERROR_INTERNAL);
    } finally {
        try {
            if (oConnection != null)
                oConnection.close();
        } catch (Exception e) {
            _logger.error("Could not close connection", e);
        }
    }
}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.internal.jdbc.JDBCInternalStorage.java

/**
 * Removes a user with the supplied id.//www.  j  a  va  2s.  c o  m
 * @see com.alfaariss.oa.engine.user.provisioning.storage.internal.IInternalStorage#remove(java.lang.String)
 */
public void remove(String id) throws UserException {
    Connection oConnection = null;
    try {
        oConnection = _oDataSource.getConnection();
        oConnection.setAutoCommit(false);

        remove(oConnection, id);

        oConnection.commit();
    } catch (UserException e) {
        rollback(oConnection);
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not store user with id: " + id, e);
        rollback(oConnection);
        throw new UserException(SystemErrors.ERROR_INTERNAL);
    } finally {
        try {
            if (oConnection != null)
                oConnection.close();
        } catch (Exception e) {
            _logger.error("Could not close connection", e);
        }
    }
}

From source file:com.tacitknowledge.util.migration.jdbc.JdbcMigrationLauncher.java

/**
 * Performs the application rollbacks/*from w w  w . j a  v  a 2s .  c  om*/
 *
 * @param context       the database context to run the patches in
 * @param rollbackLevel the level the system should rollback to
 * @param forceRollback is a boolean indicating if the application should ignore a check to see if all patches are rollbackable
 * @return the number of patches applied
 * @throws SQLException       if an unrecoverable database error occurs while working with the patches table.
 * @throws MigrationException if an unrecoverable error occurs during the migration
 */
public int doRollbacks(JdbcMigrationContext context, int[] rollbackLevel, boolean forceRollback)
        throws SQLException, MigrationException {
    PatchInfoStore patchTable = createPatchStore(context);

    lockPatchStore(context);

    // Now apply the patches
    int executedPatchCount = 0;
    try {

        // remember the auto-commit state, and turn auto-commit off
        Connection conn = context.getConnection();
        boolean commitState = conn.getAutoCommit();
        conn.setAutoCommit(false);

        // run the rollbacks
        try {
            executedPatchCount = migrationProcess.doRollbacks(patchTable, rollbackLevel, context,
                    forceRollback);
        }

        // restore autocommit state
        finally {
            if ((conn != null) && !conn.isClosed()) {
                conn.setAutoCommit(commitState);
            }
        }
    } catch (MigrationException me) {
        // If there was any kind of error, we don't want to eat it, but we do
        // want to unlock the patch store. So do that, then re-throw.
        patchTable.unlockPatchStore();
        throw me;
    }

    // Do any post-patch tasks
    try {
        migrationProcess.doPostPatchMigrations(context);
        return executedPatchCount;
    } finally {
        try {
            patchTable.unlockPatchStore();
        } catch (MigrationException e) {
            log.error("Error unlocking patch table: ", e);
        }
    }
}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.internal.jdbc.JDBCInternalStorage.java

/**
 * Adds the supplied user to the internal storage.
 * @see IInternalStorage#add(ProvisioningUser)
 */// ww w  . ja v a  2s. c om
public void add(ProvisioningUser user) throws UserException {
    Connection oConnection = null;
    try {
        oConnection = _oDataSource.getConnection();
        oConnection.setAutoCommit(false);

        insertAccount(oConnection, user);

        Set<String> setMethods = user.getAuthenticationMethods();
        for (String sMethod : setMethods)
            insertProfile(oConnection, user, sMethod);

        oConnection.commit();
    } catch (UserException e) {
        rollback(oConnection);
        throw e;
    } catch (Exception e) {
        rollback(oConnection);
        _logger.fatal("Could not store", e);
        throw new UserException(SystemErrors.ERROR_INTERNAL);
    } finally {
        try {
            if (oConnection != null)
                oConnection.close();
        } catch (Exception e) {
            _logger.error("Could not close connection", e);
        }
    }
}

From source file:com.cws.esolutions.core.dao.impl.ApplicationDataDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IApplicationDataDAO#getApplication(java.lang.String)
 *//*from   w  ww  .  j ava 2s  . com*/
public synchronized List<Object> getApplication(final String value) throws SQLException {
    final String methodName = IApplicationDataDAO.CNAME
            + "#getApplication(final String value) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("value: {}", value);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<Object> responseData = null;

    try {
        sqlConn = dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);
        stmt = sqlConn.prepareCall("{CALL getApplicationData(?)}");
        stmt.setString(1, value);

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        if (stmt.execute()) {
            resultSet = stmt.getResultSet();

            if (DEBUG) {
                DEBUGGER.debug("resultSet: {}", resultSet);
            }

            if (resultSet.next()) {
                resultSet.first();

                responseData = new ArrayList<Object>(Arrays.asList(resultSet.getString(1), // APPLICATION_GUID
                        resultSet.getString(2), // APPLICATION_NAME
                        resultSet.getDouble(3), // APPLICATION_VERSION
                        resultSet.getString(4), // INSTALLATION_PATH
                        resultSet.getString(5), // PACKAGE_LOCATION
                        resultSet.getString(6), // PACKAGE_INSTALLER
                        resultSet.getString(7), // INSTALLER_OPTIONS
                        resultSet.getString(8), // LOGS_DIRECTORY
                        resultSet.getString(9) // PLATFORM_GUID
                ));

                if (DEBUG) {
                    DEBUGGER.debug("data: {}", responseData);
                }
            }
        }
    } catch (SQLException sqx) {
        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }

        if (stmt != null) {
            stmt.close();
        }

        if ((sqlConn != null) && (!(sqlConn.isClosed()))) {
            sqlConn.close();
        }
    }

    return responseData;
}

From source file:com.adaptris.core.jdbc.DatabaseConnection.java

/**
 * <p>/*from   w ww.j  ava 2 s. c o  m*/
 * Initiate a connection to the database.
 * </p>
 * 
 * @throws SQLException if connection fails after exhausting the specified number of retry attempts
 */
private Connection attemptConnect() throws SQLException {
    int attemptCount = 0;
    Connection sqlConnection = null;
    while (sqlConnection == null) {
        checkInternalState();
        try {
            attemptCount++;
            sqlConnection = makeConnection();
            if (sqlConnection.getAutoCommit() != autoCommit()) {
                sqlConnection.setAutoCommit(autoCommit());
            }
        } catch (SQLException e) {
            if (logWarning(attemptCount)) {
                log.warn("Connection attempt [{}] failed for {}", attemptCount, getConnectionName(), e);
            }
            if (connectionAttempts() != -1 && attemptCount >= connectionAttempts()) {
                log.error("Failed to make any Jdbc Connections");
                throw e;
            } else {
                log.trace(createLoggingStatement(attemptCount));
                try {
                    Thread.sleep(connectionRetryInterval());
                } catch (InterruptedException e2) {
                    throw new SQLException(e2);
                }
                continue;
            }
        }
    }
    return sqlConnection;
}

From source file:com.cws.esolutions.core.dao.impl.ApplicationDataDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IApplicationDataDAO#listApplications(int)
 *///from  w ww.  j  a v  a  2s.  com
public synchronized List<String[]> listApplications(final int startRow) throws SQLException {
    final String methodName = IApplicationDataDAO.CNAME
            + "#listApplications(final int startRow) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", startRow);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<String[]> responseData = null;

    try {
        sqlConn = dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);

        stmt = sqlConn.prepareCall("{CALL listApplications(?, ?)}");
        stmt.setInt(1, startRow);
        stmt.registerOutParameter(2, Types.INTEGER);

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        if (stmt.execute()) {
            resultSet = stmt.getResultSet();

            if (DEBUG) {
                DEBUGGER.debug("resultSet: {}", resultSet);
            }

            if (resultSet.next()) {
                resultSet.beforeFirst();
                responseData = new ArrayList<String[]>();

                while (resultSet.next()) {
                    String[] data = new String[] { resultSet.getString(1), // APPLICATION_GUID
                            resultSet.getString(2), // APPLICATION_NAME
                    };

                    if (DEBUG) {
                        DEBUGGER.debug("Value: {}", (Object[]) data);
                    }

                    responseData.add(data);
                }

                if (DEBUG) {
                    DEBUGGER.debug("Value: {}", responseData);
                }
            }
        }
    } catch (SQLException sqx) {
        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }

        if (stmt != null) {
            stmt.close();
        }

        if ((sqlConn != null) && (!(sqlConn.isClosed()))) {
            sqlConn.close();
        }
    }

    return responseData;
}

From source file:com.cws.esolutions.security.dao.userauth.impl.SQLAuthenticator.java

/**
 * @see com.cws.esolutions.security.dao.userauth.interfaces.Authenticator#performLogon(java.lang.String, java.lang.String)
 *///from w  w  w  .j a va  2s .  co  m
public synchronized List<Object> performLogon(final String username, final String password)
        throws AuthenticatorException {
    final String methodName = SQLAuthenticator.CNAME
            + "#performLogon(final String user, final String password) throws AuthenticatorException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("String: {}", username);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<Object> userAccount = null;

    try {
        sqlConn = SQLAuthenticator.dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);

        stmt = sqlConn.prepareCall("{CALL performAuthentication(?, ?)}");
        stmt.setString(1, username); // username
        stmt.setString(2, password); // password

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        if (!(stmt.execute())) {
            throw new AuthenticatorException("No user was found for the provided user information");
        }

        resultSet = stmt.getResultSet();

        if (DEBUG) {
            DEBUGGER.debug("ResultSet: {}", resultSet);
        }

        if (resultSet.next()) {
            resultSet.first();

            userAccount = new ArrayList<Object>();

            for (String returningAttribute : userAttributes.getReturningAttributes()) {
                if (DEBUG) {
                    DEBUGGER.debug("returningAttribute: {}", returningAttribute);
                }

                userAccount.add(resultSet.getString(returningAttribute));
            }

            if (DEBUG) {
                DEBUGGER.debug("List<Object>: {}", userAccount);
            }
        }
    } catch (SQLException sqx) {
        throw new AuthenticatorException(sqx.getMessage(), sqx);
    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
            }

            if (stmt != null) {
                stmt.close();
            }

            if (!(sqlConn == null) && (!(sqlConn.isClosed()))) {
                sqlConn.close();
            }
        } catch (SQLException sqx) {
            throw new AuthenticatorException(sqx.getMessage(), sqx);
        }
    }

    return userAccount;
}

From source file:com.wso2telco.workflow.dao.WorkflowDbService.java

/**
 * Insert operator app endpoints./*from  ww w  .  j a va2s  .co  m*/
 *
 * @param appID            the app id
 * @param opEndpointIDList the op endpoint id list
 * @throws Exception the exception
 */

public void insertOperatorAppEndpoints(int appID, int[] opEndpointIDList)
        throws SQLException, BusinessException {

    Connection con = null;
    Statement st = null;

    try {
        con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);
        log.debug("opEndpointIDList.length : " + opEndpointIDList.length);
        con.setAutoCommit(false);
        st = con.createStatement();
        for (int i = 0; i < opEndpointIDList.length; i++) {
            if (opEndpointIDList[i] > 0 && !endpointAppsIsExist(opEndpointIDList[i], appID)) {
                StringBuilder query = new StringBuilder();
                query.append("INSERT INTO endpointapps (endpointid, applicationid, isactive) VALUES ");
                query.append("(" + opEndpointIDList[i] + "," + appID + ",0)");
                st.addBatch(query.toString());
            }
        }
        st.executeBatch();
        con.commit();

    } catch (SQLException e) {
        throw new SQLException();
    } catch (Exception e) {
        throw new BusinessException(GenaralError.UNDEFINED);
    } finally {
        DbUtils.closeAllConnections(st, con, null);
    }
}