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:hoot.services.controllers.job.ReviewResource.java

/**
 * <NAME>Conflated Data Review Service Mark Items as Reviewed</NAME>
 * <DESCRIPTION>/*  w  w w .j  a v  a  2  s  . c o  m*/
 *    After editing reviewable items, this method is called to mark the items as having been reviewed.
 * The inputs to the service method are either a JSON structure which describes the status of the review for
 * each reviewed item, or when setting a boolean true to mark all items as reviewed the structure is not required.
 * Also optionally for convenience sake, a OSM XML changeset may be included in the request to upload a
 * changeset in the same call which marks data as reviewed. If a changeset is uploaded, the service
 * automatically creates and closes the changeset that stores the uploaded data. The response from the server contains
 * the outcome of the changeset upload and the changeset ID created (if a changeset was uploaded) as well as the number
 * of submitted items that were actually marked as reviewed. Clients can compare this number to the number of
 *  items sent for review, and if they are not equal, further troubleshooting should occur.
 *  For each item in the reviewed items JSON, the service will:
 *  mark the reviewable item as reviewed, so that it will not be returned for review again
 *  append the UUID of the item the reviewed item was reviewed against to its "uuid" OSM tag
 *   remove the UUID of the item reviewed against from the "hoot:review:uuid" OSM tag of the reviewed item
 *   remove all OSM review tags from the reviewed item, if it no longer contains items to be reviewed against
 *   The caller is responsible for doing the following things, as the service will not automatically do them:
 *   Adding the "changeset" XML attribute to the elements in the XML changeset being uploaded, as is required by
 *    the standard OSM changeset upload service. The changeset ID attribute value may either be blank or populated with a number,
 *     however, the changeset ID will be overwritten with the ID of the changeset created by the service method execution.
 * </DESCRIPTION>
 * <PARAMETERS>
 *    <mapId>
 *    string; required; ID string or unique name of the map associated with the reviewable conflated data
 *    </mapId>
 *  <markAll>
 *  boolean; optional; defaults to false; indicates whether all items belonging to the map should be marked as reviewed
 *  </markAll>
 *  <markItemsReviewedRequest>
 *   JSON object; sent in request body payload; required; object is made up of:
 *   reviewedItems - JSON object; required if markAll is set to false; optional otherwise; lists the items which should be marked as reviewed
 *   reviewedItemsChangeset - XML string; optional; OSM changeset XML
 *  </markItemsReviewedRequest>
 * </PARAMETERS>
 * <OUTPUT>
 *    A number string to show how many items were marked as reviewed as a result of the service call.
 * </OUTPUT>
 * <EXAMPLE>
 *    <URL>http://localhost:8080/hoot-services/job/review?mapId=1&markAll=false</URL>
 *    <REQUEST_TYPE>PUT</REQUEST_TYPE>
 *    <INPUT>
 * {
 *   "reviewedItems":
 *   [
 *     {
 *       "id": 2402,
 *       "type": "way",
 *       "reviewedAgainstId": 2403,
 *       "reviewedAgainstType": "way",
 *     },
 *     {
 *       "id": 2404,
 *       "type": "way",
 *       "reviewedAgainstId": 2405,
 *       "reviewedAgainstType": "way",
 *     },
 *   ]
 * }
 *   </INPUT>
 * <OUTPUT>
 * 2
 * </OUTPUT>
 * </EXAMPLE>
