Example usage for java.sql Connection getAutoCommit

List of usage examples for java.sql Connection getAutoCommit

Introduction

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

Prototype

boolean getAutoCommit() throws SQLException;

Source Link

Document

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

Usage

From source file:org.horizontaldb.integration.InterceptorMockEnvironmentTest.java

@Test
public void shouldValidateMultiLevelShardedCalls() throws SQLException {
    ConversationRegistry mockRegistry = EasyMock.createMock(ConversationRegistry.class);
    TenantContext mockTenantContext = EasyMock.createMock(TenantContext.class);
    org.apache.tomcat.jdbc.pool.DataSource mockDataSource = EasyMock
            .createMock(org.apache.tomcat.jdbc.pool.DataSource.class);
    DataSourceResource mockDataSourceResource = new DataSourceResource(mockDataSource);
    ShardBeanResolver mockShardBeanResolver = EasyMock.createMock(ShardBeanResolver.class);
    ShardBeanEnricher mockShardBeanEnricher = EasyMock.createMock(ShardBeanEnricher.class);
    Connection mockConnection = EasyMock.createMock(Connection.class);
    PreparedStatement mockStatement = EasyMock.createMock(PreparedStatement.class);
    ResultSet mockResultset = EasyMock.createMock(ResultSet.class);

    conversationRegistryMockProxy.setMockRegistry(mockRegistry);
    tenantContextMockProxy.setMockTenantContext(mockTenantContext);
    dataSourceFactoryMockProxy.setMockDataSourceResource(mockDataSourceResource);
    shardBeanResolverMockProxy.setMockResolver(mockShardBeanResolver);
    shardBeanEnricherMockProxy.setMockEnricher(mockShardBeanEnricher);

    // This is the protocol that the interceptors should follow during a sharded call
    mockRegistry.startConversation(testUserHelper.getJoeToken());
    expect(mockRegistry.hasConversation(TestUser.JOE.name())).andReturn(true);
    expect(mockTenantContext.resolveCurrentTenantIdentifier()).andReturn(TestUser.JOE.name());
    mockRegistry.addResource(TestUser.JOE.name(), mockDataSourceResource);

    // resolve Dao for TestServiceTwo
    expect(mockShardBeanResolver.getBean(same(PersonDao.class), anyObject(ShardContext.class))).andReturn(null);
    mockRegistry.addResource(same(TestUser.JOE.name()), anyObject(PersonDao.class));
    mockShardBeanEnricher.setup(anyObject(PersonDao.class), anyObject(ShardContext.class));
    mockShardBeanEnricher.tearDown(anyObject(PersonDao.class), anyObject(ShardContext.class));

    // Hibernate transaction flow
    expect(mockDataSource.getConnection()).andReturn(mockConnection);
    mockConnection.setReadOnly(true);/*from   w  w  w . j a v  a 2  s. com*/
    expect(mockConnection.getAutoCommit()).andReturn(false);
    expect(mockConnection.prepareStatement(anyObject(String.class))).andReturn(mockStatement);
    expect(mockStatement.executeQuery()).andReturn(mockResultset);
    expect(mockStatement.getWarnings()).andReturn(null);
    mockStatement.clearWarnings();
    expect(mockStatement.getMaxRows()).andReturn(0);
    expect(mockStatement.getQueryTimeout()).andReturn(0);
    expect(mockResultset.next()).andReturn(true);
    expect(mockResultset.next()).andReturn(false);
    expect(mockResultset.getLong(anyObject(String.class))).andReturn(0l);
    expect(mockResultset.wasNull()).andReturn(false);
    expect(mockResultset.getLong(anyObject(String.class))).andReturn(0l);
    expect(mockResultset.wasNull()).andReturn(true);
    expect(mockResultset.getString(anyObject(String.class))).andReturn("mockPerson");
    expect(mockResultset.wasNull()).andReturn(false);
    mockResultset.close();
    mockStatement.close();
    mockConnection.commit();
    // end Hibernate transaction

    // resolve Dao for TestServiceThree
    expect(mockRegistry.hasConversation(TestUser.JOE.name())).andReturn(true);
    expect(mockShardBeanResolver.getBean(same(DepartmentDao.class), anyObject(ShardContext.class)))
            .andReturn(null);
    mockRegistry.addResource(same(TestUser.JOE.name()), anyObject(DepartmentDaoImpl.class));
    mockShardBeanEnricher.setup(anyObject(DepartmentDaoImpl.class), anyObject(ShardContext.class));
    mockShardBeanEnricher.tearDown(anyObject(DepartmentDaoImpl.class), anyObject(ShardContext.class));

    // Hibernate transaction flow
    expect(mockConnection.prepareStatement(anyObject(String.class))).andReturn(mockStatement);
    expect(mockStatement.executeQuery()).andReturn(mockResultset);
    expect(mockStatement.getWarnings()).andReturn(null);
    mockStatement.clearWarnings();
    expect(mockStatement.getMaxRows()).andReturn(0);
    expect(mockStatement.getQueryTimeout()).andReturn(0);
    expect(mockResultset.next()).andReturn(true);
    expect(mockResultset.next()).andReturn(false);
    expect(mockResultset.getLong(anyObject(String.class))).andReturn(0l);
    expect(mockResultset.wasNull()).andReturn(false);
    expect(mockResultset.getString(anyObject(String.class))).andReturn("mockDepartment");
    expect(mockResultset.wasNull()).andReturn(false);
    mockResultset.close();
    mockStatement.close();
    // end Hibernate transaction

    // cleanup after service calls
    mockDataSource.close(true);
    mockRegistry.teardownConversation(testUserHelper.getJoeToken());

    replay(mockRegistry, mockTenantContext, mockShardBeanResolver, mockShardBeanEnricher, mockDataSource,
            mockConnection, mockStatement, mockResultset);

    try {
        testService.authenticate(testUserHelper.getJoeToken());

        testService.callNestedServiceChain(TestUser.JOE.name());
    } finally {
        testService.logoff(testUserHelper.getJoeToken());
    }

    verify(mockRegistry, mockTenantContext, mockShardBeanResolver, mockShardBeanEnricher, mockDataSource,
            mockConnection, mockStatement, mockResultset);
}

