Example usage for java.sql Connection rollback

List of usage examples for java.sql Connection rollback

Introduction

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

Prototype

void rollback() throws SQLException;

Source Link

Document

Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object.

Usage

From source file:net.unicon.mercury.fac.rdbms.RdbmsMessageFactory.java

/**
 * Rolls back the provided connection.//from   w  w  w. j av a2  s. c  o  m
 *
 * @param  conn
 *     a Connection to be rolled back. Cannot be null.
 */
protected void rollBack(Connection conn) {
    if (conn != null) {
        try {
            conn.rollback();
        } catch (SQLException e) {
            String msg = "Error during rollback. Data may be corrupted.";
            throw new RuntimeException(msg, e);
        }
    }
}

From source file:com.tremolosecurity.provisioning.core.providers.BasicDB.java

@Override
public void createUser(User user, Set<String> attributes, Map<String, Object> request)
        throws ProvisioningException {

    int userID = 0;
    int approvalID = 0;
    int workflow = 0;

    if (request.containsKey("TREMOLO_USER_ID")) {
        userID = (Integer) request.get("TREMOLO_USER_ID");
    }//  w  ww.  j  av a 2  s. co  m

    if (request.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) request.get("APPROVAL_ID");
    }

    if (request.containsKey("WORKFLOW_ID")) {
        workflow = (Integer) request.get("WORKFLOW_ID");
    }

    Map<String, Attribute> attrs = new HashMap<String, Attribute>();
    attrs.putAll(user.getAttribs());

    if (!attrs.containsKey(this.userName)) {
        attrs.remove("userid");
        attrs.put(this.userName, new Attribute(this.userName, user.getUserID()));
    }

    Connection con = null;
    try {

        con = this.ds.getConnection();
        con.setAutoCommit(false);

        int userid = -1;

        if (this.customDBProvider != null) {
            Map<String, Attribute> toadd = new HashMap<String, Attribute>();

            for (String attr : attributes) {
                if (attrs.get(attr) != null) {
                    toadd.put(attr, user.getAttribs().get(attr));
                }
            }

            userid = this.customDBProvider.createUser(con, user, toadd);
            for (String groupName : user.getGroups()) {
                this.customDBProvider.addGroup(con, userid, groupName);
            }
        } else {

            insertCreate(user, attributes, attrs, con, request);
        }
        con.commit();
    } catch (Exception e) {
        try {
            if (con != null)
                con.rollback();
        } catch (SQLException e1) {

        }
        throw new ProvisioningException("Could not create user", e);
    } finally {
        if (con != null) {
            try {

                con.close();
            } catch (SQLException e) {

            }
        }
    }

}

From source file:jade.domain.DFDBKB.java

/**
 * Add a subscription to the database/*from w w w.  j  a  v  a 2 s .  c  o  m*/
 * @param convID conversation id (used as primary key)
 * @param aclM ACL message for the subscription
 */
private void registerSubscription(String convID, String aclM) throws SQLException {
    Connection conn = getConnectionWrapper().getConnection();
    try {
        PreparedStatements pss = getPreparedStatements();
        String base64Str = new String(Base64.encodeBase64(aclM.getBytes("US-ASCII")), "US-ASCII");
        // --> convert string to Base64 encoding
        pss.stm_insSubscription.setString(1, convID);
        pss.stm_insSubscription.setString(2, base64Str);
        pss.stm_insSubscription.execute();
        conn.commit();
    } catch (SQLException sqle) {
        // Rollback the transaction
        try {
            conn.rollback();
        } catch (SQLException se) {
            logger.log(Logger.SEVERE, "Rollback for incomplete subscription failed.", se);
        }
        // Re-throw the exception
        throw sqle;
    } catch (Exception e) {
        logger.log(Logger.SEVERE, "Error encoding subscription message in Base64.", e);
        throw new SQLException("Error encoding subscription message in Base64. " + e.getMessage());
    }
}

From source file:com.wso2telco.dep.mediator.dao.USSDDAO.java