*
* Marks a set of reviewable items as reviewed and updates the tags of their corresponding OSM
* elements
*
* @param reviewItemsChangeset an OSM changeset to be uploaded into the services database
* @param mapId ID of the map for which items are being marked as reviewed
* @return the number of items marked as reviewed
* @throws Exception
* @see https://insightcloud.digitalglobe.com/redmine/projects/hootenany/wiki/User_-_Conflated_Data_Review_Service_2#Mark-Items-as-Reviewed
*/
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public MarkItemsReviewedResponse markItemsReviewed(MarkItemsReviewedRequest markItemsReviewedRequest,
        @QueryParam("mapId") String mapId, @DefaultValue("false") @QueryParam("markAll") boolean markAll)
        throws Exception {
    Connection conn = DbUtils.createConnection();
    final String errorMessageStart = "marking items as reviewed";
    MarkItemsReviewedResponse markItemsReviewedResponse = null;
    try {
        log.debug("markItemsReviewedRequest: " + markItemsReviewedRequest.toString());

        Map<String, Object> inputParams = new HashMap<String, Object>();
        inputParams.put("mapId", mapId);
        inputParams.put("markAll", markAll);
        ReviewInputParamsValidator inputParamsValidator = new ReviewInputParamsValidator(inputParams);
        mapId = (String) inputParamsValidator.validateAndParseInputParam("mapId", "", null, null, false, null);
        markAll = (Boolean) inputParamsValidator.validateAndParseInputParam("markAll", false, null, null, true,
                false);
        if (!markAll && (markItemsReviewedRequest.getReviewedItems() == null
                || markItemsReviewedRequest.getReviewedItems().getReviewedItems() == null
                || markItemsReviewedRequest.getReviewedItems().getReviewedItems().length == 0)) {
            throw new Exception("Invalid input parameter: markAll set to false and "
                    + "markItemsReviewedRequest.reviewedItems empty.");
        }

        log.debug("Initializing database connection...");

        log.debug("Intializing transaction...");
        TransactionStatus transactionStatus = transactionManager
                .getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED));
        conn.setAutoCommit(false);

        try {
            markItemsReviewedResponse = (new ReviewItemsMarker(conn, mapId))
                    .markItemsReviewed(markItemsReviewedRequest, markAll);
        } catch (Exception e) {
            log.debug("Rolling back database transaction for ReviewResource::markItemsAsReviewed...");
            transactionManager.rollback(transactionStatus);
            conn.rollback();
            throw e;
        }

        log.debug("Committing ReviewResource::markItemsAsReviewed. database transaction...");
        transactionManager.commit(transactionStatus);
        conn.commit();
    } catch (Exception e) {
        ReviewUtils.handleError(e, errorMessageStart, false);
    } finally {
        try {
            conn.setAutoCommit(true);
            DbUtils.closeConnection(conn);
        } catch (Exception e) {
            ReviewUtils.handleError(e, errorMessageStart, false);
        }
    }

    //TODO: MarkItemsReviewedResponse toString() not working
    //    if (markItemsReviewedResponse != null)
    //    {
    //      log.debug("Returning mark items reviewed response: " +
    //        StringUtils.abbreviate(markItemsReviewedResponse.toString(), 100) + " ...");
    //    }

    return markItemsReviewedResponse;
}

From source file:com.runwaysdk.dataaccess.database.general.PostgreSQL.java

/**
 * //from  w ww.  ja v  a 2 s .  com
 * @param errorCode
 * @param errorMessage
 */
