Example usage for java.sql Connection getAutoCommit

List of usage examples for java.sql Connection getAutoCommit

Introduction

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

Prototype

boolean getAutoCommit() throws SQLException;

Source Link

Document

Retrieves the current auto-commit mode for this Connection object.

Usage

From source file:it.doqui.index.ecmengine.business.personalization.hibernate.RoutingLocalSessionFactoryBean.java

/**
 * Execute the given schema script on the given JDBC Connection.
 * <p>Note that the default implementation will log unsuccessful statements
 * and continue to execute. Override the <code>executeSchemaStatement</code>
 * method to treat failures differently.
 * @param con the JDBC Connection to execute the script on
 * @param sql the SQL statements to execute
 * @throws SQLException if thrown by JDBC methods
 * @see #executeSchemaStatement//from  w  w  w  . j av  a  2  s  .  co  m
 */
protected void executeSchemaScript(Connection con, String[] sql) throws SQLException {
    if (sql != null && sql.length > 0) {
        boolean oldAutoCommit = con.getAutoCommit();
        if (!oldAutoCommit) {
            con.setAutoCommit(true);
        }
        try {
            Statement stmt = con.createStatement();
            try {
                for (int i = 0; i < sql.length; i++) {
                    executeSchemaStatement(stmt, sql[i]);
                }
            } finally {
                JdbcUtils.closeStatement(stmt);
            }
        } finally {
            if (!oldAutoCommit) {
                con.setAutoCommit(false);
            }
        }
    }
}

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

/**
 * Test that sybase database patches are committed when illegal multi
 * statement transaction commands are used.
 * //from   ww  w. j  a  v  a2 s. c  o m
 * @throws IOException
 *                 if an unexpected error occurs
 * @throws MigrationException
 *                 if an unexpected error occurs
 * @throws SQLException
 *                 if an unexpected error occurs
 */
public void testSybasePatchesCommitsOnEveryStatement() throws IOException, MigrationException, SQLException {
    InputStream is = getClass().getResourceAsStream("test/sybase_tsql.sql");
    assertNotNull(is);
    task = new SqlScriptMigrationTask("sybase_tsql.sql", 1, is);

    MockDatabaseType dbType = new MockDatabaseType("sybase");
    dbType.setMultipleStatementsSupported(false);
    context.setDatabaseType(dbType);
    int numStatements = task.getSqlStatements(context).size();

    // setup mocks to verify commits are called
    MockControl dataSourceControl = MockControl.createControl(DataSource.class);
    DataSource dataSource = (DataSource) dataSourceControl.getMock();
    context.setDataSource(dataSource);

    MockControl connectionControl = MockControl.createControl(Connection.class);
    Connection connection = (Connection) connectionControl.getMock();

    dataSourceControl.expectAndReturn(dataSource.getConnection(), connection);

    MockControl statementControl = MockControl.createControl(Statement.class);
    Statement statement = (Statement) statementControl.getMock();
    statement.execute("");
    statementControl.setMatcher(MockControl.ALWAYS_MATCHER);
    statementControl.setReturnValue(true, MockControl.ONE_OR_MORE);
    statement.close();
    statementControl.setVoidCallable(MockControl.ONE_OR_MORE);

    connectionControl.expectAndReturn(connection.isClosed(), false, MockControl.ONE_OR_MORE);
    connectionControl.expectAndReturn(connection.createStatement(), statement, numStatements);
    connectionControl.expectAndReturn(connection.getAutoCommit(), false, MockControl.ONE_OR_MORE);
    connection.commit();
    /*
     * Magic Number 4 derived from the assumption that the fixture sql
     * contains only one statement that is not allowed in a multi statement
     * transaction: commit at beginning of migrate method commit prior to
     * running the command not allowed in multi statement transaction to
     * clear the transaction state. commit after running the multi statement
     * transaction to clear transaction state for upcoming statements.
     * commit at end of migrate method once all statements executed.
     * 
     * Therefore, if you add more illegal statements to the fixture, add 2
     * more commit call's for each illegal statement.
     */
    connectionControl.setVoidCallable(4);

    dataSourceControl.replay();
    connectionControl.replay();
    statementControl.replay();

    // run tests
    task.migrate(context);
    dataSourceControl.verify();
    connectionControl.verify();
}

From source file:org.wso2.carbon.identity.application.authentication.framework.store.SessionDataStore.java