public void moUssdSubscriptionDelete(Integer moSubscriptionId) throws SQLException, Exception {

    Connection con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);
    PreparedStatement deleteSubscriptionsStatement = null;
    PreparedStatement deleteOperatorSubscriptionsStatement = null;

    try {/* w  ww  . j a  v a 2s .  c o  m*/

        if (con == null) {

            throw new Exception("Connection not found");
        }

        /**
         * Set autocommit off to handle the transaction
         */
        con.setAutoCommit(false);

        StringBuilder deleteSubscriptionsQueryString = new StringBuilder("DELETE FROM ")
                .append(DatabaseTables.USSD_REQUEST_ENTRY.getTableName()).append(" WHERE ussd_request_did = ?");

        deleteSubscriptionsStatement = con.prepareStatement(deleteSubscriptionsQueryString.toString());
        deleteSubscriptionsStatement.setInt(1, moSubscriptionId);

        log.debug("sql query in outboundSubscriptionDelete : " + deleteSubscriptionsStatement);

        deleteSubscriptionsStatement.executeUpdate();

        StringBuilder deleteOperatorSubscriptionsQueryString = new StringBuilder("DELETE FROM ")
                .append(DatabaseTables.MO_USSD_SUBSCRIPTIONS.getTableName())
                .append(" WHERE ussd_request_did = ?");

        deleteOperatorSubscriptionsStatement = con
                .prepareStatement(deleteOperatorSubscriptionsQueryString.toString());

        deleteOperatorSubscriptionsStatement.setInt(1, moSubscriptionId);

        log.debug("sql query in outboundSubscriptionDelete : " + deleteOperatorSubscriptionsStatement);

        deleteOperatorSubscriptionsStatement.executeUpdate();

        /**
         * commit the transaction if all success
         */
        con.commit();
    } catch (SQLException e) {

        /**
         * rollback if Exception occurs
         */
        con.rollback();

        log.error("database operation error in moUssdSubscriptionDelete : ", e);
        throw e;
    } catch (Exception e) {

        /**
         * rollback if Exception occurs
         */
        con.rollback();

        log.error("Error while deleting subscriptions. ", e);
        throw e;
    } finally {

        DbUtils.closeAllConnections(deleteSubscriptionsStatement, con, null);
        DbUtils.closeAllConnections(deleteOperatorSubscriptionsStatement, null, null);
    }
}

From source file:org.apache.hadoop.hive.metastore.txn.CompactionTxnHandler.java

/**
 * This will look through the completed_txn_components table and look for partitions or tables
 * that may be ready for compaction.  Also, look through txns and txn_components tables for
 * aborted transactions that we should add to the list.
 * @param maxAborted Maximum number of aborted queries to allow before marking this as a
 *                   potential compaction.
 * @return list of CompactionInfo structs.  These will not have id, type,
 * or runAs set since these are only potential compactions not actual ones.
 *//* w w  w  .  j a v a2  s .  c  o m*/
public Set<CompactionInfo> findPotentialCompactions(int maxAborted) throws MetaException {
    Connection dbConn = null;
    Set<CompactionInfo> response = new HashSet<CompactionInfo>();
    Statement stmt = null;
    try {
        try {
            dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
            stmt = dbConn.createStatement();
            // Check for completed transactions
            String s = "select distinct ctc_database, ctc_table, "
                    + "ctc_partition from COMPLETED_TXN_COMPONENTS";
            LOG.debug("Going to execute query <" + s + ">");
            ResultSet rs = stmt.executeQuery(s);
            while (rs.next()) {
                CompactionInfo info = new CompactionInfo();
                info.dbname = rs.getString(1);
                info.tableName = rs.getString(2);
                info.partName = rs.getString(3);
                response.add(info);
            }

            // Check for aborted txns
            s = "select tc_database, tc_table, tc_partition " + "from TXNS, TXN_COMPONENTS "
                    + "where txn_id = tc_txnid and txn_state = '" + TXN_ABORTED + "' "
                    + "group by tc_database, tc_table, tc_partition " + "having count(*) > " + maxAborted;

            LOG.debug("Going to execute query <" + s + ">");
            rs = stmt.executeQuery(s);
            while (rs.next()) {
                CompactionInfo info = new CompactionInfo();
                info.dbname = rs.getString(1);
                info.tableName = rs.getString(2);
                info.partName = rs.getString(3);
                info.tooManyAborts = true;
                response.add(info);
            }

            LOG.debug("Going to rollback");
            dbConn.rollback();
        } catch (SQLException e) {
            LOG.error("Unable to connect to transaction database " + e.getMessage());
            checkRetryable(dbConn, e, "findPotentialCompactions(maxAborted:" + maxAborted + ")");
        } finally {
            closeDbConn(dbConn);
            closeStmt(stmt);
        }
        return response;
    } catch (RetryException e) {
        return findPotentialCompactions(maxAborted);
    }
}