public void throwDatabaseException(SQLException ex, String debugMsg) {
    String errorCode = ex.getSQLState();
    String errorMessage = ex.getMessage();

    // In PostgreSQL, no more queries to the database during the session can
    // occur until the
    // transaction block has been closed. This is done with a rollback.
    try {
        try {
            // If there is a savepoint, then don't rollback. The calling code that
            // has set a savepoint
            // should release it.
            Database.peekCurrentSavepoint();
        } catch (EmptyStackException e) {
            Connection conn = Database.getConnection();
            conn.rollback();
        }
    } catch (SQLException sqlEx) {
        throw new DatabaseException(sqlEx);
    }

    if (errorCode == null) {
        throw new DatabaseException(errorMessage, debugMsg);
    }

    errorCode = errorCode.trim();

    if (errorCode.equals("23505")) {
        int startIndex = errorMessage.indexOf("\"") + 1;
        int endIndex = errorMessage.indexOf("\"", startIndex);
        String indexName = errorMessage.substring(startIndex, endIndex);

        if (indexName.substring(0, 4).equalsIgnoreCase(MdRelationshipDAOIF.INDEX_PREFIX)) {
            String error = "Constraint [" + indexName + "] on relationship violated";

            throw new DuplicateGraphPathException(error);
        } else {
            String error = "Constraint [" + indexName + "] on object violated";

            int pkeyStartIndex = indexName.indexOf(PRIMARY_KEY_SUFFIX);

            if (indexName.contains(PRIMARY_KEY_SUFFIX)
                    && indexName.substring(pkeyStartIndex, indexName.length()).equals(PRIMARY_KEY_SUFFIX)) {
                String tableName = indexName.substring(0, pkeyStartIndex).trim();

                throw new DuplicateDataDatabaseException(error, ex, indexName, tableName);
            } else {
                throw new DuplicateDataDatabaseException(error, ex, indexName);
            }
        }

    }

    if (errorCode.equals("21000")) {
        String errMsg = "Subquery returns more than 1 row";
        throw new SubSelectReturnedMultipleRowsException(errMsg);
    }

    if (errorCode.equals("22003")) {
        String errMsg = "Numeric input overflowed the bounds of its column";
        throw new NumericFieldOverflowException(errMsg);
    }

    if (DatabaseProperties.isSeriousError(errorCode)) {
        throw new ProgrammingErrorException(debugMsg, ex);
    } else {
        throw new DatabaseException(errorMessage, debugMsg);
    }
}

From source file:com.webpagebytes.wpbsample.database.WPBDatabase.java

public Transaction createTransaction(int source_user_id, int destination_user_id, long amount)
        throws SQLException {
    Connection connection = getConnection();
    PreparedStatement statement = null;
    PreparedStatement statementAccountS = null;
    PreparedStatement statementAccountD = null;

    Transaction transaction = new Transaction();
    try {/*from  w  ww .j  av a 2 s  .c  o m*/
        statement = connection.prepareStatement(CREATE_ACCOUNTOPERATIONS_STATEMENT);
        connection.setAutoCommit(false);

        statement.setInt(1, source_user_id);
        statement.setInt(2, ACCOUNT_OPERATION_PAYMENT);

        statement.setLong(3, amount);
        Date now = new Date();
        java.sql.Timestamp sqlDate = new java.sql.Timestamp(now.getTime());
        statement.setTimestamp(4, sqlDate);
        statement.setInt(5, source_user_id);
        statement.setInt(6, destination_user_id);

        statement.execute();
        ResultSet rs = statement.getGeneratedKeys();
        if (rs.next()) {
            transaction.setId(rs.getLong(1));
            transaction.setAmount(amount);
            transaction.setDate(now);
            transaction.setSource_user_id(source_user_id);
            transaction.setDestination_user_id(destination_user_id);
        }

        statementAccountS = connection.prepareStatement(UPDATE_ACCOUNT_FOR_ADDITION_STATEMENT);
        statementAccountS.setLong(1, -amount);
        statementAccountS.setInt(2, source_user_id);
        statementAccountS.execute();

        statementAccountD = connection.prepareStatement(UPDATE_ACCOUNT_FOR_ADDITION_STATEMENT);
        statementAccountD.setLong(1, amount);
        statementAccountD.setInt(2, destination_user_id);
        statementAccountD.execute();

        connection.commit();
    } catch (SQLException e) {
        if (connection != null) {
            connection.rollback();
        }
        throw e;
    } finally {
        if (statement != null) {
            statement.close();
        }
        if (statementAccountD != null) {
            statementAccountD.close();
        }
        if (statementAccountS != null) {
            statementAccountS.close();
        }
        if (connection != null) {
            connection.close();
        }

    }
    return transaction;
}

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

/**
 * Description of the Method/*from   ww w . j  av  a 2  s  . c  o m*/
 *
 * @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:dao.DirectoryAuthorDaoDb.java

