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.moss.schematrax.SchemaUpdater.java

public synchronized void createOrUpdateSchema(DatabaseType databaseType, JdbcConnectionConfig connectionConfig,
        String schema) throws SchematraxException {
    try {//ww w  .  j  a  va  2s.co  m
        Class.forName(connectionConfig.getJdbcDriverClassName());
        Connection sqlConnection = DriverManager.getConnection(connectionConfig.getJdbcUrl(),
                connectionConfig.getLogon(), connectionConfig.getPassword());
        sqlConnection.setAutoCommit(false);

        createOrUpdateSchema(databaseType, sqlConnection, schema);

        sqlConnection.close();
    } catch (ClassNotFoundException e) {
        throw new SchematraxException(e);
    } catch (SQLException e) {
        throw new SchematraxException(e);
    }
}

From source file:com.wso2telco.dep.operatorservice.dao.BlackListWhiteListDAO.java

/**
 * when the subscription id is known/*from w ww  . j a va 2 s . c o  m*/
 *
 * @param userMSISDNs
 * @param subscriptionId
 * @param apiID
 * @param applicationID
 * @throws SQLException
 * @throws Exception
 */
public void whitelist(MSISDNValidationDTO msisdns, String subscriptionId, String apiID, String applicationID)
        throws Exception {

    StringBuilder sql = new StringBuilder();
    sql.append("INSERT INTO ");
    sql.append(OparatorTable.SUBSCRIPTION_WHITELIST.getTObject());
    sql.append(" (subscriptionID, prefix, msisdn, api_id, application_id, validation_regex)");
    sql.append(" VALUES (?,?,?,?,?,?);");

    Connection conn = null;
    PreparedStatement ps = null;

    try {
        conn = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB);
        ps = conn.prepareStatement(sql.toString());

        conn.setAutoCommit(false);
        for (MsisdnDTO msisdn : msisdns.getValidProcessed()) {

            ps.setString(1, subscriptionId);
            ps.setString(2, msisdn.getPrefix());
            ps.setString(3, msisdn.getDigits());
            ps.setString(4, apiID);
            ps.setString(5, applicationID);
            ps.setString(6, msisdns.getValidationRegex());

            ps.addBatch();
        }
        ps.executeBatch();
        conn.commit();

    } catch (Exception e) {
        if (conn != null) {
            conn.rollback();
        }
        log.error("", e);
        throw e;
    } finally {
        DbUtils.closeAllConnections(ps, conn, null);
    }

}

From source file:com.wso2telco.dep.operatorservice.dao.BlackListWhiteListDAO.java

/**
 * blacklist list given msisdns//from w  w w .  j a  va  2 s. c  o  m
 *
 * @param msisdns
 * @param apiID
 * @param apiName
 * @param userID
 * @throws Exception
 */
public void blacklist(MSISDNValidationDTO msisdns, final String apiID, final String apiName,
        final String userID) throws Exception {

    log.debug("BlackListWhiteListDAO.blacklist triggerd MSISDN["
            + StringUtils.join(msisdns.getValidProcessed().toArray(), ",") + "] apiID:" + apiID + " apiName:"
            + apiName + " userID:" + userID);

    StringBuilder sql = new StringBuilder();
    sql.append(" INSERT INTO ");
    sql.append(OparatorTable.BLACKLIST_MSISDN.getTObject());
    sql.append("(PREFIX,MSISDN,API_ID,API_NAME,USER_ID,VALIDATION_REGEX)");
    sql.append(" VALUES (?, ?, ?, ?, ?, ?)");

    Connection conn = null;
    PreparedStatement ps = null;

    try {
        conn = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB);
        ps = conn.prepareStatement(sql.toString());

        conn.setAutoCommit(false);

        for (MsisdnDTO msisdn : msisdns.getValidProcessed()) {

            ps.setString(1, msisdn.getPrefix());
            ps.setString(2, msisdn.getDigits());
            ps.setString(3, apiID);
            ps.setString(4, apiName);
            ps.setString(5, userID);
            ps.setString(6, msisdns.getValidationRegex());
            ps.addBatch();
        }

        ps.executeBatch();
        conn.commit();

    } catch (Exception e) {
        if (conn != null) {
            conn.rollback();
        }
        throw e;
    } finally {
        DbUtils.closeAllConnections(ps, conn, null);
    }

}