From source file:nl.b3p.viewer.util.databaseupdate.ScriptRunner.java

/**
 * Runs an SQL script (read in using the Reader parameter) using the
 * connection passed in/*from  w w w  .ja v a 2 s  .  c o m*/
 *
 * @param conn - the connection to use for the script
 * @param reader - the source of the script
 * @throws SQLException if any SQL errors occur
 * @throws IOException if there is an error reading from the Reader
 */
private void runScript(Connection conn, Reader reader) throws IOException, SQLException {
    StringBuffer command = null;
    try {
        LineNumberReader lineReader = new LineNumberReader(reader);
        String line = null;
        while ((line = lineReader.readLine()) != null) {
            if (command == null) {
                command = new StringBuffer();
            }
            String trimmedLine = line.trim();
            if (trimmedLine.startsWith("--")) {
                log.debug(trimmedLine);
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
                // Do nothing
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) {
                // Do nothing
            } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter())
                    || fullLineDelimiter && trimmedLine.equals(getDelimiter())) {
                command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
                command.append(" ");
                Statement statement = conn.createStatement();

                log.debug(command);

                boolean hasResults = false;
                if (stopOnError) {
                    hasResults = statement.execute(command.toString());
                } else {
                    try {
                        statement.execute(command.toString());
                    } catch (SQLException e) {
                        e.fillInStackTrace();
                        log.error("Error executing: " + command, e);
                    }
                }

                if (autoCommit && !conn.getAutoCommit()) {
                    conn.commit();
                }

                ResultSet rs = statement.getResultSet();
                if (hasResults && rs != null) {
                    ResultSetMetaData md = rs.getMetaData();
                    int cols = md.getColumnCount();
                    for (int i = 0; i < cols; i++) {
                        String name = md.getColumnLabel(i);
                        log.debug(name + "\t");
                    }
                    while (rs.next()) {
                        for (int i = 0; i < cols; i++) {
                            String value = rs.getString(i);
                            log.debug(value + "\t");
                        }
                    }
                }

                command = null;
                try {
                    statement.close();
                } catch (Exception e) {
                    // Ignore to workaround a bug in Jakarta DBCP
                }
                Thread.yield();
            } else {
                command.append(line);
                command.append(" ");
            }
        }
        if (!autoCommit) {
            conn.commit();
        }
    } catch (SQLException e) {
        e.fillInStackTrace();
        log.error("Error executing: " + command, e);
        throw e;
    } catch (IOException e) {
        e.fillInStackTrace();
        log.error("Error executing: " + command, e);
        throw e;
    } finally {
        if (!this.autoCommit) {
            conn.rollback();
        }
    }
}