/**
  *  Deletes the author from multiple directories.
  *  @param idList the list of directory ids
  *  @param member  the member to remove as author from this directory
  *  @param userId  the user Login is used to check if this user has the permission to delete authors
  *  @param userLogin  the user Login is used to check if this user has the permission to delete authors
 *//*  ww  w .j a v  a2  s  . c o m*/
public void deleteAuthor(ArrayList idList, String member, String userId, String userLogin)
        throws BaseDaoException {

    if ((idList == null) || RegexStrUtil.isNull(userLogin) || RegexStrUtil.isNull(member)
            || RegexStrUtil.isNull(userId)) {
        throw new BaseDaoException("params are null");
    }

    /**
     *  Get scalability datasource for diradmin, not partitioned
     */
    String sourceName = scalabilityManager.getWriteZeroScalability();
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds null, deleteAuthor() " + sourceName + " userId = " + userId);
    }

    /**
     *  delete author from a given list of directories (idList)
     */
    String memberId = null;
    Connection conn = null;
    try {
        Hdlogin hdlogin = getLoginid(member);
        memberId = hdlogin.getValue(DbConstants.LOGIN_ID);
        conn = ds.getConnection();
        conn.setAutoCommit(false);
        for (int i = 0; i < idList.size(); i++) {
            deleteAuthorQuery.run(conn, (String) idList.get(i), memberId);
        }
    } catch (Exception e) {
        try {
            conn.rollback();
        } catch (Exception e1) {
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
            } catch (Exception e2) {
                throw new BaseDaoException("conn.close() error, deleteAuthor, memberId" + memberId, e2);
            }
            throw new BaseDaoException(" rollback() exception, for deleteAuthor(),  userId = " + userId, e1);
        }
    }

    /**
    * commit the transaction
    */
    try {
        conn.commit();
    } catch (Exception e3) {
        throw new BaseDaoException(" commit() exception, for deleteAuthor() userId = " + userId, e3);
    }

    /**
     *  autocommit close
     */
    try {
        if (conn != null) {
            conn.setAutoCommit(true);
            conn.close();
        }
    } catch (Exception e4) {
        throw new BaseDaoException(" conn.close() exception, for commit(), deleteAuthor() userId = " + userId,
                e4);
    }

    /** Jboss methods
     * fqn - full qualified name
     * check if the author already set in the cache
     * If it exists, remove the authors 
     */
    Fqn fqn = cacheUtil.fqn(DbConstants.AUTHORS_DIRECTORIES);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.AUTHORS_LIST);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.AUTHORS_LIST);
    if (treeCache.exists(fqn, userLogin)) {
        treeCache.remove(fqn, userLogin);
    }

    fqn = cacheUtil.fqn(DbConstants.USER_PAGE);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.DIR_MOVE);
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }

    fqn = cacheUtil.fqn(DbConstants.DIR_COPY);
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }

    fqn = cacheUtil.fqn(DbConstants.DIR_USERS_SCOPE);
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }

    for (int i = 0; i < idList.size(); i++) {
        fqn = cacheUtil.fqn(DbConstants.DIRECTORY);
        String directoryId = (String) idList.get(i);
        if (treeCache.exists(fqn, directoryId)) {
            treeCache.remove(fqn, directoryId);
        }

        removeUsersFromDirAuthorsCache(directoryId);

        fqn = cacheUtil.fqn(DbConstants.DIR_AUTHORS);
        if (treeCache.exists(fqn, directoryId)) {
            treeCache.remove(fqn, directoryId);
        }

        fqn = cacheUtil.fqn(DbConstants.DIR_ADMINS);
        if (treeCache.exists(fqn, directoryId)) {
            treeCache.remove(fqn, directoryId);
        }

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

        StringBuffer sb = new StringBuffer(directoryId);
        sb.append("-");
        sb.append(memberId);
        fqn = cacheUtil.fqn(DbConstants.DIR_AUTHOR);
        if (treeCache.exists(fqn, sb.toString())) {
            treeCache.remove(fqn, sb.toString());
        }
    }
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.JDBCConnector.java