public void removeSessionData(String key, String type, Timestamp timestamp) {
    if (!enablePersist) {
        return;//from www .  jav  a  2s. co  m
    }
    Connection connection = null;
    try {
        connection = IdentityDatabaseUtil.getDBConnection();
    } catch (IdentityRuntimeException e) {
        log.error(e.getMessage(), e);
        return;
    }
    PreparedStatement preparedStatement = null;
    try {
        preparedStatement = connection.prepareStatement(sqlInsertDELETE);
        preparedStatement.setString(1, key);
        preparedStatement.setString(2, type);
        preparedStatement.setString(3, OPERATION_DELETE);
        preparedStatement.setLong(4, timestamp.getTime());
        preparedStatement.executeUpdate();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
    } catch (Exception e) {
        log.error("Error while storing DELETE operation session data", e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, preparedStatement);
    }
}

From source file:com.wabacus.system.dataset.update.action.rationaldb.AbsRationalDBUpdateAction.java

public void beginTransaction(ReportRequest rrequest) {
    Connection conn = rrequest.getConnection(this.datasource);
    String dsLevel = rrequest.getTransactionLevel(this.datasource);
    if (dsLevel != null && !dsLevel.trim().equals("")) {
        if (!Consts_Private.M_ALL_TRANSACTION_LEVELS.containsKey(dsLevel)) {
            throw new WabacusRuntimeException("?" + rrequest.getPagebean().getId() + "??"
                    + this.datasource + "" + dsLevel
                    + "????");
        }/*from   w w  w .  j  a  v a  2  s  . c  om*/
        if (dsLevel.equals(Consts.TRANS_NONE))
            return;
    }
    try {
        if (!conn.getAutoCommit())
            return;
        conn.setAutoCommit(false);
        if (!Tools.isEmpty(dsLevel))
            conn.setTransactionIsolation(Consts_Private.M_ALL_TRANSACTION_LEVELS.get(dsLevel));
    } catch (SQLException e) {
        throw new WabacusRuntimeException(
                "?" + this.ownerUpdateBean.getOwner().getReportBean().getPath() + "??"
                        + this.datasource + "",
                e);
    }
}

From source file:com.concursive.connect.web.modules.register.beans.RegisterBean.java

/**
 * Description of the Method/*from w  w w. ja v  a 2 s. c om*/
 *
 * @param db      Description of the Parameter
 * @param prefs   Description of the Parameter
 * @param request Description of the Parameter
 * @param userIp  The user's ip address in which the registration was made from
 * @return Description of the Return Value
 * @throws SQLException Description of the Exception
 */
public boolean save(Connection db, ApplicationPrefs prefs, ActionRequest request, String userIp)
        throws SQLException {
    // Remove the captcha's session value
    request.getPortletSession().removeAttribute("TE-REGISTER-CAPTCHA-PASSED");
    // Determine the user's password
    password = String.valueOf(StringUtils.rand(100000, 999999));
    encryptedPassword = PasswordHash.encrypt(password);
    // NOTE: A confirmation message will be sent by the workflow
    boolean commit = db.getAutoCommit();
    try {
        if (commit) {
            db.setAutoCommit(false);
        }
        // Store the user in the database
        user = new User();
        user.setId(User.getIdByEmailAddress(db, email));
        user.setInstanceId(instanceId);
        user.setGroupId(1);
        user.setDepartmentId(1);
        user.setFirstName(nameFirst);
        user.setLastName(nameLast);
        user.setCompany(organization);
        user.setEmail(email);
        user.setUsername(email);
        user.setPassword(encryptedPassword);
        user.setEnteredBy(0);
        user.setModifiedBy(0);
        user.setEnabled(true);
        user.setStartPage(1);
        user.setRegistered(true);
        user.setTerms(terms);
        user.setAccountSize(prefs.get("ACCOUNT.SIZE"));
        user.setAccessAddProjects(prefs.get(ApplicationPrefs.USERS_CAN_START_PROJECTS));
        user.setCity(city);
        user.setState(state);
        user.setCountry(country);
        user.setPostalCode(postalCode);

        if (user.getId() == -1) {
            // This is a new user, so insert
            user.insert(db, userIp, prefs);
        } else {
            // Else set the status as registered and update the info
            updateRegisteredStatus(db, user);
        }
        if (commit) {
            db.commit();
        }
    } catch (Exception e) {
        LOG.error("save", e);
        if (commit) {
            db.rollback();
        }
        throw new SQLException(e.getMessage());
    } finally {
        if (commit) {
            db.setAutoCommit(true);
        }
    }
    // After the commit, reload the complete user record
    CacheUtils.invalidateValue(Constants.SYSTEM_USER_CACHE, user.getId());
    CacheUtils.invalidateValue(Constants.SYSTEM_PROJECT_CACHE, user.getProfileProjectId());
    user = UserUtils.loadUser(user.getId());
    this.setEntered(user.getEntered());
    this.setModified(user.getModified());
    return true;
}