From source file:com.concursive.connect.web.modules.documents.dao.FileItem.java

/**
 * Description of the Method/* ww w  . java2s  .  co m*/
 *
 * @param db Description of Parameter
 * @return Description of the Returned Value
 * @throws SQLException Description of Exception
 */
public boolean insertVersion(Connection db) throws SQLException {
    if (!isValid()) {
        return false;
    }
    boolean result = false;
    boolean doCommit = false;
    try {
        if (doCommit = db.getAutoCommit()) {
            db.setAutoCommit(false);
        }
        //Insert a new version of an existing file
        FileItemVersion thisVersion = new FileItemVersion();
        thisVersion.setId(this.getId());
        thisVersion.setSubject(subject);
        thisVersion.setClientFilename(clientFilename);
        thisVersion.setFilename(filename);
        thisVersion.setVersion(version);
        thisVersion.setSize(size);
        thisVersion.setEnteredBy(enteredBy);
        thisVersion.setModifiedBy(modifiedBy);
        thisVersion.setImageWidth(imageWidth);
        thisVersion.setImageHeight(imageHeight);
        thisVersion.setComment(comment);
        thisVersion.insert(db);

        //Update the master record
        int i = 0;
        PreparedStatement pst = db.prepareStatement("UPDATE project_files "
                + "SET subject = ?, client_filename = ?, filename = ?, version = ?, "
                + "size = ?, modifiedby = ?, modified = CURRENT_TIMESTAMP, comment = ?, image_width = ?, image_height = ? , featured_file = ? "
                + "WHERE item_id = ? ");
        pst.setString(++i, subject);
        pst.setString(++i, clientFilename);
        pst.setString(++i, filename);
        pst.setDouble(++i, version);
        pst.setInt(++i, size);
        pst.setInt(++i, modifiedBy);
        pst.setString(++i, comment);
        pst.setInt(++i, imageWidth);
        pst.setInt(++i, imageHeight);
        pst.setBoolean(++i, featuredFile);
        pst.setInt(++i, this.getId());
        pst.execute();
        pst.close();
        logUpload(db);
        if (doCommit) {
            db.commit();
        }
        result = true;
    } catch (Exception e) {
        LOG.error("Could not insert version", e);
        if (doCommit) {
            db.rollback();
        }
        throw new SQLException(e.getMessage());
    } finally {
        if (doCommit) {
            db.setAutoCommit(true);
        }
    }
    return result;
}

From source file:fll.db.Queries.java

/**
 * Delete a team from the database. This clears team from the Teams table and
 * all tables specified by the challengeDocument. It is not an error if the
 * team doesn't exist.//from  w w w.  j a  v  a  2s .c  o m
 * 
 * @param teamNumber team to delete
 * @param connection connection to database, needs delete privileges
 * @throws SQLException on an error talking to the database
 */
@SuppressFBWarnings(value = {
        "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING" }, justification = "Category name determines table")