public List<ColumnVO> getColumnsMetaData(String sql) throws Exception {
    Exception error = null;/*from ww w . ja  v  a  2 s .c  o  m*/

    List<ColumnVO> tableColumns = new LinkedList<ColumnVO>();

    Connection connection = null;
    PreparedStatement preparedStmnt = null;

    try {
        DataSource dataSource = poolDataSources.get(schemaId);
        connection = dataSource.getConnection();
        connection.setAutoCommit(false);

        preparedStmnt = connection.prepareStatement(sql);
        ResultSet rs = preparedStmnt.executeQuery();
        ResultSetMetaData rsmd = rs.getMetaData();
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            String columnName = rsmd.getColumnName(i);
            String columnType = rsmd.getColumnTypeName(i);
            int columnSqlType = rsmd.getColumnType(i);
            int columnLength = rsmd.getColumnDisplaySize(i);
            int columnPrecision = rsmd.getPrecision(i);

            ColumnVO column = new ColumnVO();
            column.setNameOnTable(columnName);
            column.setType(columnType);
            column.setSqlType(columnSqlType);
            column.setLength(columnLength);
            column.setPrecision(columnPrecision);
            column.setInTable(true);

            tableColumns.add(column);
        }
    } catch (SQLException e) {
        error = e;
    } finally {
        if (preparedStmnt != null) {
            try {
                preparedStmnt.close();
            } catch (SQLException se2) {
                log.warn("No se pudo cerrar el statment: ".concat(se2.getLocalizedMessage()));
            }
        }
        if (connection != null) {
            try {
                if (error != null) {
                    connection.rollback();
                }
            } catch (SQLException se) {
                log.warn("Se produjo un error al manejar la conexin: ".concat(se.getLocalizedMessage()));
            }
            try {
                connection.close();
            } catch (SQLException se) {
                log.warn("Se produjo un error al intentar cerrar la conexin: "
                        .concat(se.getLocalizedMessage()));
            }
        }
    }
    if (error != null) {
        throw error;
    }
    return tableColumns;
}

From source file:edu.ku.brc.specify.tasks.RecordSetTask.java

/**
 * Merge two RecordSets removes duplicates and saves the destination RecordSet to the database
 * @param srcObj the source data (better be a RecordSet)
 * @param dstObj the destination data (better be a RecordSet)
 *///w w  w  .j  av  a 2  s.  c  o m