From source file:org.wso2.carbon.dashboard.portal.core.datasource.DSDataSourceManager.java

/**
 * To check whether a dashboard related usage information is updated in database
 *
 * @param tenantId    Id of the tenant which the dashboard belongs to
 * @param dashboardId Id of the dashboard
 * @return whether a dashboard related information exist in database
 * @throws DashboardPortalException//from  w  w  w .  j a v a2s  .co  m
 */
public boolean checkDashboard(int tenantId, String dashboardId) throws DashboardPortalException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet;
    try {
        connection = dataSource.getConnection();
        preparedStatement = connection.prepareStatement(DataSourceConstants.SQL_CHECK_DASHBOARD_OPERATION);
        preparedStatement.setInt(1, tenantId);
        preparedStatement.setString(2, dashboardId);
        resultSet = preparedStatement.executeQuery();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
        if (resultSet.next()) {
            return true;
        }
    } catch (SQLException e) {
        log.error("Cannot insert the gadget usage info ", e);
    } finally {
        closeDatabaseResources(connection, preparedStatement, null);
    }
    return false;
}

From source file:org.flowable.common.engine.impl.db.LiquibaseBasedSchemaManager.java

protected Liquibase createLiquibaseInstance(LiquibaseDatabaseConfiguration databaseConfiguration)
        throws SQLException {
    Connection jdbcConnection = null;
    boolean closeConnection = false;
    try {//from w w  w .  j ava 2 s  .  co  m
        CommandContext commandContext = Context.getCommandContext();
        if (commandContext == null) {
            jdbcConnection = databaseConfiguration.getDataSource().getConnection();
            closeConnection = true;
        } else {
            jdbcConnection = commandContext.getSession(DbSqlSession.class).getSqlSession().getConnection();
        }

        // A commit is needed here, because one of the things that Liquibase does when acquiring its lock
        // is doing a rollback, which removes all changes done so far.
        // For most databases, this is not a problem as DDL statements are not transactional.
        // However for some (e.g. sql server), this would remove all previous statements, which is not wanted,
        // hence the extra commit here.
        if (!jdbcConnection.getAutoCommit()) {
            jdbcConnection.commit();
        }

        DatabaseConnection connection = new JdbcConnection(jdbcConnection);
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection);
        database.setDatabaseChangeLogTableName(changeLogPrefix + database.getDatabaseChangeLogTableName());
        database.setDatabaseChangeLogLockTableName(
                changeLogPrefix + database.getDatabaseChangeLogLockTableName());

        String databaseSchema = databaseConfiguration.getDatabaseSchema();
        if (StringUtils.isNotEmpty(databaseSchema)) {
            database.setDefaultSchemaName(databaseSchema);
            database.setLiquibaseSchemaName(databaseSchema);
        }

        String databaseCatalog = databaseConfiguration.getDatabaseCatalog();
        if (StringUtils.isNotEmpty(databaseCatalog)) {
            database.setDefaultCatalogName(databaseCatalog);
            database.setLiquibaseCatalogName(databaseCatalog);
        }

        return new Liquibase(changeLogFile, new ClassLoaderResourceAccessor(), database);

    } catch (Exception e) {
        // We only close the connection if an exception occurred, otherwise the Liquibase instance cannot be used
        if (jdbcConnection != null && closeConnection) {
            jdbcConnection.close();
        }
        throw new FlowableException("Error creating " + context + " liquibase instance", e);
    }
}

From source file:org.jumpmind.db.sql.JdbcSqlTemplate.java