public static void deleteTeam(final int teamNumber, final ChallengeDescription description,
        final Connection connection) throws SQLException {
    PreparedStatement prep = null;
    final boolean autoCommit = connection.getAutoCommit();
    try {
        connection.setAutoCommit(false);

        // delete from TournamentTeams
        prep = connection.prepareStatement("DELETE FROM TournamentTeams WHERE TeamNumber = ?");
        prep.setInt(1, teamNumber);
        prep.executeUpdate();
        SQLFunctions.close(prep);
        prep = null;

        // delete from subjective categories
        for (final ScoreCategory category : description.getSubjectiveCategories()) {
            final String name = category.getName();
            prep = connection.prepareStatement("DELETE FROM " + name + " WHERE TeamNumber = ?");
            prep.setInt(1, teamNumber);
            prep.executeUpdate();
            SQLFunctions.close(prep);
            prep = null;
        }

        // delete from Performance
        prep = connection.prepareStatement("DELETE FROM Performance WHERE TeamNumber = ?");
        prep.setInt(1, teamNumber);
        prep.executeUpdate();
        SQLFunctions.close(prep);
        prep = null;

        // delete from FinalScores
        prep = connection.prepareStatement("DELETE FROM FinalScores WHERE TeamNumber = ?");
        prep.setInt(1, teamNumber);
        prep.executeUpdate();
        SQLFunctions.close(prep);
        prep = null;

        // delete from schedule
        prep = connection.prepareStatement("DELETE FROM sched_perf_rounds WHERE team_number = ?");
        prep.setInt(1, teamNumber);
        prep.executeUpdate();
        SQLFunctions.close(prep);
        prep = null;
        prep = connection.prepareStatement("DELETE FROM sched_subjective WHERE team_number = ?");
        prep.setInt(1, teamNumber);
        prep.executeUpdate();
        SQLFunctions.close(prep);
        prep = null;
        prep = connection.prepareStatement("DELETE FROM schedule WHERE team_number = ?");
        prep.setInt(1, teamNumber);
        prep.executeUpdate();
        SQLFunctions.close(prep);
        prep = null;

        // delete from Teams
        prep = connection.prepareStatement("DELETE FROM Teams WHERE TeamNumber = ?");
        prep.setInt(1, teamNumber);
        prep.executeUpdate();
        SQLFunctions.close(prep);
        prep = null;

        connection.commit();
    } finally {
        try {
            connection.setAutoCommit(autoCommit);
        } catch (final SQLException e) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(e, e);
            }
        }
        SQLFunctions.close(prep);
    }
}

From source file:org.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java

/**
 * Return a {@link Connection} to the write pool
 * /*  ww  w  .  j  a  va 2s .  c  om*/
 * @param connection
 *            {@link Connection} to return
 * @throws AnzoException
 *             {@link ExceptionConstants.RDB#FAILED_GETTING_CONNECTION} if there was a problem returning a connection to the write pool
 * 
 */
private void returnWriteConnection(Connection connection) throws AnzoException {
    try {
        if (!connection.isClosed()) {
            if (!connection.getAutoCommit()) {
                abort(connection, false, true);
            }
            writePool.returnObject(connection);
        } else {
            writePool.invalidateObject(connection);
        }

    } catch (AnzoException ae) {
        throw ae;
    } catch (Exception exception) {
        throw new AnzoException(ExceptionConstants.RDB.FAILED_RETURNING_CONNECTION, exception);
    }
}

From source file:org.cfr.capsicum.datasource.CayenneTransactionManager.java

/**
 * This implementation sets the isolation level but ignores the timeout.
 */// ww  w .  ja  va  2s  .  c o  m
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    CayenneTransactionObject txObject = (CayenneTransactionObject) transaction;
    Connection con = null;

    try {
        if (txObject.getConnectionHolder() == null
                || txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
            Connection newCon = this.dataSource.getConnection();
            if (logger.isDebugEnabled()) {
                logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
            }
            ObjectContext context = null;
            if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
                Injector injector = this.cayenneRuntime.getInjector();
                context = injector.getInstance(ObjectContextFactory.class).createContext();
            } else {
                context = BaseContext.getThreadObjectContext();
            }
            txObject.setConnectionHolder(new CayenneConnectionHolder(newCon, context), true);
            BaseContext.bindThreadObjectContext(context);
        }

        txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
        con = txObject.getConnectionHolder().getConnection();

        Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
        txObject.setPreviousIsolationLevel(previousIsolationLevel);

        // Switch to manual commit if necessary. This is very expensive in
        // some
        // JDBC drivers,
        // so we don't want to do it unnecessarily (for example if we've
        // explicitly
        // configured the connection pool to set it already).
        if (con.getAutoCommit()) {
            txObject.setMustRestoreAutoCommit(true);
            if (logger.isDebugEnabled()) {
                logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
            }
            con.setAutoCommit(false);
        }
        txObject.getConnectionHolderEx().setTransactionActive(true);

        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
        }

        // Bind the session holder to the thread.
        if (txObject.isNewConnectionHolder()) {
            TransactionSynchronizationManager.bindResource(getDataSource(), txObject.getConnectionHolder());
        }
    }

    catch (SQLException ex) {
        DataSourceUtils.releaseConnection(con, this.dataSource);
        throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction",
                exceptionTranslator.convertJdbcAccessException(ex));
    }
}

