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:gridool.db.partitioning.phihash.monetdb.MonetDBCsvLoadOperation.java

private static long invokeCopyInto(final Connection conn, final String copyIntoQuery, final String tableName,
        final String fileName, final long numRecords) throws SQLException {
    final File loadFile = prepareLoadFile(fileName);
    final String queryTpl = complementCopyIntoQuery(copyIntoQuery, loadFile);
    long rtotal = 0;
    try {/*from   ww w . j  a v a  2  s.  c  om*/
        if (ENV_COPYINTO_PIECES > 0) {
            for (long offset = 0; offset < numRecords; offset += ENV_COPYINTO_PIECES) {
                final long rest = numRecords - offset;
                if (rest > 0) {
                    final String query;
                    if (rest > ENV_COPYINTO_PIECES) {
                        query = getCopyIntoQuery(queryTpl, ENV_COPYINTO_PIECES, offset);
                    } else {
                        query = getCopyIntoQuery(queryTpl, rest, offset);
                    }
                    final int ret = JDBCUtils.update(conn, query);
                    if (ret > 0) {
                        rtotal += ret;
                    } else {
                        LOG.warn("Unexpected result '" + ret + "' for query: " + query);
                    }
                } else {
                    break;
                }
            }
        } else {
            String query = getCopyIntoQuery(queryTpl, numRecords);
            rtotal = JDBCUtils.update(conn, query);
        }
        conn.commit();
    } catch (SQLException e) {
        LOG.error("rollback a transaction: " + queryTpl, e);
        conn.rollback();
        throw e;
    } finally {
        new FileDeletionThread(loadFile, LOG).start();
    }
    return rtotal;
}

From source file:gridool.db.catalog.DistributionCatalog.java

public void registerPartition(@Nonnull GridNode master, @Nonnull final List<GridNode> slaves,
        @Nonnull final String distKey) throws GridException {
    synchronized (lock) {
        boolean needToInsertDb = true;
        Map<GridNode, List<NodeWithState>> mapping = distributionMap.get(distKey);
        if (mapping == null) {
            mapping = new HashMap<GridNode, List<NodeWithState>>(32);
            mapping.put(master, wrapNodes(slaves, true));
            if (distributionMap.put(distKey, mapping) != null) {
                throw new IllegalStateException();
            }//from w  w  w  .  j  a v a2s .com
        } else {
            final List<NodeWithState> slaveList = mapping.get(master);
            if (slaveList == null) {
                if (mapping.put(master, wrapNodes(slaves, true)) != null) {
                    throw new IllegalStateException();
                }
            } else {
                boolean noAdd = true;
                for (final GridNode slave : slaves) {
                    NodeWithState slaveWS = wrapNode(slave, true);
                    if (!slaveList.contains(slaveWS)) {
                        slaveList.add(slaveWS);
                        noAdd = false;
                    }
                }
                needToInsertDb = !noAdd;
            }
        }
        if (!needToInsertDb) {
            return;
        }
        final String insertQuery = "INSERT INTO \"" + distributionTableName + "\" VALUES(?, ?, ?, ?)";
        final Object[][] params = toNewParams(distKey, master, slaves);
        final Connection conn = GridDbUtils.getPrimaryDbConnection(dbAccessor, false);
        try {
            JDBCUtils.batch(conn, insertQuery, params);
            conn.commit();
        } catch (SQLException e) {
            String errmsg = "Failed to execute a query: " + insertQuery;
            LOG.error(errmsg, e);
            try {
                conn.rollback();
            } catch (SQLException sqle) {
                LOG.warn("rollback failed", e);
            }
            throw new GridException(errmsg, e);
        } finally {
            JDBCUtils.closeQuietly(conn);
        }
    }
}

From source file:com.adaptris.jdbc.connection.FailoverDatasourceTest.java