protected void mergeRecordSets(final Object srcObj, final Object dstObj) {
    UsageTracker.incrUsageCount("RS.MERGE");
    String MERGE_ERR = "RecordSetTask.MERGE_ERROR";

    if (srcObj != dstObj && srcObj != null && dstObj != null && srcObj instanceof RecordSetIFace
            && dstObj instanceof RecordSetIFace) {
        RecordSetIFace srcRecordSet = srcObj instanceof RecordSetProxy
                ? ((RecordSetProxy) srcObj).getRecordSet()
                : (RecordSetIFace) srcObj;
        RecordSetIFace dstRecordSet = dstObj instanceof RecordSetProxy
                ? ((RecordSetProxy) dstObj).getRecordSet()
                : (RecordSetIFace) dstObj;

        if (srcRecordSet != null && dstRecordSet != null) {
            // It' just easier to build this up front
            DBTableInfo srcTI = DBTableIdMgr.getInstance().getInfoById(srcRecordSet.getDbTableId());
            DBTableInfo dstTI = DBTableIdMgr.getInstance().getInfoById(dstRecordSet.getDbTableId());
            String mergeErrStr = String.format(getResourceString(MERGE_ERR),
                    new Object[] { srcTI.getShortClassName(), dstTI.getShortClassName() });

            if (srcRecordSet.getDbTableId().equals(dstRecordSet.getDbTableId())) {
                List<Integer> dstIdList = RecordSet.getIdList(dstRecordSet.getRecordSetId(), null);
                List<Integer> srcIdList;
                if (srcRecordSet.getRecordSetId() == null) {
                    srcIdList = new Vector<Integer>();
                    for (RecordSetItemIFace rsi : srcRecordSet.getOrderedItems()) {
                        srcIdList.add(rsi.getRecordId());
                    }
                } else {
                    srcIdList = RecordSet.getIdList(srcRecordSet.getRecordSetId(), null);
                }

                boolean debug = true;
                if (debug) {
                    log.debug("Source:");
                    for (Integer id : srcIdList) {
                        log.debug(" " + id);
                    }
                    log.debug("Dest:");
                    for (Integer id : dstIdList) {
                        log.debug(" " + id);
                    }
                    log.debug("");
                }

                Hashtable<Integer, Boolean> dupHash = new Hashtable<Integer, Boolean>();
                for (Integer id : dstIdList) {
                    dupHash.put(id, true);
                }

                List<Integer> newIdsList = new ArrayList<Integer>(srcIdList.size() + dstIdList.size());
                for (Integer id : srcIdList) {
                    if (dupHash.get(id) == null) {
                        //dstRecordSet.addItem(id); // for saving with Hibernate
                        newIdsList.add(id);
                    }
                }

                if (debug) {
                    log.debug("");
                    log.debug("New Dest:");
                    for (RecordSetItemIFace rsi : dstRecordSet.getItems()) {
                        log.debug(" " + rsi.getRecordId());
                    }
                    log.debug("");
                }

                if (newIdsList.size() > 0) {
                    //long start = System.currentTimeMillis();
                    boolean success = false;

                    if (true) // Use SQL to save the merge RecordSets
                    {
                        boolean doRollback = false;
                        Connection connection = DBConnection.getInstance().getConnection();
                        Statement stmt = null;
                        try {
                            connection.setAutoCommit(false);
                            stmt = connection.createStatement();
                            for (int i = 0; i < newIdsList.size(); i++) {
                                stmt.executeUpdate(
                                        "INSERT INTO recordsetitem (RecordSetID, RecordID, OrderNumber) VALUES ("
                                                + dstRecordSet.getRecordSetId() + "," + newIdsList.get(i) + ","
                                                + i + ")");
                            }
                            connection.commit();
                            success = true;

                        } catch (SQLException ex) {
                            edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
                            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(RecordSetTask.class,
                                    ex);
                            ex.printStackTrace();
                            doRollback = true;

                        } finally {
                            try {
                                if (doRollback) {
                                    connection.rollback();
                                }
                                if (stmt != null) {
                                    stmt.close();
                                }

                                connection.setAutoCommit(true);

                            } catch (SQLException ex2) {
                                edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
                                edu.ku.brc.exceptions.ExceptionTracker.getInstance()
                                        .capture(RecordSetTask.class, ex2);
                                ex2.printStackTrace();
                            }
                        }
                        //} else
                        //{
                        //    success = persistRecordSet(dstRecordSet);
                    }
                    //System.err.println("Time: "+(System.currentTimeMillis() - start));

                    if (success) {
                        String msg = String.format(getResourceString("RecordSetTask.MERGE_SUCCESS"),
                                new Object[] { srcTI.getShortClassName(), dstTI.getShortClassName() });
                        UIRegistry.displayStatusBarText(msg);
                    } else {
                        JOptionPane.showMessageDialog(UIRegistry.getTopWindow(), mergeErrStr,
                                getResourceString("Error"), JOptionPane.ERROR_MESSAGE);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(UIRegistry.getTopWindow(), mergeErrStr,
                        getResourceString("Error"), JOptionPane.ERROR_MESSAGE);
            }
        } else {
            log.error("The src or the dst RecordSet were null src[" + srcRecordSet + "]  dst[" + dstRecordSet
                    + "]");
        }
    }
}

From source file:dao.DirectoryAuthorDaoDb.java

/**
  *  Adds the author to multiple directories 
  *  @param idList the list of directory ids to which the author is added.
  *  @param member  the member who is added as author to this directory
  *  @param userId  the user Login is used to check if this user has the permission to add authors
  *  @param userLogin  the user Login is used to check if this user has the permission to add authors
 *//*from w  w w  .  j ava  2 s .  c  om*/
public void addAuthor(ArrayList idList, String member, String userId, String userLogin)
        throws BaseDaoException {

    if ((idList == null) || RegexStrUtil.isNull(userLogin) || RegexStrUtil.isNull(member)
            || RegexStrUtil.isNull(userId)) {
        throw new BaseDaoException("params are null");
    }

    /**
     *  Get scalability datasource for directory, diradmin, not partitioned
     */
    String sourceName = scalabilityManager.getWriteZeroScalability();
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException(
                "ds null, addAuthor(ArrayList) " + sourceName + " author to add = " + member);
    }

    /**
     *  Add this author to multiple directories
     */
    Connection conn = null;
    String memberId = null;
    try {
        Hdlogin hdlogin = getLoginid(member);
        memberId = hdlogin.getValue(DbConstants.LOGIN_ID);
        conn = ds.getConnection();
        conn.setAutoCommit(false);
        for (int i = 0; i < idList.size(); i++) {
            addAdminQuery.run(conn, (String) idList.get(i), memberId);
            deleteBlockQuery.run(conn, (String) idList.get(i), memberId);
        }
    } catch (Exception e) {
        try {
            conn.rollback();
        } catch (Exception e1) {
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
            } catch (Exception e2) {
                throw new BaseDaoException("conn.close() error, addAuthor(ArrayList), memberId" + memberId, e2);
            }
            throw new BaseDaoException(" rollback() exception, for addAuthor(ArrayList),  userId = " + userId,
                    e1);
        }
        throw new BaseDaoException(" addAuthor(ArrayList) exception,  userId = " + userId, e);
    }

    // connection commit
    try {
        conn.commit();
    } catch (Exception e3) {
        throw new BaseDaoException(" commit() exception, for addAuthor(ArrayList) userId = " + userId, e3);
    }
    try {
        if (conn != null) {
            conn.setAutoCommit(true);
            conn.close();
        }
    } catch (Exception e4) {
        throw new BaseDaoException(
                " conn.close() exception, for commit(), addAuthor(ArrayList) userId = " + userId, e4);
    }

    /**
     *  member's list needs to be updated with the new query, remove the old entries for this member
     */
    Fqn fqn = cacheUtil.fqn(DbConstants.AUTHORS_LIST);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.AUTHORS_LIST);
    if (treeCache.exists(fqn, userLogin)) {
        treeCache.remove(fqn, userLogin);
    }

    fqn = cacheUtil.fqn(DbConstants.USER_PAGE);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.AUTHORS_DIRECTORIES);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    for (int i = 0; i < idList.size(); i++) {
        // remove directory from cache
        fqn = cacheUtil.fqn(DbConstants.DIRECTORY);
        String directoryId = (String) idList.get(i);
        if (treeCache.exists(fqn, directoryId)) {
            treeCache.remove(fqn, directoryId);
        }

        fqn = cacheUtil.fqn(DbConstants.DIR_AUTHORS);
        if (treeCache.exists(fqn, directoryId)) {
            treeCache.remove(fqn, directoryId);
        }

        fqn = cacheUtil.fqn(DbConstants.DIR_ADMINS);
        if (treeCache.exists(fqn, directoryId)) {
            treeCache.remove(fqn, directoryId);
        }

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

        StringBuffer sb = new StringBuffer(directoryId);
        sb.append("-");
        sb.append(memberId);
        fqn = cacheUtil.fqn(DbConstants.DIR_AUTHOR);
        if (treeCache.exists(fqn, sb.toString())) {
            treeCache.remove(fqn, sb.toString());
        }
    }

    fqn = cacheUtil.fqn(DbConstants.AUTHOR_BLOCKED_DIRS);
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }
}