From source file:org.gsoft.admin.ScriptRunner.java

/**
 * Runs an SQL script (read in using the Reader parameter) using the
 * connection passed in/*  ww  w  . j  a v a2s  .  c o  m*/
 * 
 * @param conn
 *            - the connection to use for the script
 * @param reader
 *            - the source of the script
 * @throws SQLException
 *             if any SQL errors occur
 * @throws IOException
 *             if there is an error reading from the Reader
 */
private void runScript(Connection conn, Reader reader) throws IOException, SQLException {
    StringBuffer command = null;
    try {
        LineNumberReader lineReader = new LineNumberReader(reader);
        String line = null;
        while ((line = lineReader.readLine()) != null) {
            if (command == null) {
                command = new StringBuffer();
            }
            String trimmedLine = line.trim();
            if (trimmedLine.startsWith("--")) {
                println(trimmedLine);
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
                // Do nothing
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) {
                // Do nothing
            } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter())
                    || fullLineDelimiter && trimmedLine.equals(getDelimiter())) {
                command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
                command.append(" ");
                Statement statement = conn.createStatement();

                println(command);

                boolean hasResults = false;
                if (stopOnError) {
                    hasResults = statement.execute(command.toString());
                } else {
                    try {
                        statement.execute(command.toString());
                    } catch (SQLException e) {
                        e.fillInStackTrace();
                        printlnError("Error executing: " + command);
                        printlnError(e);
                    }
                }

                if (autoCommit && !conn.getAutoCommit()) {
                    conn.commit();
                }

                ResultSet rs = statement.getResultSet();
                if (hasResults && rs != null) {
                    ResultSetMetaData md = rs.getMetaData();
                    int cols = md.getColumnCount();
                    for (int i = 0; i < cols; i++) {
                        String name = md.getColumnLabel(i);
                        print(name + "\t");
                    }
                    println("");
                    while (rs.next()) {
                        for (int i = 0; i < cols; i++) {
                            String value = rs.getString(i);
                            print(value + "\t");
                        }
                        println("");
                    }
                }

                command = null;
                try {
                    statement.close();
                } catch (Exception e) {
                    // Ignore to workaround a bug in Jakarta DBCP
                }
                Thread.yield();
            } else {
                command.append(line);
                command.append(" ");
            }
        }
        if (!autoCommit) {
            conn.commit();
        }
    } catch (SQLException e) {
        e.fillInStackTrace();
        printlnError("Error executing: " + command);
        printlnError(e);
        throw e;
    } catch (IOException e) {
        e.fillInStackTrace();
        printlnError("Error executing: " + command);
        printlnError(e);
        throw e;
    } finally {
        conn.rollback();
        flush();
    }
}

From source file:com.concursive.connect.web.modules.documents.dao.FileItem.java

/**
 * Description of the Method//from   w w w. java 2s.  c  o m
 *
 * @param db Description of Parameter
 * @return Description of the Returned Value
 * @throws SQLException Description of Exception
 */