From source file:dao.ContactDaoDb.java

/**
 *  This method deletes a contact based on contactId
 *  @param loginId - the loginid/*from  ww w.  j ava2s .co m*/
 *  @param contactId - the contact id 
 *  @param alphabet - the first letter of firstname or lastname
 *  @throws BaseDaoException - when error occurs
 */
public void deleteOneContact(String loginId, String contactId, String alphabet) throws BaseDaoException {

    if (RegexStrUtil.isNull(loginId) || RegexStrUtil.isNull(contactId)) {
        throw new BaseDaoException("params are null in deleteOneContact()");
    }

    /**
     *  Get scalability datasource for hdcontacts
     */
    String sourceName = scalabilityManager.getWriteZeroScalability();
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds null, deleteOneContact() " + sourceName);
    }

    Connection conn = null;
    try {
        conn = ds.getConnection();
        conn.setAutoCommit(false);
        deleteQuery.run(conn, contactId, loginId);
        // delete all sharecontacts that match with this contactId
        deleteShareContactByIdQuery.run(conn, contactId);
        deleteTagQuery.run(conn, contactId);
    } catch (Exception e) {
        try {
            conn.rollback();
        } catch (Exception e1) {
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
            } catch (Exception e2) {
                throw new BaseDaoException(
                        "error in deleteOneContact(), contactId " + contactId + " loginId = " + loginId, e2);
            }
            throw new BaseDaoException(
                    "error in deleteOneContact(), contactId " + contactId + " loginId = " + loginId, e1);
        }
        throw new BaseDaoException(
                "error in deleteOneContact(), contactId " + contactId + " loginId = " + loginId, e);
    }

    // conn commit
    try {
        conn.commit();
    } catch (Exception e3) {
        throw new BaseDaoException("conn.commit() in deleteOneContact loginid=" + loginId, e3);
    }

    try {
        if (conn != null) {
            conn.setAutoCommit(true);
            conn.close();
        }
    } catch (Exception e) {
        throw new BaseDaoException(
                "error in deleteOneContact(), contactId " + contactId + " loginId = " + loginId, e);
    }

    Fqn fqn = cacheUtil.fqn(DbConstants.CONTACTS);
    if (treeCache.exists(fqn, loginId)) {
        treeCache.remove(fqn, loginId);
    }

    fqn = cacheUtil.fqn(DbConstants.CONTACT);
    if (treeCache.exists(fqn, contactId)) {
        treeCache.remove(fqn, contactId);
    }

    fqn = cacheUtil.fqn(DbConstants.CONTACTS_ALPHABET);
    StringBuffer sb = new StringBuffer(alphabet);
    sb.append("-");
    sb.append(loginId);
    if (treeCache.exists(fqn, sb.toString())) {
        treeCache.remove(fqn, sb.toString());
    }

    // (DbConstants.SHARED_CONTACTS)
    deleteAllShareContactsByContactId(contactId);

    fqn = cacheUtil.fqn(DbConstants.MY_SHARED_CONTACTS);
    if (treeCache.exists(fqn, loginId)) {
        treeCache.remove(fqn, loginId);
    }

    fqn = cacheUtil.fqn(DbConstants.PUBLISHED_CONTACTS);
    if (treeCache.exists(fqn, loginId)) {
        treeCache.remove(fqn, loginId);
    }

    fqn = cacheUtil.fqn(DbConstants.SHARED_PUBLISHED_CONTACTS);
    if (treeCache.exists(fqn, loginId)) {
        treeCache.remove(fqn, loginId);
    }
}

From source file:com.wso2telco.aggregatorblacklist.dao.ProvisionDAO.java