From source file:com.webpagebytes.wpbsample.database.WPBDatabase.java

public DepositWithdrawal createDepositOrWithdrawal(int user_id, DepositWithdrawal.OperationType type,
        long amount) throws SQLException {
    Connection connection = getConnection();
    PreparedStatement statement = null;
    PreparedStatement statementAccount = null;

    DepositWithdrawal operation = new DepositWithdrawal();
    try {//from w  w  w  .  j a  v a 2 s.  c  om
        statement = connection.prepareStatement(CREATE_ACCOUNTOPERATIONS_STATEMENT);
        connection.setAutoCommit(false);

        statement.setInt(1, user_id);
        int typeOperation = ACCOUNT_OPERATION_DEPOSIT;
        if (type == OperationType.WITHDRAWAL) {
            typeOperation = ACCOUNT_OPERATION_WITHDRAWAL;
        }
        statement.setInt(2, typeOperation);

        statement.setLong(3, amount);
        Date now = new Date();
        java.sql.Timestamp sqlDate = new java.sql.Timestamp(now.getTime());
        statement.setTimestamp(4, sqlDate);
        statement.setNull(5, Types.INTEGER);
        statement.setNull(6, Types.INTEGER);

        statement.execute();
        ResultSet rs = statement.getGeneratedKeys();
        if (rs.next()) {
            operation.setId(rs.getInt(1));
            operation.setAmount(amount);
            operation.setDate(now);
            operation.setType(type);
        }
        Account account = getAccount(user_id);
        long balanceToSet = 0L;
        if (type == OperationType.DEPOSIT) {
            balanceToSet = account.getBalance() + amount;
        } else {
            balanceToSet = account.getBalance() - amount;
        }
        if (balanceToSet < 0) {
            throw new SQLException("Balance cannot become negative");
        }
        statementAccount = connection.prepareStatement(UPDATE_ACCOUNT_BY_ID_STATEMENT);
        statementAccount.setLong(1, balanceToSet);
        statementAccount.setInt(2, user_id);
        statementAccount.execute();

        connection.commit();
    } catch (SQLException e) {
        if (connection != null) {
            connection.rollback();
        }
        throw e;
    } finally {
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
    return operation;
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.JDBCConnector.java

public List<RowVO> getRows(String sql, List<ColumnVO> columns) throws Exception {
    List<RowVO> rows = new LinkedList<RowVO>();

    Exception error = null;//  ww w  .  ja va  2 s.  com

    Connection connection = null;
    PreparedStatement preparedStmnt = null;

    try {
        DataSource dataSource = poolDataSources.get(schemaId);
        connection = dataSource.getConnection();
        connection.setAutoCommit(false);

        preparedStmnt = connection.prepareStatement(sql);
        ResultSet result = preparedStmnt.executeQuery();
        while (result.next()) {
            RowVO row = new RowVO();
            for (ColumnVO column : columns) {
                String columnName = column.getNameOnTable();
                String columnValue = null;
                Object columnValueObj = result.getObject(columnName);
                if (columnValueObj != null) {
                    columnValue = columnValueObj.toString();

                }

                /* if the column is a geometry type then set the
                 * geometry column name of the row */
                if (column.getSqlType() == Types.OTHER) {
                    row.setGeomFieldName(columnName);
                }
                row.addField(columnName, columnValue);
            }
            rows.add(row);
        }
    } catch (SQLException e) {
        error = e;
    } finally {
        if (preparedStmnt != null) {
            try {
                preparedStmnt.close();
            } catch (SQLException se2) {
                log.warn("No se pudo cerrar el statment: ".concat(se2.getLocalizedMessage()));
            }
        }
        if (connection != null) {
            try {
                if (error != null) {
                    connection.rollback();
                }
            } catch (SQLException se) {
                log.warn("Se produjo un error al manejar la conexin: ".concat(se.getLocalizedMessage()));
            }
            try {
                connection.close();
            } catch (SQLException se) {
                log.warn("Se produjo un error al intentar cerrar la conexin: "
                        .concat(se.getLocalizedMessage()));
            }
        }
    }

    if (error != null) {
        throw error;
    }

    return rows;
}