Example usage for java.sql Connection setTransactionIsolation

List of usage examples for java.sql Connection setTransactionIsolation

Introduction

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

Prototype

void setTransactionIsolation(int level) throws SQLException;

Source Link

Document

Attempts to change the transaction isolation level for this Connection object to the one given.

Usage

From source file:org.apache.hadoop.mapreduce.lib.db.DBInputFormat.java

public Connection createConnection() {
    try {//from ww  w.ja v a2 s  . co m
        Connection newConnection = dbConf.getConnection();
        newConnection.setAutoCommit(false);
        newConnection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);

        return newConnection;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jboss.dashboard.database.NonPooledDataSource.java

protected void setIsolation(Connection conn, int isolation) {
    try {/*w  w w  .jav a  2 s. c  o m*/
        if (conn.getTransactionIsolation() != isolation) {
            conn.setTransactionIsolation(isolation);
        }
    } catch (SQLException e) {
        log.debug("Can not set connection isolation.", e);
    }
}

From source file:org.wso2.carbon.dashboard.portal.core.datasource.DataBaseInitializer.java

/**
 * Returns an database connection for the Dashboards Data source
 *
 * @return Database connection// w  ww . j  av a2 s . com
 * @throws DashboardPortalException Exception to be thrown when we cannot connect to the DB source
 */
Connection getDBConnection() throws DashboardPortalException {
    try {
        Connection dbConnection = dataSource.getConnection();
        dbConnection.setAutoCommit(false);
        dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        return dbConnection;
    } catch (SQLException e) {
        throw new DashboardPortalException("Error connecting to the database", e);
    }
}

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  w w w . j a v a 2s . com*/
        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:com.glaf.core.jdbc.connection.DruidConnectionProvider.java

public Connection getConnection() throws SQLException {
    Connection connection = null;
    int count = 0;
    while (count < conf.getInt("jdbc.connection.retryCount", 10)) {
        try {/*  w ww . ja va2  s  .c o m*/
            connection = ds.getConnection();
            if (connection != null) {
                if (isolation != null) {
                    connection.setTransactionIsolation(isolation.intValue());
                }
                if (connection.getAutoCommit() != autocommit) {
                    connection.setAutoCommit(autocommit);
                }
                log.debug("druid connection: " + connection.toString());
                return connection;
            } else {
                count++;
                try {
                    Thread.sleep(conf.getInt("jdbc.connection.retryTimeMs", 500));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (SQLException ex) {
            count++;
            try {
                Thread.sleep(conf.getInt("jdbc.connection.retryTimeMs", 500));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count >= conf.getInt("jdbc.connection.retryCount", 10)) {
                ex.printStackTrace();
                throw ex;
            }
        }
    }
    return connection;
}

From source file:com.glaf.core.jdbc.connection.DBCPConnectionProvider.java

public Connection getConnection() throws SQLException {
    Connection connection = null;
    int count = 0;
    while (count < conf.getInt("jdbc.connection.retryCount", 10)) {
        try {//w  ww.j av  a 2  s .  c  o  m
            connection = ds.getConnection();
            if (connection != null) {
                if (isolation != null) {
                    connection.setTransactionIsolation(isolation.intValue());
                }
                if (connection.getAutoCommit() != autocommit) {
                    connection.setAutoCommit(autocommit);
                }
                return connection;
            } else {
                count++;
                try {
                    Thread.sleep(conf.getInt("jdbc.connection.retryTimeMs", 500));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (SQLException ex) {
            count++;
            try {
                Thread.sleep(conf.getInt("jdbc.connection.retryTimeMs", 500));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count >= conf.getInt("jdbc.connection.retryCount", 10)) {
                ex.printStackTrace();
                throw ex;
            }
        }
    }
    return connection;
}

From source file:org.craftercms.cstudio.alfresco.activityfeed.CStudioActivityFeedDaoServiceImpl.java

@Override
public void initIndexes() {
    DataSource dataSource = sqlMapper.getDataSource();
    Connection connection = null;
    int oldval = -1;
    try {// w  w  w  . j  av a2s .c o  m
        connection = dataSource.getConnection();
        oldval = connection.getTransactionIsolation();
        if (oldval != Connection.TRANSACTION_READ_COMMITTED) {
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        }

        List<HashMap> checkTable = sqlMapper.queryForList(STATEMENT_CHECK_TABLE_EXISTS);
        if (checkTable == null || checkTable.size() < 1) {
            ScriptRunner scriptRunner = new ScriptRunner(connection, false, true);
            scriptRunner.runScript(Resources.getResourceAsReader(initializeScriptPath));
        }
        connection.commit();
        List<TableIndexCheckTO> indexCheckResult = sqlMapper.queryForList(STATEMENT_CHECK_USER_IDX);
        if (indexCheckResult == null || indexCheckResult.size() < 1) {
            sqlMapper.insert(STATEMENT_ADD_USER_IDX);
        }
        indexCheckResult = sqlMapper.queryForList(STATEMENT_CHECK_SITE_IDX);
        if (indexCheckResult == null || indexCheckResult.size() < 1) {
            sqlMapper.insert(STATEMENT_ADD_SITE_IDX);
        }
        indexCheckResult = sqlMapper.queryForList(STATEMENT_CHECK_CONTENT_IDX);
        if (indexCheckResult == null || indexCheckResult.size() < 1) {
            sqlMapper.insert(STATEMENT_ADD_CONTENT_IDX);
        }
        connection.commit();
        if (oldval != -1) {
            connection.setTransactionIsolation(oldval);
        }
    } catch (SQLException e) {
        LOGGER.error("Error while initializing CStudio Activity DB indexes.", e);
    } catch (IOException e) {
        LOGGER.error("Error while initializing CStudio Activity DB indexes.", e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
            connection = null;
        }
    }
}

From source file:org.executequery.datasource.ConnectionPoolImpl.java

public void setTransactionIsolationLevel(int isolationLevel) {

    if (!isTransactionSupported()) {

        return;//from   w  ww .j  av a 2 s  .co m
    }

    int isolationLevelToApply = isolationLevel;
    if (isolationLevelToApply == -1) {

        isolationLevelToApply = defaultTxIsolation;
    }

    Log.debug("Setting transaction isolation level to open connections as [ "
            + nameForTransactionIsolationLevel(isolationLevelToApply) + " ]");

    try {

        synchronized (openConnections) {

            for (Connection connection : openConnections) {

                if (!connection.isClosed()) {

                    connection.setTransactionIsolation(isolationLevelToApply);
                }

            }

        }

    } catch (SQLException e) {

        throw new DataSourceException(e);
    }

}

From source file:net.fender.sql.DriverConnectionFactory.java

public Connection getConnection() throws SQLException {
    // don't log properties as it contains plain text user name and password
    log.debug("creating connection to " + driver + " " + url);
    Connection connection = driver.connect(url, properties);
    if (autoCommit != null) {
        connection.setAutoCommit(autoCommit);
    }/*from  ww w .j av a 2  s. c o m*/
    if (holdability != null) {
        connection.setHoldability(holdability.getHoldability());
    }
    if (readOnly != null) {
        connection.setReadOnly(readOnly);
    }
    if (transactionIsolation != null) {
        connection.setTransactionIsolation(transactionIsolation.getLevel());
    }
    if (catalog != null) {
        connection.setCatalog(catalog);
    }
    return connection;
}

From source file:edu.umd.cs.marmoset.modelClasses.Project.java

public static Project importProject(InputStream in, Course course,
        StudentRegistration canonicalStudentRegistration, Connection conn)
        throws SQLException, IOException, ClassNotFoundException {
    Project project = new Project();
    ZipInputStream zipIn = new ZipInputStream(in);

    // Start transaction
    conn.setAutoCommit(false);// w ww  . ja va  2  s .com
    conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);

    byte[] canonicalBytes = null;
    byte[] testSetupBytes = null;
    byte[] projectStarterFileBytes = null;

    while (true) {
        ZipEntry entry = zipIn.getNextEntry();
        if (entry == null)
            break;
        if (entry.getName().contains("project.out")) {
            // Found the serialized project!
            ObjectInputStream objectInputStream = new ObjectInputStream(zipIn);

            project = (Project) objectInputStream.readObject();

            // Set the PKs to null, the values that get serialized are actually from
            // a different database with a different set of keys
            project.setProjectPK(0);
            project.setTestSetupPK(0);
            project.setArchivePK(null);
            project.setVisibleToStudents(false);

            // These two PKs need to be passed in when we import/create the project
            project.setCoursePK(course.getCoursePK());
            project.setCanonicalStudentRegistrationPK(canonicalStudentRegistration.getStudentRegistrationPK());

            // Insert the project so that we have a projectPK for other methods
            project.insert(conn);

        } else if (entry.getName().contains("canonical")) {
            // Found the canonical submission...
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            CopyUtils.copy(zipIn, baos);
            canonicalBytes = baos.toByteArray();
        } else if (entry.getName().contains("test-setup")) {
            // Found the test-setup!
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            CopyUtils.copy(zipIn, baos);
            testSetupBytes = baos.toByteArray();
        } else if (entry.getName().contains("project-starter-files")) {
            // Found project starter files
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            CopyUtils.copy(zipIn, baos);
            projectStarterFileBytes = baos.toByteArray();
        }
    }

    Timestamp submissionTimestamp = new Timestamp(System.currentTimeMillis());

    // Now "upload" bytes as an archive for the project starter files, if it exists
    if (projectStarterFileBytes != null) {
        project.setArchiveForUpload(projectStarterFileBytes);
        project.uploadCachedArchive(conn);
    }

    // Now "submit" these bytes as a canonical submission
    // TODO read the submissionTimestamp from the serialized project in the archive
    Submission submission = Submission.submit(canonicalBytes, canonicalStudentRegistration, project,
            "t" + submissionTimestamp.getTime(), "ProjectImportTool, serialMinorVersion",
            Integer.toString(serialMinorVersion, 100), submissionTimestamp, conn);

    // Now "upload" the test-setup bytes as an archive
    String comment = "Project Import Tool uploaded at " + submissionTimestamp;
    TestSetup testSetup = TestSetup.submit(testSetupBytes, project, comment, conn);
    project.setTestSetupPK(testSetup.getTestSetupPK());
    testSetup.setTestRunPK(submission.getCurrentTestRunPK());

    testSetup.update(conn);

    return project;
}