public int update(Connection db) throws SQLException {
    if (this.getId() == -1) {
        throw new SQLException("ID was not specified");
    }
    if (!isValid()) {
        return -1;
    }
    int resultCount = 0;
    boolean commit = db.getAutoCommit();
    try {
        if (commit) {
            db.setAutoCommit(false);
        }
        int i = 0;
        // NOTE: Do not update the "modified" field because it is used for file paths
        PreparedStatement pst = db.prepareStatement("UPDATE project_files "
                + "SET subject = ?, client_filename = ?, default_file = ?, comment = ?, featured_file = ? "
                + "WHERE item_id = ? ");
        pst.setString(++i, subject);
        pst.setString(++i, clientFilename);
        pst.setBoolean(++i, defaultFile);
        pst.setString(++i, comment);
        pst.setBoolean(++i, featuredFile);
        pst.setInt(++i, this.getId());
        resultCount = pst.executeUpdate();
        pst.close();
        // Set default
        if (defaultFile) {
            updateDefaultRecord(db, linkModuleId, linkItemId, id);
        }
        // Retrieve any versions
        this.buildVersionList(db);
        // Update version info for the corresponding file item version
        for (FileItemVersion latestVersion : versionList) {
            if (Double.toString(this.version).equals(Double.toString(latestVersion.getVersion()))) {
                latestVersion.setClientFilename(this.getClientFilename());
                latestVersion.setSubject(this.getSubject());
                latestVersion.setComment(this.getComment());
                latestVersion.update(db);
                break;
            }
        }
    } catch (Exception e) {
        if (commit) {
            db.rollback();
        }
        throw new SQLException(e.getMessage());
    } finally {
        if (commit) {
            db.setAutoCommit(true);
        }
    }
    return resultCount;
}

From source file:com.nextep.designer.vcs.ui.controllers.MergeController.java

/**
 * @see com.nextep.datadesigner.gui.model.InvokableController#invoke(java.lang.Object)
 *///from w  w  w  .jav a  2 s  .  c o  m