@Test
public void testCommitRollback() throws Exception {
    Connection conn = new MyProxy();

    try {//from   w  w  w.  ja va  2  s  .  co  m
        try {
            conn.setAutoCommit(conn.getAutoCommit());
        } catch (SQLException e) {

        }
        try {
            conn.setAutoCommit(false);
            conn.commit();
        } catch (SQLException e) {

        }

        try {
            conn.setAutoCommit(false);
            conn.rollback();
        } catch (SQLException e) {

        }

        try {
            conn.setAutoCommit(false);
            conn.rollback(conn.setSavepoint());
        } catch (SQLException e) {

        }
        try {
            conn.setAutoCommit(false);
            conn.rollback(conn.setSavepoint("test"));
        } catch (SQLException e) {

        }
        try {
            conn.setAutoCommit(false);
            conn.releaseSavepoint(conn.setSavepoint("test2"));
        } catch (SQLException e) {

        }
    } finally {
        JdbcUtil.closeQuietly(conn);

    }
}

From source file:com.mirth.connect.server.util.DatabaseUtil.java

public static void executeScript(String script, boolean ignoreErrors) throws Exception {
    SqlSessionManager sqlSessionManger = SqlConfig.getSqlSessionManager();

    Connection conn = null;
    ResultSet resultSet = null;//  www. j  a  va 2 s . com
    Statement statement = null;

    try {
        sqlSessionManger.startManagedSession();
        conn = sqlSessionManger.getConnection();

        /*
         * Set auto commit to false or an exception will be thrown when trying to rollback
         */
        conn.setAutoCommit(false);

        statement = conn.createStatement();

        Scanner s = new Scanner(script);

        while (s.hasNextLine()) {
            StringBuilder sb = new StringBuilder();
            boolean blankLine = false;

            while (s.hasNextLine() && !blankLine) {
                String temp = s.nextLine();

                if (temp.trim().length() > 0)
                    sb.append(temp + " ");
                else
                    blankLine = true;
            }

            // Trim ending semicolons so Oracle doesn't throw
            // "java.sql.SQLException: ORA-00911: invalid character"
            String statementString = StringUtils.removeEnd(sb.toString().trim(), ";");

            if (statementString.length() > 0) {
                try {
                    statement.execute(statementString);
                    conn.commit();
                } catch (SQLException se) {
                    if (!ignoreErrors) {
                        throw se;
                    } else {
                        logger.error("Error was encountered and ignored while executing statement: "
                                + statementString, se);
                        conn.rollback();
                    }
                }
            }
        }

    } catch (Exception e) {
        throw new Exception(e);
    } finally {
        DbUtils.closeQuietly(statement);
        DbUtils.closeQuietly(resultSet);
        DbUtils.closeQuietly(conn);
        sqlSessionManger.close();
    }
}

From source file:net.gcolin.simplerepo.search.SearchController.java

public void rebuild() throws IOException {
    if (running) {
        return;//  w  w  w .  j  a  v a  2  s . co  m
    }
    running = true;
    configManager.setCurrentAction(REBUILD + "initialize");
    nb = 0;
    try {
        final QueryRunner run = new QueryRunner();

        try {
            Connection connection = null;
            try {
                connection = datasource.getConnection();
                connection.setAutoCommit(false);
                run.update(connection, "delete from artifacttype");
                run.update(connection, "delete from artifactversion");
                run.update(connection, "delete from artifact");
                run.update(connection, "update artifactindex set artifact=1,version=1");
                connection.commit();
            } catch (SQLException ex) {
                connection.rollback();
                throw ex;
            } finally {
                DbUtils.close(connection);
            }
        } catch (SQLException ex) {
            logger.log(Level.SEVERE, null, ex);
            throw new IOException(ex);
        }
        for (final Repository repository : configManager.getConfiguration().getRepositories()) {
            File repo = new File(configManager.getRoot(), repository.getName());
            if (repo.exists()) {
                Files.walkFileTree(repo.toPath(), new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        nb++;
                        if (nb % 20 == 0) {
                            configManager.setCurrentAction(REBUILD + " " + nb + " files");
                        }
                        if (file.toString().endsWith(".pom")) {
                            Model model = readPom(file.toFile());
                            add(repository, file.toFile(), model);
                        }
                        return FileVisitResult.CONTINUE;
                    }

                });
            }
        }
    } finally {
        running = false;
        configManager.setCurrentAction(null);
    }
}

From source file:com.che.software.testato.domain.dao.jdbc.impl.ItemDAO.java