public int update(final boolean autoCommit, final boolean failOnError, final boolean failOnDrops,
        final boolean failOnSequenceCreate, final int commitRate, final ISqlResultsListener resultsListener,
        final ISqlStatementSource source) {
    return execute(new IConnectionCallback<Integer>() {
        @SuppressWarnings("resource")
        public Integer execute(Connection con) throws SQLException {
            int totalUpdateCount = 0;
            boolean oldAutoCommitSetting = con.getAutoCommit();
            Statement stmt = null;
            try {
                con.setAutoCommit(autoCommit);
                stmt = con.createStatement();
                int statementCount = 0;
                for (String statement = source.readSqlStatement(); statement != null; statement = source
                        .readSqlStatement()) {
                    logSql(statement, null);
                    try {
                        boolean hasResults = stmt.execute(statement);
                        int updateCount = stmt.getUpdateCount();
                        totalUpdateCount += updateCount;
                        int rowsRetrieved = 0;
                        if (hasResults) {
                            ResultSet rs = null;
                            try {
                                rs = stmt.getResultSet();
                                while (rs.next()) {
                                    rowsRetrieved++;
                                }// w  ww. j a  v a  2s.c o  m
                            } finally {
                                close(rs);
                            }
                        }
                        if (resultsListener != null) {
                            resultsListener.sqlApplied(statement, updateCount, rowsRetrieved, statementCount);
                        }
                        statementCount++;
                        if (statementCount % commitRate == 0 && !autoCommit) {
                            con.commit();
                        }
                    } catch (SQLException ex) {
                        boolean isDrop = statement.toLowerCase().trim().startsWith("drop");
                        boolean isSequenceCreate = statement.toLowerCase().trim().startsWith("create sequence");
                        if (resultsListener != null) {
                            resultsListener.sqlErrored(statement, translate(statement, ex), statementCount,
                                    isDrop, isSequenceCreate);
                        }

                        if ((isDrop && !failOnDrops) || (isSequenceCreate && !failOnSequenceCreate)) {
                            log.debug("{}.  Failed to execute: {}", ex.getMessage(), statement);
                        } else {
                            log.warn("{}.  Failed to execute: {}", ex.getMessage(), statement);
                            if (failOnError) {
                                throw ex;
                            }
                        }

                    }
                }

                if (!autoCommit) {
                    con.commit();
                }
                return totalUpdateCount;
            } catch (SQLException ex) {
                if (!autoCommit) {
                    con.rollback();
                }
                throw ex;
            } finally {
                close(stmt);
                if (!con.isClosed()) {
                    con.setAutoCommit(oldAutoCommitSetting);
                }
            }
        }
    });
}

From source file:org.wso2.carbon.dashboard.portal.core.datasource.DSDataSourceManager.java

/**
 * To delete the gadget usage information of partciular gadget in particular dashboard
 *
 * @param tenantId    Id of the tenant, dashboard belongs to
 * @param dashboardId Id of the dashboard
 * @param gadgetId    Id of the gadget/*from   w  w w  .  ja v  a  2 s.  co  m*/
 * @throws DashboardPortalException
 */
public void deleteGadgetUsageInformation(int tenantId, String dashboardId, String gadgetId)
        throws DashboardPortalException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    try {
        connection = dataSource.getConnection();
        preparedStatement = connection.prepareStatement(DataSourceConstants.SQL_DELETE_GADGET_USAGE_OPERATION);
        preparedStatement.setInt(1, tenantId);
        preparedStatement.setString(2, dashboardId);
        preparedStatement.setString(3, gadgetId);
        preparedStatement.executeUpdate();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
    } catch (SQLException e) {
        log.error("Cannot insert the gadget usage info ", e);
    } finally {
        closeDatabaseResources(connection, preparedStatement, null);
    }
}

From source file:org.wso2.carbon.dashboard.portal.core.datasource.DSDataSourceManager.java

/**
 * To update the gadget state information
 *
 * @param tenantId    Id of the tenant which gadget belongs to
 * @param gadgetId    Id of the gadget//from  w ww .  j  av a 2s  . c o m
 * @param gadgetState State of the gadget, whether is it in active or delete state
 * @throws DashboardPortalException
 */
public void updateGadgetStateInformation(int tenantId, String gadgetId, String gadgetState)
        throws DashboardPortalException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    try {
        connection = dataSource.getConnection();
        preparedStatement = connection.prepareStatement(DataSourceConstants.SQL_UPDATE_GADGET_STATE_OPERATION);
        preparedStatement.setString(1, gadgetState);
        preparedStatement.setInt(2, tenantId);
        preparedStatement.setString(3, gadgetId);
        preparedStatement.executeUpdate();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
    } catch (SQLException e) {
        log.error("Cannot insert the gadget usage info ", e);
    } finally {
        closeDatabaseResources(connection, preparedStatement, null);
    }
}