@Override
public Object invoke(Object... model) {
    if (model.length == 0) {
        throw new ErrorException("The merge controller need at least 1 non-null argument to proceed.");
    } else {
        final IVersionable<?> versionable = (IVersionable<?>) model[0];
        final MergeWizard wiz = new MergeWizard(new MergeInitGUI(versionable),
                new MergePreviewWizard(versionable));
        wiz.setToVersionable(versionable);
        WizardDialog w = new WizardDialog(
                VCSUIPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(), wiz);
        w.setBlockOnOpen(true);
        w.open();
        if (w.getReturnCode() != Window.CANCEL) {
            // FIXME QUICKFIX calling this static method => TO remove !!!
            MergeStrategy.setIsGenerating(false);
            // try {
            final IMerger m = MergerFactory.getMerger(wiz.getToRelease());
            // Building compare command
            ICommand compareCommand = new ICommand() {

                @Override
                public Object execute(Object... parameters) {
                    return m.compare(wiz.getReference(), wiz.getFromRelease(), wiz.getToRelease(), true);
                }

                @Override
                public String getName() {
                    return "Computing differences between " + wiz.getToRelease().getLabel() + " and "
                            + wiz.getFromRelease().getLabel();
                }
            };
            final IComparisonItem comp = (IComparisonItem) CommandProgress.runWithProgress(compareCommand)
                    .iterator().next();

            ProgressMonitorDialog pd = new ProgressMonitorDialog(
                    VCSUIPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getShell());
            try {
                pd.run(true, false, new MergeProgress(comp, m));
            } catch (Exception e) {
                throw new ErrorException(e);
            }
            // } finally {
            MergeStrategy.setIsGenerating(true);
            // }
            MergeResultGUI mergeGUI = new MergeResultGUI(true, comp);
            mergeGUI.setIsRepositoryMerge(true);
            mergeGUI.setRootText("Source release " + wiz.getFromRelease().getLabel() + " [" //$NON-NLS-2$
                    + wiz.getFromRelease().getBranch().getName() + "]", //$NON-NLS-1$
                    "Current target release " + wiz.getToRelease().getLabel() + " [" //$NON-NLS-2$
                            + wiz.getToRelease().getBranch().getName() + "]", //$NON-NLS-1$
                    "Merge result");
            boolean doItAgain = true;
            while (doItAgain) {
                invokeGUI(new GUIWrapper(mergeGUI, "Merge results", 800, 600));
                // Checking that everything is resolved
                if (comp.getMergeInfo().getStatus() != MergeStatus.MERGE_RESOLVED) {
                    // IF not we ask if the user would like to edit again
                    doItAgain = MessageDialog.openQuestion(
                            VCSUIPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(),
                            VCSUIMessages.getString("mergeUnresolvedTitle"), //$NON-NLS-1$
                            VCSUIMessages.getString("mergeUnresolved")); //$NON-NLS-1$
                    if (!doItAgain) {
                        throw new CancelException("Merge operation aborted due to unresolved conflicts.");
                    }
                } else {
                    doItAgain = false;
                }
            }
            // We fall here if no cancel exception
            // HibernateUtil.getInstance().getSession().clear();
            // IdentifiableDAO.getInstance().loadAll(VersionReference.class);
            HibernateUtil.getInstance().clearAllSessions();
            pd = new ProgressMonitorDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
            try {
                pd.run(false, false, new IRunnableWithProgress() {

                    @Override
                    public void run(IProgressMonitor monitor)
                            throws InvocationTargetException, InterruptedException {
                        monitor.beginTask("Merge in progress...", 5);
                        // Global listeners switch off
                        Observable.deactivateListeners();
                        // Refreshing progress
                        monitor.worked(1);
                        IVersionable<?> mergedObject = null;
                        try {
                            // Building the merge result
                            final String activityText = "Merged " + wiz.getFromRelease().getLabel() + " -> " //$NON-NLS-2$
                                    + wiz.getFromRelease().getBranch().getName();
                            final IVersioningService versioningService = VCSPlugin
                                    .getService(IVersioningService.class);
                            final IActivity mergeActivity = versioningService.createActivity(activityText);
                            mergedObject = (IVersionable<?>) m.buildMergedObject(comp, mergeActivity);
                            // Checking if the merge did anything
                            if (mergedObject instanceof IVersionable<?>) {
                                if (((IVersionable<?>) mergedObject).getVersion()
                                        .getStatus() == IVersionStatus.CHECKED_IN) {
                                    final boolean forceMerge = MessageDialog.openQuestion(
                                            Display.getCurrent().getActiveShell(),
                                            VCSUIMessages.getString("mergeDidNothingTitle"), //$NON-NLS-1$
                                            VCSUIMessages.getString("mergeDidNothing")); //$NON-NLS-1$
                                    if (forceMerge) {
                                        comp.getMergeInfo().setMergeProposal(null);
                                        mergedObject = (IVersionable<?>) m.buildMergedObject(comp,
                                                mergeActivity);
                                    } else {
                                        return;
                                    }
                                }
                            }
                        } finally {
                            Observable.activateListeners();
                        }
                        LOGGER.info("Merged successfully!");
                        // Refreshing progress
                        monitor.worked(1);
                        monitor.setTaskName("Updating view contents...");

                        // Temporary bugfix for DES-710
                        // TODO refactor EVERYTHING as a service
                        final Session session = HibernateUtil.getInstance().getSandBoxSession();

                        // FIXME draft of view removal / addition of the merged object
                        // Switching versionables (for database only)
                        IVersionContainer parent = versionable.getContainer();
                        // First removing current versionable in current session
                        parent.getContents().remove(versionable);
                        versionable.setContainer(null);

                        // Forcing save of module without parent
                        final IIdentifiableDAO identifiableDao = CorePlugin.getIdentifiableDao();
                        identifiableDao.save(parent);
                        // Refreshing progress
                        monitor.worked(1);
                        // Reloading parent container in sandbox (because merged object is in
                        // sandbox)

                        if (parent instanceof IWorkspace) {
                            parent = (IVersionContainer) identifiableDao.load(Workspace.class, parent.getUID(),
                                    session, false);
                        } else {
                            parent = (IVersionContainer) identifiableDao.load(IVersionable.class,
                                    parent.getUID(), session, false);
                        }
                        // Refreshing progress
                        monitor.worked(1);
                        monitor.setTaskName("Committing to repository...");
                        // Adding sandbox merged object
                        mergedObject.setContainer(parent);
                        parent.getContents().add(mergedObject);
                        // Saving to sandbox before reloading view

                        identifiableDao.save(mergedObject);
                        session.flush();
                        // **************
                        // DES-710 urgent workaround
                        // Hibernate does not properly send the INSERT statements to the db
                        // But logs it properly in the logs !
                        final IRepositoryService repositoryService = CorePlugin.getRepositoryService();
                        final IConnectionService connectionService = CorePlugin.getConnectionService();
                        final IConnection repositoryConnection = repositoryService.getRepositoryConnection();
                        Connection conn = null;
                        PreparedStatement stmt = null;
                        try {
                            conn = connectionService.connect(repositoryConnection);
                            String insertSql = null;
                            if (parent instanceof IWorkspace) {
                                insertSql = "INSERT INTO rep_view_contents ( " //$NON-NLS-1$
                                        + "  view_id, version_id " //$NON-NLS-1$
                                        + ") VALUES ( " //$NON-NLS-1$
                                        + "  ?, ? " //$NON-NLS-1$
                                        + ") "; //$NON-NLS-1$
                            } else {
                                insertSql = "INSERT INTO rep_module_contents ( " //$NON-NLS-1$
                                        + "  module_id, version_id " //$NON-NLS-1$
                                        + ") VALUES ( " //$NON-NLS-1$
                                        + "  ?, ? " //$NON-NLS-1$
                                        + ") "; //$NON-NLS-1$
                            }
                            stmt = conn.prepareStatement(insertSql);
                            stmt.setLong(1, parent.getUID().rawId());
                            stmt.setLong(2, mergedObject.getUID().rawId());
                            stmt.execute();
                            if (!conn.getAutoCommit()) {
                                conn.commit();
                            }
                        } catch (SQLException e) {
                            LOGGER.error(e);
                        } finally {
                            if (stmt != null) {
                                try {
                                    stmt.close();
                                } catch (SQLException e) {
                                    LOGGER.error(e);
                                }
                            }
                            if (conn != null) {
                                try {
                                    conn.close();
                                } catch (SQLException e) {
                                    LOGGER.error(e);
                                }
                            }
                        }
                        // End of DES-710 workaround
                        // **************

                        // HibernateUtil.getInstance().reconnectAll();
                        // Merger.save(mergedObject);
                        // Merger.save(parent);
                        monitor.worked(1);
                        LOGGER.info("Please wait while view is reloading...");
                        monitor.setTaskName("Finished: Reloading view...");
                        monitor.done();
                        // END OF the fixme part

                    }

                });
            } catch (Exception e) {
                throw new ErrorException(e);
            }

            // Restoring a new view
            LOGGER.info("Refreshing current view");
            VersionUIHelper.changeView(VersionHelper.getCurrentView().getUID());

            // Designer.getInstance().invokeSelection("com.neXtep.designer.vcs.SelectionInvoker",
            // "version.compare", comp);
        }
    }
    return null;
}

From source file:fll.db.Queries.java

/**
 * Insert or update a performance score.
 * /*from  w  ww. j  a v a2  s  .  c om*/
 * @throws SQLException on a database error.
 * @throws RuntimeException if a parameter is missing.
 * @throws ParseException if the team number cannot be parsed
 */
public static void insertOrUpdatePerformanceScore(final ChallengeDescription description,
        final Connection connection, final HttpServletRequest request)
        throws SQLException, ParseException, RuntimeException {
    final int oldTransactionIsolation = connection.getTransactionIsolation();
    final boolean oldAutoCommit = connection.getAutoCommit();
    try {
        // make sure that we don't get into a race with another thread
        connection.setAutoCommit(false);
        connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);

        final int rowsUpdated = updatePerformanceScore(description, connection, request);
        if (rowsUpdated < 1) {
            insertPerformanceScore(description, connection, request);
        }
        connection.commit();
    } finally {
        connection.setTransactionIsolation(oldTransactionIsolation);
        connection.setAutoCommit(oldAutoCommit);
    }
}