From source file:backtype.storm.scheduler.adaptive.DataManager.java

public void removeTopologies(List<String> topologies) throws Exception {
    Connection connection = null;
    Statement statement = null;/*from  w  ww .j  a v  a2  s.  c  o m*/
    logger.debug("Going to remove these topologies: " + Utils.collectionToString(topologies));
    try {
        connection = getConnection();
        connection.setAutoCommit(false);
        statement = connection.createStatement();
        for (String topology : topologies) {
            logger.debug("Removing load stats of topology " + topology);
            String sql = "delete from `load` where topology_id in (select id from topology where storm_id = '"
                    + topology + "')";
            logger.debug("SQL script: " + sql);
            statement.execute(sql);

            logger.debug("Removing traffic stats of topology " + topology);
            sql = "delete from traffic where topology_id in (select id from topology where storm_id = '"
                    + topology + "')";
            logger.debug("SQL script: " + sql);
            statement.execute(sql);

            logger.debug("Removing topology " + topology);
            sql = "delete from topology where storm_id = '" + topology + "'";
            logger.debug("SQL script: " + sql);
            statement.execute(sql);
        }
        connection.commit();
    } catch (Exception e) {
        logger.error("An error occurred removing topologies", e);
        connection.rollback();
        throw e;
    } finally {
        if (statement != null)
            statement.close();
        if (connection != null) {
            connection.setAutoCommit(true);
            connection.close();
        }
    }
}

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

/**
 * @see com.cws.esolutions.core.dao.interfaces.IServiceDataDAO#getService(java.lang.String)
 *//* w  ww.  j  a va2s  .c  o m*/