public boolean insertMerchantProvision(Integer appID, String subscriber, String operator, String[] merchants)
        throws SQLException, Exception {

    Connection con = null;
    ResultSet rs = null;/* www . j  a v  a  2s .c  o  m*/
    PreparedStatement insertStatement = null;
    PreparedStatement selectStatement = null;

    try {

        con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);
        if (con == null) {

            throw new Exception("Connection not found");
        }

        /**
         * Set autocommit off to handle the transaction
         */
        con.setAutoCommit(false);

        StringBuilder selectQueryString = new StringBuilder(" SELECT id ");
        selectQueryString.append(" FROM ");
        selectQueryString.append(DatabaseTables.OPERATORS.getTableName());
        selectQueryString.append(" WHERE operatorname = '" + operator + "'");

        selectStatement = con.prepareStatement(selectQueryString.toString());
        rs = selectStatement.executeQuery();

        int operatorid = 0;
        if (rs.next()) {
            operatorid = rs.getInt("id");
        } else {
            throw new Exception("Operator Not Found");
        }

        for (int i = 0; i < merchants.length; i++) {
            StringBuilder insertQueryString = new StringBuilder("INSERT INTO ");
            insertQueryString.append(DatabaseTables.MERCHANTOPCO_BLACKLIST.getTableName());
            insertQueryString.append(" (application_id, operator_id, subscriber, merchant) ");
            insertQueryString.append("VALUES (?, ?, ?, ?)");

            insertStatement = con.prepareStatement(insertQueryString.toString());
            if (appID == null) {
                insertStatement.setNull(1, Types.INTEGER);
            } else {
                insertStatement.setInt(1, appID);
            }
            insertStatement.setInt(2, operatorid);
            insertStatement.setString(3, subscriber);
            insertStatement.setString(4, merchants[i]);
            insertStatement.executeUpdate();

            /**
             * commit the transaction if all success
             */
            con.commit();
        }

    } catch (SQLException e) {
        /**
         * rollback if Exception occurs
         */
        con.rollback();

        log.error("database operation error in Merachantopco Blacklist Entry : ", e);
        throw e;
    } catch (Exception e) {
        /**
         * rollback if Exception occurs
         */
        con.rollback();
        log.error("Error while Provisioning Merchant : ", e);

        throw e;
    } finally {
        DbUtils.closeAllConnections(selectStatement, con, rs);
        DbUtils.closeAllConnections(insertStatement, null, null);
    }
    return true;
}

From source file:mom.trd.opentheso.bdd.helper.CandidateHelper.java