/**
 * Update an item to operationalize it./*w w w  .  j a v  a  2 s . co  m*/
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param itemId the item id.
 * @return the created test case id.
 * @since July, 2011.
 * @throws ItemUpdateDAOException if an error occurs during the update.
 */
@Override
public int operationalizeItem(int itemId) throws ItemUpdateDAOException {
    LOGGER.debug("operationalizeItem(" + itemId + ").");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        connection.setAutoCommit(false);
        getQueryRunner().update(connection,
                "INSERT INTO test_case(test_case_id) VALUES(nextval('test_case_id_seq')) ");
        Integer createdTestCase = (Integer) getQueryRunner().query(connection,
                "SELECT MAX(test_case_id)::int AS testCaseId FROM test_case ", new ScalarHandler("testCaseId"));
        getQueryRunner().update(connection, "UPDATE item SET test_case_id = ? WHERE item_id = ? ",
                new Object[] { createdTestCase, itemId });
        connection.commit();
        return createdTestCase;
    } catch (SQLException e) {
        try {
            connection.rollback();
        } catch (SQLException e1) {
            throw new ItemUpdateDAOException(e);
        }
        throw new ItemUpdateDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

From source file:edu.clemson.cs.nestbed.server.adaptation.sql.ProgramProfilingSymbolSqlAdapter.java

public ProgramProfilingSymbol updateProgramProfilingSymbol(int id, int configID, int programSymbolID)
        throws AdaptationException {
    ProgramProfilingSymbol pps = null;//  w  w w  .j av a2  s. c om
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;

    try {
        String query = "UPDATE ProgramProfilingSymbols SET " + "projectDeploymentConfigurationID = " + configID
                + ", " + "programSymbolID                  = " + programSymbolID + ", " + "WHERE id = " + id;

        connection = DriverManager.getConnection(CONN_STR);
        statement = connection.createStatement();
        statement.executeUpdate(query);

        query = "SELECT * from ProgramProfilingSymbols WHERE " + "id = " + id;
        resultSet = statement.executeQuery(query);

        if (!resultSet.next()) {
            connection.rollback();
            String msg = "Attempt to update program profiling " + "symbol failed.";
            log.error(msg);
            throw new AdaptationException(msg);
        }

        pps = getProfilingSymbol(resultSet);
        connection.commit();
    } catch (SQLException ex) {
        try {
            connection.rollback();
        } catch (Exception e) {
        }

        String msg = "SQLException in updateProgramProfilingSymbol";
        log.error(msg, ex);
        throw new AdaptationException(msg, ex);
    } finally {
        try {
            resultSet.close();
        } catch (Exception ex) {
        }
        try {
            statement.close();
        } catch (Exception ex) {
        }
        try {
            connection.close();
        } catch (Exception ex) {
        }
    }
    return pps;
}

From source file:edu.umd.cs.submitServer.servlets.UploadSubmission.java

public static Submission uploadSubmission(Project project, StudentRegistration studentRegistration,
        byte[] zipOutput, HttpServletRequest request, Timestamp submissionTimestamp, String clientTool,
        String clientVersion, String cvsTimestamp, SubmitServerDatabaseProperties db, Logger log)
        throws ServletException, IOException {

    Connection conn;
    try {/*from  ww w .  ja va 2 s.  c  o  m*/
        conn = db.getConnection();
    } catch (SQLException e) {
        throw new ServletException(e);
    }
    Submission submission = null;
    boolean transactionSuccess = false;

    try {
        Integer baselinePK = project.getArchivePK();
        int testSetupPK = project.getTestSetupPK();
        byte baseLineSubmission[] = null;
        if (baselinePK != null && baselinePK.intValue() != 0) {
            baseLineSubmission = project.getBaselineZip(conn);
        } else if (testSetupPK != 0) {
            baseLineSubmission = Submission.lookupCanonicalSubmissionArchive(project.getProjectPK(), conn);
        }
        zipOutput = FixZip.adjustZipNames(baseLineSubmission, zipOutput);

        int archivePK = Submission.uploadSubmissionArchive(zipOutput, conn);

        synchronized (UPLOAD_LOCK) {
            final int NUMBER_OF_ATTEMPTS = 2;
            int attempt = 1;
            while (true) {
                try {
                    conn.setAutoCommit(false);
                    conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

                    submission = Submission.submit(archivePK, studentRegistration, project, cvsTimestamp,
                            clientTool, clientVersion, submissionTimestamp, conn);

                    conn.commit();
                    transactionSuccess = true;
                    break;
                } catch (SQLException e) {
                    conn.rollback();

                    if (attempt++ >= NUMBER_OF_ATTEMPTS) {
                        Submission.deleteAbortedSubmissionArchive(archivePK, conn);
                        throw e;
                    }

                }
            }
        }

    } catch (SQLException e) {
        throw new ServletException(e);
    } finally {
        rollbackIfUnsuccessfulAndAlwaysReleaseConnection(transactionSuccess, request, conn, db, log);
    }
    logSubmission(studentRegistration, zipOutput, submission);

    if (submission.getBuildStatus() == Submission.BuildStatus.NEW)
        WaitingBuildServer.offerSubmission(project, submission);
    return submission;
}

From source file:edu.clemson.cs.nestbed.server.adaptation.sql.ProjectSqlAdapter.java

public Project createProject(int testbedID, String name, String description) throws AdaptationException {
    Project project = null;/*from  w w  w.j av  a 2 s  .co  m*/
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;

    try {
        String query = "INSERT INTO Projects(testbedID, name, " + "description) VALUES (" + testbedID + ", '"
                + name + "', '" + description + "')";

        connection = DriverManager.getConnection(CONN_STR);
        statement = connection.createStatement();
        statement.executeUpdate(query);

        query = "SELECT * FROM Projects WHERE " + " testbedID   = " + testbedID + "  AND " + " name        = '"
                + name + "' AND " + " description = '" + description + "'";

        resultSet = statement.executeQuery(query);

        if (!resultSet.next()) {
            connection.rollback();
            String msg = "Attempt to create project failed.";
            log.error(msg);
            throw new AdaptationException(msg);
        }

        project = getProject(resultSet);
        connection.commit();
    } catch (SQLException ex) {
        try {
            connection.rollback();
        } catch (Exception e) {
        }

        String msg = "SQLException in createProject";
        log.error(msg, ex);
        throw new AdaptationException(msg, ex);
    } finally {
        try {
            resultSet.close();
        } catch (Exception ex) {
        }
        try {
            statement.close();
        } catch (Exception ex) {
        }
        try {
            connection.close();
        } catch (Exception ex) {
        }
    }

    return project;
}

From source file:edu.clemson.cs.nestbed.server.adaptation.sql.MoteDeploymentConfigurationSqlAdapter.java

public MoteDeploymentConfiguration updateMoteDeploymentConfiguration(int mdConfigID, int programID,
        int radioPowerLevel) throws AdaptationException {
    MoteDeploymentConfiguration mdc = null;
    Connection connection = null;
    Statement statement = null;/*  w ww. j av a2  s.  co m*/
    ResultSet resultSet = null;

    try {
        String query = "UPDATE MoteDeploymentConfigurations SET " + "programID       = " + programID + ", "
                + "radioPowerLevel = " + radioPowerLevel + "  " + "WHERE id = " + mdConfigID;

        connection = DriverManager.getConnection(CONN_STR);
        statement = connection.createStatement();
        statement.executeUpdate(query);

        query = "SELECT * from MoteDeploymentConfigurations WHERE " + "id = " + mdConfigID;
        resultSet = statement.executeQuery(query);

        if (!resultSet.next()) {
            connection.rollback();
            String msg = "Unable to select updated config.";
            log.error(msg);
            ;
            throw new AdaptationException(msg);
        }

        mdc = getMoteDeploymentConfiguration(resultSet);
        connection.commit();
    } catch (SQLException ex) {
        try {
            connection.rollback();
        } catch (Exception e) {
        }

        String msg = "SQLException in updateMoteDeploymentConfiguration";
        log.error(msg, ex);
        throw new AdaptationException(msg, ex);
    } finally {
        try {
            resultSet.close();
        } catch (Exception ex) {
        }
        try {
            statement.close();
        } catch (Exception ex) {
        }
        try {
            connection.close();
        } catch (Exception ex) {
        }
    }

    return mdc;
}