public synchronized List<String> getService(final String attribute) throws SQLException {
    final String methodName = IServiceDataDAO.CNAME + "#getService(final String attribute) throws SQLException";

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

    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);

        // we dont know what we have here - it could be a guid or it could be a hostname
        // most commonly it'll be a guid, but we're going to search anyway
        stmt = sqlConn.prepareCall("{ CALL getServiceData(?) }");
        stmt.setString(1, attribute);

        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<String>(Arrays.asList(resultSet.getString(1), // SERVICE_TYPE
                        resultSet.getString(2), // NAME
                        resultSet.getString(3), // REGION
                        resultSet.getString(4), // NWPARTITION
                        resultSet.getString(5), // STATUS
                        resultSet.getString(6), // SERVERS
                        resultSet.getString(7))); // DESCRIPTION

                if (DEBUG) {
                    DEBUGGER.debug("responseData: {}", 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.moss.schematrax.SchemaUpdater.java

public void updateSchema(DatabaseType databaseType, Connection sqlConnection, String schema,
        String schemaVersion) throws SchematraxException {

    try {// w  ww  .  j  ava  2  s  .  co  m
        if (manageTransactions)
            sqlConnection.setAutoCommit(false);

        List appliedUpdates = listAppliedUpdates(sqlConnection, schema);
        /*
         * PROCESS THE SQL UPDATES
         */
        List<SchemaVersion> versionsList = new ArrayList<SchemaVersion>();
        // Create an array of all prior versions
        SchemaVersion version = schemaData.getVersion(schemaVersion);
        versionsList.add(version);
        while (version.getPriorVersion() != null) {
            version = version.getPriorVersion();
            versionsList.add(version);
        }

        for (int x = versionsList.size() - 1; x > -1; x--) {
            version = (SchemaVersion) versionsList.get(x);
            applyUpdatesForVersion(version, appliedUpdates, databaseType, schema, sqlConnection);
        }

        // WE'RE DONE! NOTIFY THE INJECTORS
        for (Injector injector : injectors) {
            injector.updateComplete();
        }

        if (manageTransactions)
            sqlConnection.commit();
    } catch (Exception e) {
        try {
            if (manageTransactions)
                sqlConnection.rollback();
            if (e instanceof SchematraxException)
                throw (SchematraxException) e;
            throw new SchemaUpdateException(e);
        } catch (SQLException e1) {
            log.fatal("An update failed.", e); // this is so that we still get the root cause somewhere
            throw new SchemaUpdateException(e1);
        }
    }

}

From source file:eionet.cr.dao.virtuoso.VirtuosoStagingDatabaseDAO.java

@Override
public void delete(List<String> dbNames) throws DAOException {

    if (dbNames == null || dbNames.isEmpty()) {
        return;//from   www  .j  a  v  a2 s  .  c o  m
    }

    Connection conn = null;
    try {
        conn = getSQLConnection();
        conn.setAutoCommit(false);

        // First, ensure the given databases are present in staging databases table (to avoid deleting other databases).
        String questionMarks = StringUtils.join(Collections.nCopies(dbNames.size(), "?"), ',');
        String sql = COUNT_EXISTING_DBS_SQL.replace("?", questionMarks);
        int count = NumberUtils.toInt(SQLUtil.executeSingleReturnValueQuery(sql, dbNames, conn).toString());
        if (dbNames.size() > count) {
            throw new DAOException("At least one of the given databases is unknown");
        }

        // Second, delete the databases themselves.
        deleteDatabases(dbNames, conn);

        // Third, delete rows from the staging databases table.
        sql = DELETE_DB_SQL.replace("?", questionMarks);
        SQLUtil.executeUpdate(sql, dbNames, conn);

        conn.commit();
    } catch (SQLException e) {
        SQLUtil.rollback(conn);
        throw new DAOException(e.getMessage(), e);
    } finally {
        SQLUtil.close(conn);
    }
}

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

/**
 * @see com.cws.esolutions.core.dao.interfaces.IServiceDataDAO#listServices(int)
 *//*w w  w  .j  a  v  a 2s.  c  o m*/
public synchronized List<String[]> listServices(final int startRow) throws SQLException {
    final String methodName = IServiceDataDAO.CNAME + "#listServices(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 listServices(?)}");
        stmt.setInt(1, startRow);

        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), // GUID
                            resultSet.getString(2), // SERVICE_TYPE
                            resultSet.getString(3), // NAME
                    };

                    responseData.add(data);
                }

                if (DEBUG) {
                    DEBUGGER.debug("List<String>: {}", responseData);
                }
            }
        }
    } catch (SQLException sqx) {
        ERROR_RECORDER.error(sqx.getMessage(), 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.webpagebytes.cms.local.WPBLocalDataStoreDao.java

public <T> T addRecordWithKey(T object, String keyFieldName) throws SQLException, WPBSerializerException {
    Connection connection = getConnection();
    PreparedStatement preparedStatement = null;
    try {/*  w w  w .ja  va2s. co m*/
        Set<String> ignoreFields = new HashSet<String>();
        String sqlStatement = getSQLStringForInsert(object, ignoreFields);
        connection.setAutoCommit(true);
        preparedStatement = connection.prepareStatement(sqlStatement);
        buildStatementForInsertUpdate(object, ignoreFields, preparedStatement, connection);
        preparedStatement.execute();
        return object;
    } catch (SQLException e) {
        throw e;
    } finally {
        if (preparedStatement != null) {
            preparedStatement.close();
        }
        connection.close();
    }
}

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

/**
 * @see com.cws.esolutions.core.dao.interfaces.IServerDataDAO#removeServer(java.lang.String)
 *//*from   www  .jav a 2s .c o m*/
public synchronized boolean removeServer(final String serverGuid) throws SQLException {
    final String methodName = IServerDataDAO.CNAME
            + "#removeServer(final String serverGuid) throws SQLException";

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

    Connection sqlConn = null;
    boolean isComplete = false;
    CallableStatement stmt = null;

    try {
        sqlConn = dataSource.getConnection();

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

        sqlConn.setAutoCommit(true);

        stmt = sqlConn.prepareCall("{CALL removeServerFromAssets(?)}");
        stmt.setString(1, serverGuid);

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

        isComplete = (!(stmt.execute()));

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

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

    return isComplete;
}