/**
* Cette fonction permet d'ajouter un group (MT, domaine etc..) avec le
* libell/*  w  w w  .  j  a va  2  s. c o m*/
*
* @param conn
* @param lexical_value
* @param idLang
* @param idThesaurus
* @param contributor
* @param note
* @param idParentConcept
* @param idGroup
* @return null si le term existe ou si erreur, sinon le numero de Concept
*/
public String addCandidat_rollBack(Connection conn, String lexical_value, String idLang, String idThesaurus,
        int contributor, String note, String idParentConcept, String idGroup) {

    try {
        conn.setAutoCommit(false);

        CandidateHelper candidateHelper = new CandidateHelper();
        // controle si le term existe avant de rajouter un concept
        if (candidateHelper.isCandidatExist_rollBack(conn, lexical_value, idThesaurus, idLang)) {
            conn.rollback();
            conn.close();
            return null;
        }

        String idConceptCandidat = addConceptCandidat_rollback(conn, idThesaurus);
        if (idConceptCandidat == null) {
            conn.rollback();
            conn.close();
            return null;
        }

        String idTermCandidat = candidateHelper.addTermCandidat_RollBack(conn, lexical_value, idLang,
                idThesaurus, contributor);
        if (idTermCandidat == null) {
            conn.rollback();
            conn.close();
            return null;
        }

        if (!addRelationConceptTermCandidat_RollBack(conn, idConceptCandidat, idTermCandidat, idThesaurus)) {
            conn.rollback();
            conn.close();
            return null;
        }

        if (!candidateHelper.addPropositionCandidat_RollBack(conn, idConceptCandidat, contributor, idThesaurus,
                note, idParentConcept, idGroup)) {
            conn.rollback();
            conn.close();
            return null;
        }

        return idConceptCandidat;
    } catch (SQLException ex) {
        Logger.getLogger(CandidateHelper.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:DbServletTrans.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    Connection conn = null;
    Statement stmt = null;//from   w w w  .  java  2s  .c  om

    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html><head><title>Using transactions</title></head><body>");
    out.println("<h2>These SQL statements are part of a transaction</h2>");
    out.println("CallableStatement.executeUpdate()");
    out.println("<br><br>");
    out.println("Statement.executeUpdate()");
    out.println("<br><br>");

    try {

        conn = pool.getConnection();

        out.println("AutoCommit before setAutoCommit(): " + conn.getAutoCommit() + "<br><br>");

        out.println("Transaction isolation level: ");

        switch (conn.getTransactionIsolation()) {

        case 0:
            out.println("TRANSACTION_NONE<br><br>");
            break;
        case 1:
            out.println("TRANSACTION_READ_UNCOMMITTED<br><br>");
            break;
        case 2:
            out.println("TRANSACTION_READ_COMMITTED<br><br>");
            break;
        case 4:
            out.println("TRANSACTION_REPEATABLE_READ<br><br>");
            break;
        case 8:
            out.println("TRANSACTION_SERIALIZABLE<br><br>");
            break;
        default:
            out.println("UNKNOWN<br><br>");

        }
        conn.setAutoCommit(false);

        CallableStatement cs = null;

        //Create an instance of the CallableStatement
        cs = conn.prepareCall("{call addEvent (?,?,?)}");

        cs.setString(1, "Salisbury Beach 5-Miler");
        cs.setString(2, "Salisbury MA");
        cs.setString(3, "14-Aug-2003");

        //Call the inherited PreparedStatement.executeUpdate() method
        cs.executeUpdate();

        String sql = "update raceevent set racedate='13-Aug-2003' " + "where name='Salisbury Beach 5-Miler'";

        int res = 0;

        stmt = conn.createStatement();

        res = stmt.executeUpdate(sql);

        //commit the two SQL statements
        conn.commit();

    } catch (Exception e) {

        try {
            //rollback the transaction in case of a problem
            conn.rollback();

        } catch (SQLException sqle) {
        }

        throw new ServletException(e.getMessage());

    } finally {

        try {

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

            if (conn != null)
                conn.close();//this returns the Connection to the
                             // Connection pool

        } catch (SQLException sqle) {
        }

    }
    out.println("</table></body></html>");
    out.close();

}

From source file:com.l2jserver.service.database.sql.AbstractSQLDatabaseService.java

@Override
public <M extends Model<?>, T extends RelationalPathBase<?>> void importData(final java.nio.file.Path path,
        final T entity) throws IOException {
    final Connection conn;
    try {//from   w ww.j  a va 2 s . c o m
        conn = dataSource.getConnection();
    } catch (SQLException e) {
        return;
    }
    log.info("Importing {} to {}", path, entity);
    try {
        conn.setAutoCommit(false);
        CSVUtils.parseCSV(path, new CSVMapProcessor<Long>() {
            @Override
            public Long process(final Map<String, String> map) {
                SQLInsertClause insert = engine.createSQLQueryFactory(conn).insert(entity);
                insert.populate(map, new Mapper<Map<String, String>>() {
                    @Override
                    public Map<Path<?>, Object> createMap(RelationalPath<?> relationalPath,
                            Map<String, String> map) {
                        final Map<Path<?>, Object> values = CollectionFactory.newMap();
                        for (final Entry<String, String> entry : map.entrySet()) {
                            final Path<?> path = QPathUtils.getPath(entity, entry.getKey());
                            values.put(path, entry.getValue());
                        }
                        return values;
                    }
                });
                return insert.execute();
            }
        });
        conn.commit();
    } catch (SQLException e) {
        try {
            conn.rollback();
        } catch (SQLException e1) {
        }
    } finally {
        try {
            conn.setAutoCommit(true);
            conn.close();
        } catch (SQLException e) {
        }
    }
}