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:com.concursive.connect.web.modules.documents.dao.FileItem.java

/**
 * Description of the Method// w w  w.j  av  a2s.c  om
 *
 * @param db Description of Parameter
 * @return Description of the Returned Value
 * @throws SQLException Description of Exception
 */
public boolean insert(Connection db) throws SQLException {
    if (!isValid()) {
        LOG.debug("Object validation failed");
        return false;
    }

    boolean result = false;
    boolean doCommit = false;
    try {
        if (doCommit = db.getAutoCommit()) {
            db.setAutoCommit(false);
        }
        StringBuffer sql = new StringBuffer();
        sql.append("INSERT INTO project_files "
                + "(folder_id, subject, client_filename, filename, version, size, ");
        sql.append("enabled, downloads, ");
        if (entered != null) {
            sql.append("entered, ");
        }
        if (modified != null) {
            sql.append("modified, ");
        }
        sql.append(" link_module_id, link_item_id, "
                + " enteredby, modifiedby, default_file, image_width, image_height, comment, featured_file) "
                + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ");
        if (entered != null) {
            sql.append("?, ");
        }
        if (modified != null) {
            sql.append("?, ");
        }
        sql.append("?, ?, ?, ?, ?, ?, ?, ?, ?) ");

        int i = 0;
        PreparedStatement pst = db.prepareStatement(sql.toString());
        if (folderId > 0) {
            pst.setInt(++i, folderId);
        } else {
            pst.setNull(++i, java.sql.Types.INTEGER);
        }
        pst.setString(++i, subject);
        pst.setString(++i, clientFilename);
        pst.setString(++i, filename);
        pst.setDouble(++i, version);
        pst.setInt(++i, size);
        pst.setBoolean(++i, enabled);
        pst.setInt(++i, downloads);
        if (entered != null) {
            pst.setTimestamp(++i, entered);
        }
        if (modified != null) {
            pst.setTimestamp(++i, modified);
        }
        pst.setInt(++i, linkModuleId);
        pst.setInt(++i, linkItemId);
        pst.setInt(++i, enteredBy);
        pst.setInt(++i, modifiedBy);
        pst.setBoolean(++i, defaultFile);
        pst.setInt(++i, imageWidth);
        pst.setInt(++i, imageHeight);
        pst.setString(++i, comment);
        pst.setBoolean(++i, featuredFile);
        pst.execute();
        pst.close();
        id = DatabaseUtils.getCurrVal(db, "project_files_item_id_seq", -1);
        // New default item
        if (defaultFile) {
            updateDefaultRecord(db, linkModuleId, linkItemId, id);
        }
        // Insert the version information
        if (doVersionInsert) {
            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);
        }
        logUpload(db);
        if (doCommit) {
            db.commit();
        }
        result = true;
    } catch (Exception e) {
        e.printStackTrace(System.out);
        if (doCommit) {
            db.rollback();
        }
        throw new SQLException(e.getMessage());
    } finally {
        if (doCommit) {
            db.setAutoCommit(true);
        }
    }
    return result;
}

From source file:org.apache.cocoon.acting.modular.DatabaseAction.java

/**
 * Add a record to the database.  This action assumes that
 * the file referenced by the "descriptor" parameter conforms
 * to the AbstractDatabaseAction specifications.
 *///ww  w  .ja  v  a 2 s. c o m
public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters param)
        throws Exception {

    DataSourceComponent datasource = null;
    Connection conn = null;
    Map results = new HashMap();
    int rows = 0;
    boolean failed = false;

    // read global parameter settings
    boolean reloadable = Constants.DESCRIPTOR_RELOADABLE_DEFAULT;

    // call specific default modes apart from output mode are not supported
    // set request attribute
    String outputMode = param.getParameter("output", (String) defaultModeNames.get(MODE_OUTPUT));

    if (this.settings.containsKey("reloadable")) {
        reloadable = Boolean.valueOf((String) this.settings.get("reloadable")).booleanValue();
    }
    // read local parameter settings
    try {
        Configuration conf = this.getConfiguration(
                param.getParameter("descriptor", (String) this.settings.get("descriptor")), resolver,
                param.getParameterAsBoolean("reloadable", reloadable));

        // get database connection and try to turn off autocommit
        datasource = this.getDataSource(conf, param);
        conn = datasource.getConnection();
        if (conn.getAutoCommit() == true) {
            try {
                conn.setAutoCommit(false);
            } catch (Exception ex) {
                String tmp = param.getParameter("use-transactions",
                        (String) this.settings.get("use-transactions", null));
                if (tmp != null && (tmp.equalsIgnoreCase("no") || tmp.equalsIgnoreCase("false")
                        || tmp.equalsIgnoreCase("0"))) {
                    if (getLogger().isErrorEnabled())
                        getLogger().error(
                                "This DB connection does not support transactions. If you want to risk your data's integrity by continuing nonetheless set parameter \"use-transactions\" to \"no\".");
                    throw ex;
                }
            }
        }

        // find tables to work with
        Configuration[] tables = conf.getChildren("table");
        String tablesetname = param.getParameter("table-set", (String) this.settings.get("table-set"));

        Map modeTypes = null;

        if (tablesetname == null) {
            modeTypes = new HashMap(6);
            modeTypes.put(MODE_AUTOINCR, "autoincr");
            modeTypes.put(MODE_OTHERS, "others");
            modeTypes.put(MODE_OUTPUT, outputMode);
            for (int i = 0; i < tables.length; i++) {
                rows += processTable(tables[i], conn, objectModel, results, modeTypes);
            }
        } else {
            // new set based behaviour

            // create index for table names / aliases
            Map tableIndex = new HashMap(2 * tables.length);
            String tableName = null;
            Object result = null;
            for (int i = 0; i < tables.length; i++) {
                tableName = tables[i].getAttribute("alias", tables[i].getAttribute("name", ""));
                result = tableIndex.put(tableName, new Integer(i));
                if (result != null) {
                    throw new IOException(
                            "Duplicate table entry for " + tableName + " at positions " + result + " and " + i);
                }
            }

            Configuration[] tablesets = conf.getChildren("table-set");
            String setname = null;
            boolean found = false;

            // find tables contained in tableset
            int j = 0;
            for (j = 0; j < tablesets.length; j++) {
                setname = tablesets[j].getAttribute("name", "");
                if (tablesetname.trim().equals(setname.trim())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new IOException(" given set " + tablesetname + " does not exists in a description file.");
            }

            Configuration[] set = tablesets[j].getChildren("table");

            for (int i = 0; i < set.length; i++) {
                // look for alternative mode types
                modeTypes = new HashMap(6);
                modeTypes.put(MODE_AUTOINCR, set[i].getAttribute("autoincr-mode", "autoincr"));
                modeTypes.put(MODE_OTHERS, set[i].getAttribute("others-mode", "others"));
                modeTypes.put(MODE_OUTPUT, outputMode);
                tableName = set[i].getAttribute("name", "");
                if (tableIndex.containsKey(tableName)) {
                    j = ((Integer) tableIndex.get(tableName)).intValue();
                    rows += processTable(tables[j], conn, objectModel, results, modeTypes);
                } else {
                    throw new IOException(
                            " given table " + tableName + " does not exists in a description file.");
                }
            }
        }

        if (conn.getAutoCommit() == false) {
            conn.commit();
        }

        // obtain output mode module and rollback output
        ServiceSelector outputSelector = null;
        OutputModule output = null;
        try {
            outputSelector = (ServiceSelector) this.manager.lookup(OUTPUT_MODULE_SELECTOR);
            if (outputMode != null && outputSelector != null && outputSelector.isSelectable(outputMode)) {
                output = (OutputModule) outputSelector.select(outputMode);
            }
            if (output != null) {
                output.commit(null, objectModel);
            } else if (getLogger().isWarnEnabled()) {
                getLogger().warn("Could not select output mode " + outputMode);
            }
        } catch (ServiceException e) {
            if (getLogger().isWarnEnabled()) {
                getLogger().warn("Could not select output mode " + outputMode + ":" + e.getMessage());
            }
        } finally {
            if (outputSelector != null) {
                if (output != null) {
                    outputSelector.release(output);
                }
                this.manager.release(outputSelector);
            }
        }
    } catch (Exception e) {
        failed = true;
        if (conn != null) {
            try {
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug("Rolling back transaction. Caused by " + e.getMessage());
                    e.printStackTrace();
                }
                conn.rollback();
                results = null;

                // obtain output mode module and commit output
                ServiceSelector outputSelector = null;
                OutputModule output = null;
                try {
                    outputSelector = (ServiceSelector) this.manager.lookup(OUTPUT_MODULE_SELECTOR);
                    if (outputMode != null && outputSelector != null
                            && outputSelector.isSelectable(outputMode)) {
                        output = (OutputModule) outputSelector.select(outputMode);
                    }
                    if (output != null) {
                        output.rollback(null, objectModel, e);
                    } else if (getLogger().isWarnEnabled()) {
                        getLogger().warn("Could not select output mode " + outputMode);
                    }
                } catch (ServiceException e2) {
                    if (getLogger().isWarnEnabled()) {
                        getLogger().warn("Could not select output mode " + outputMode + ":" + e2.getMessage());
                    }
                } finally {
                    if (outputSelector != null) {
                        if (output != null) {
                            outputSelector.release(output);
                        }
                        this.manager.release(outputSelector);
                    }
                }
            } catch (SQLException se) {
                if (getLogger().isDebugEnabled())
                    getLogger().debug("There was an error rolling back the transaction", se);
            }
        }

        //throw new ProcessingException("Could not add record :position = " + currentIndex, e);

        // don't throw an exception, an error has been signalled, that should suffice

        String throwException = (String) this.settings.get("throw-exception",
                param.getParameter("throw-exception", null));
        if (throwException != null && BooleanUtils.toBoolean(throwException)) {
            throw new ProcessingException("Cannot process the requested SQL statement ", e);
        }
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException sqe) {
                getLogger().warn("There was an error closing the datasource", sqe);
            }
        }

        if (datasource != null)
            this.dbselector.release(datasource);
    }
    if (results != null) {
        if (rows > 0 || (!failed && !this.failOnEmpty)) {
            results.put("row-count", new Integer(rows));
        } else {
            results = null;
        }
    } else {
        if (rows > 0) {
            results = new HashMap(1);
            results.put("row-count", new Integer(rows));
        }
    }

    return results; // (results == null? results : Collections.unmodifiableMap(results));
}

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

@Test
public void shouldValidateOneLevelShardedCall() 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);
    mockRegistry.addResource(same(TestUser.JOE.name()), anyObject(DepartmentDaoImpl.class));
    expect(mockShardBeanResolver.getBean(same(DepartmentDao.class), anyObject(ShardContext.class)))
            .andReturn(null);//w w  w  .j  a  v a2 s  . co m
    mockShardBeanEnricher.setup(anyObject(DepartmentDaoImpl.class), anyObject(ShardContext.class));
    mockShardBeanEnricher.tearDown(anyObject(DepartmentDaoImpl.class), anyObject(ShardContext.class));
    mockDataSource.close(true);
    mockRegistry.teardownConversation(testUserHelper.getJoeToken());
    // end protocol

    // This is the flow of a Hibernate transaction which is irrelevant, but had to be defined because of the
    // mocked dataSource.
    expect(mockDataSource.getConnection()).andReturn(mockConnection);
    mockConnection.setReadOnly(true);
    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);
    mockResultset.close();
    mockStatement.close();
    mockConnection.commit();
    // end Hibernate transaction

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

    try {
        ShardContext context = new ShardContext(TestUser.JOE.name());

        testService.authenticate(testUserHelper.getJoeToken());

        Long actualCount = testService.getCountOfDepartments(context);

        assertEquals(0, actualCount.longValue());
    } finally {
        testService.logoff(testUserHelper.getJoeToken());
    }

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

From source file:com.concursive.connect.web.modules.login.dao.User.java

/**
 * There's quite a bit of work to delete a user, so active users will
 * not be able to be deleted; this will simply delete a user without any
 * related data and without a profile/*from w ww.  j av  a  2 s  .c  o m*/
 *
 * @param db Description of the Parameter
 * @return Description of the Return Value
 * @throws SQLException Description of the Exception
 */
public int delete(Connection db) throws SQLException {
    int count = 0;
    boolean commit = db.getAutoCommit();
    try {
        if (commit) {
            db.setAutoCommit(false);
        }
        // Delete any login records
        PreparedStatement pst = db.prepareStatement("DELETE FROM user_log WHERE user_id = ?");
        pst.setInt(1, id);
        pst.execute();
        pst.close();
        // Delete the user
        pst = db.prepareStatement("DELETE FROM users WHERE user_id = ?");
        pst.setInt(1, id);
        count = pst.executeUpdate();
        pst.close();
        if (commit) {
            db.commit();
        }
        CacheUtils.invalidateValue(Constants.SYSTEM_USER_CACHE, id);
        //@todo enable
        //CacheUtils.invalidateValue(Constants.SYSTEM_USER_PROJECT_ROLE_CACHE, id);
    } catch (SQLException e) {
        if (commit) {
            db.rollback();
        }
        throw new SQLException(e.getMessage());
    } finally {
        if (commit) {
            db.setAutoCommit(true);
        }
    }
    return count;
}

From source file:com.concursive.connect.web.modules.login.dao.User.java

/**
 * Description of the Method/*from   w w w . j a v a  2  s .co  m*/
 *
 * @param db        The database connection
 * @param ipAddress The ip address requesting the user to be added
 * @param prefs     The application prefs
 * @return true if the record was added successfully
 * @throws SQLException Database exception
 */
public boolean insert(Connection db, String ipAddress, ApplicationPrefs prefs) throws SQLException {
    boolean commit = db.getAutoCommit();
    try {
        if (commit) {
            db.setAutoCommit(false);
        }
        // Insert the user
        PreparedStatement pst = db.prepareStatement("INSERT INTO users "
                + "(instance_id, group_id, department_id, first_name, last_name, username, password, temporary_password, "
                + "company, email, enteredby, modifiedby, enabled, start_page, access_personal, access_enterprise, "
                + "access_admin, access_inbox, access_resources, expiration, registered, "
                + "account_size, access_invite, access_add_projects, terms, timezone, currency, language"
                + (entered != null ? ", entered" : "") + (modified != null ? ", modified" : "") + ") "
                + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?"
                + (entered != null ? ", ?" : "") + (modified != null ? ", ?" : "") + ") ");
        int i = 0;
        DatabaseUtils.setInt(pst, ++i, instanceId);
        pst.setInt(++i, groupId);
        pst.setInt(++i, departmentId);
        pst.setString(++i, firstName);
        pst.setString(++i, lastName);
        pst.setString(++i, username);
        pst.setString(++i, password);
        pst.setString(++i, temporaryPassword);
        pst.setString(++i, company);
        pst.setString(++i, email);
        pst.setInt(++i, enteredBy);
        pst.setInt(++i, modifiedBy);
        pst.setBoolean(++i, enabled);
        pst.setInt(++i, startPage);
        pst.setBoolean(++i, true);
        pst.setBoolean(++i, true);
        pst.setBoolean(++i, accessAdmin);
        pst.setBoolean(++i, false);
        pst.setBoolean(++i, false);
        DatabaseUtils.setTimestamp(pst, ++i, expiration);
        pst.setBoolean(++i, registered);
        DatabaseUtils.setInt(pst, ++i, accountSize);
        pst.setBoolean(++i, accessInvite);
        pst.setBoolean(++i, accessAddProjects);
        pst.setBoolean(++i, terms);
        pst.setString(++i, timeZone);
        pst.setString(++i, currency);
        pst.setString(++i, language);
        if (entered != null) {
            pst.setTimestamp(++i, entered);
        }
        if (modified != null) {
            pst.setTimestamp(++i, modified);
        }
        pst.execute();
        pst.close();
        id = DatabaseUtils.getCurrVal(db, "users_user_id_seq", -1);
        // Record the IP
        if (ipAddress != null) {
            pst = db.prepareStatement("INSERT INTO user_log (user_id, ip_address) VALUES (?, ?)");
            pst.setInt(1, id);
            pst.setString(2, ipAddress);
            pst.execute();
            pst.close();
        }
        if (!isApiRestore()) {
            // Insert a corresponding user profile project
            UserUtils.addUserProfile(db, this, prefs);
            if (profileProjectId == -1) {
                LOG.error("profileProjectId did not get assigned!");
            }
        }
        if (commit) {
            db.commit();
        }
    } catch (Exception e) {
        LOG.error("adding user", e);
        if (commit) {
            db.rollback();
        }
        throw new SQLException(e.getMessage());
    } finally {
        if (commit) {
            db.setAutoCommit(true);
        }
    }
    return true;
}

From source file:org.apache.hive.beeline.BeeLine.java

void autocommitStatus(Connection c) throws SQLException {
    info(loc("autocommit-status", c.getAutoCommit() + ""));
}

From source file:org.sakaiproject.search.component.service.impl.SearchIndexBuilderWorkerImpl.java

public boolean getHardLock(long nodeLifetime, boolean forceLock) {
    String nodeID = getNodeID();/*from w  ww.j  av  a2 s.co m*/
    Connection connection = null;
    boolean locked = false;
    boolean autoCommit = false;
    PreparedStatement selectLock = null;
    PreparedStatement updateLock = null;
    PreparedStatement insertLock = null;
    PreparedStatement countWork = null;

    ResultSet resultSet = null;
    Timestamp now = new Timestamp(System.currentTimeMillis());
    Timestamp expiryDate = new Timestamp(now.getTime() + (10L * 60L * 1000L));

    try {

        // I need to go direct to JDBC since its just too awful to
        // try and do this in Hibernate.

        updateNodeLock(nodeLifetime);

        connection = dataSource.getConnection();
        autoCommit = connection.getAutoCommit();
        if (autoCommit) {
            connection.setAutoCommit(false);
        }

        selectLock = connection.prepareStatement(SELECT_LOCK_SQL);
        updateLock = connection.prepareStatement(UPDATE_LOCK_SQL);
        insertLock = connection.prepareStatement(INSERT_LOCK_SQL);
        countWork = connection.prepareStatement(COUNT_WORK_SQL);

        SearchWriterLock swl = null;
        selectLock.clearParameters();
        selectLock.setString(1, LOCKKEY);
        resultSet = selectLock.executeQuery();
        if (resultSet.next()) {
            swl = new SearchWriterLockImpl();
            swl.setId(resultSet.getString(1));
            swl.setNodename(resultSet.getString(2));
            swl.setLockkey(resultSet.getString(3));
            swl.setExpires(resultSet.getTimestamp(4));
            log.debug("GOT Lock Record " + swl.getId() + "::" + swl.getNodename() + "::" + swl.getExpires());

        }

        resultSet.close();
        resultSet = null;

        boolean takelock = false;
        if (swl == null) {
            log.debug("_-------------NO Lock Record");
            takelock = true;
        } else if ("none".equals(swl.getNodename())) {
            takelock = true;
            log.debug(nodeID + "_-------------no lock");
        } else if (nodeID.equals(swl.getNodename())) {
            takelock = true;
            log.debug(nodeID + "_------------matched threadid ");
        } else if (swl.getExpires() == null || swl.getExpires().before(now)) {
            takelock = true;
            log.debug(nodeID + "_------------thread dead ");
        }

        if (takelock) {
            // any work ?
            int nitems = 0;
            if (!forceLock) {
                countWork.clearParameters();
                countWork.setInt(1, SearchBuilderItem.STATE_PENDING.intValue());
                resultSet = countWork.executeQuery();
                if (resultSet.next()) {
                    nitems = resultSet.getInt(1);
                }
                resultSet.close();
                resultSet = null;
            }
            if (nitems > 0 || forceLock) {
                try {
                    if (swl == null) {
                        insertLock.clearParameters();
                        insertLock.setString(1, nodeID);
                        insertLock.setString(2, nodeID);
                        insertLock.setString(3, LOCKKEY);
                        insertLock.setTimestamp(4, expiryDate);

                        if (insertLock.executeUpdate() == 1) {
                            log.debug("INSERT Lock Record " + nodeID + "::" + nodeID + "::" + expiryDate);

                            locked = true;
                        }

                    } else {
                        updateLock.clearParameters();
                        updateLock.setString(1, nodeID);
                        updateLock.setTimestamp(2, expiryDate);
                        updateLock.setString(3, swl.getId());
                        updateLock.setString(4, swl.getNodename());
                        updateLock.setString(5, swl.getLockkey());
                        if (updateLock.executeUpdate() == 1) {
                            log.debug("UPDATED Lock Record " + swl.getId() + "::" + nodeID + "::" + expiryDate);
                            locked = true;
                        }

                    }
                } catch (SQLException sqlex) {
                    locked = false;
                    log.debug("Failed to get lock, but this is Ok ", sqlex);
                }

            }

        }
        connection.commit();

    } catch (Exception ex) {
        if (connection != null) {
            try {
                connection.rollback();
            } catch (SQLException e) {
                log.debug(e);
            }
        }
        log.error("Failed to get lock " + ex.getMessage());
        locked = false;
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                log.debug(e);
            }
        }
        if (selectLock != null) {
            try {
                selectLock.close();
            } catch (SQLException e) {
                log.debug(e);
            }
        }
        if (updateLock != null) {
            try {
                updateLock.close();
            } catch (SQLException e) {
                log.debug(e);
            }
        }
        if (insertLock != null) {
            try {
                insertLock.close();
            } catch (SQLException e) {
                log.debug(e);
            }
        }
        if (countWork != null) {
            try {
                countWork.close();
            } catch (SQLException e) {
                log.debug(e);
            }
        }

        if (connection != null) {
            try {
                connection.setAutoCommit(autoCommit);
            } catch (SQLException e) {
            }
            try {
                connection.close();
                log.debug("Connection Closed ");
            } catch (SQLException e) {
                log.error("Error Closing Connection ", e);
            }
            connection = null;
        }
    }
    return locked;

}

From source file:org.sakaiproject.db.impl.BasicSqlService.java

/**
 * {@inheritDoc}/*w  w  w  .ja  v  a 2  s. c  om*/
 */
public boolean transact(Runnable callback, String tag) {
    // if we are already in a transaction, stay in it (don't start a new one), and just run the callback (no retries, let the outside transaction
    // code handle that)
    if (threadLocalManager().get(TRANSACTION_CONNECTION) != null) {
        callback.run();
        return true;
    }

    // in case of deadlock we might retry
    for (int i = 0; i <= m_deadlockRetries; i++) {
        if (i > 0) {
            // make a little fuss
            LOG.warn("transact: deadlock: retrying (" + i + " / " + m_deadlockRetries + "): " + tag);

            // do a little wait, longer for each retry
            // TODO: randomize?
            try {
                Thread.sleep(i * 100L);
            } catch (Exception ignore) {
            }
        }

        Connection connection = null;
        boolean wasCommit = true;
        try {
            connection = borrowConnection();
            wasCommit = connection.getAutoCommit();
            connection.setAutoCommit(false);

            // store the connection in the thread
            threadLocalManager().set(TRANSACTION_CONNECTION, connection);

            callback.run();

            connection.commit();

            return true;
        } catch (SqlServiceDeadlockException e) {
            // rollback
            if (connection != null) {
                try {
                    connection.rollback();
                    LOG.warn("transact: deadlock: rolling back: " + tag);
                } catch (Exception ee) {
                    LOG.warn("transact: (deadlock: rollback): " + tag + " : " + ee);
                }
            }

            // if this was the last attempt, throw to abort
            if (i == m_deadlockRetries) {
                LOG.warn("transact: deadlock: retry failure: " + tag);
                throw e;
            }
        } catch (RuntimeException e) {
            // rollback
            if (connection != null) {
                try {
                    connection.rollback();
                    LOG.warn("transact: rolling back: " + tag);
                } catch (Exception ee) {
                    LOG.warn("transact: (rollback): " + tag + " : " + ee);
                }
            }
            LOG.warn("transact: failure: " + e);
            throw e;
        } catch (SQLException e) {
            // rollback
            if (connection != null) {
                try {
                    connection.rollback();
                    LOG.warn("transact: rolling back: " + tag);
                } catch (Exception ee) {
                    LOG.warn("transact: (rollback): " + tag + " : " + ee);
                }
            }
            LOG.warn("transact: failure: " + e);
            throw new RuntimeException("SqlService.transact failure", e);
        }

        finally {
            if (connection != null) {
                // clear the connection from the thread
                threadLocalManager().set(TRANSACTION_CONNECTION, null);

                try {
                    connection.setAutoCommit(wasCommit);
                } catch (Exception e) {
                    LOG.warn("transact: (setAutoCommit): " + tag + " : " + e);
                }
                returnConnection(connection);
            }
        }
    }

    return false;
}

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

protected ConnState beginTransaction(Connection conn, boolean serialized) throws SQLException {
    ConnState rslt = new ConnState();
    if (serialized) {
        rslt.isoLevel = conn.getTransactionIsolation();
        conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
    }// www . j a  v  a  2s . co  m
    rslt.autoCommit = conn.getAutoCommit();
    conn.setAutoCommit(false);
    return rslt;
}

From source file:com.wabacus.system.dataimport.DataImportItem.java

public void doImportData() {
    fileProcessor = configBean.createDataImportProcessor();
    if (datafileObj == null) {
        throw new WabacusDataImportException(
                "?" + configBean.getReskey() + "??");
    }/*from ww w .  j av  a 2  s .c o m*/
    if (!datafileObj.exists() || datafileObj.isDirectory()) {
        throw new WabacusDataImportException("?" + configBean.getReskey()
                + "?" + datafileObj.getAbsolutePath() + "?");
    }
    Connection conn = null;
    try {
        fileProcessor.init(datafileObj);
        if (configBean.getInterceptor() != null) {
            boolean flag = configBean.getInterceptor().doImportStart(this);
            if (!flag)
                return;
        }
        conn = Config.getInstance().getDataSource(configBean.getDatasource()).getConnection();
        AbsDatabaseType dbtype = Config.getInstance().getDataSource(configBean.getDatasource()).getDbType();
        if (dynimportype == null || dynimportype.trim().equals("")
                || dynimportype.trim().equals(configBean.getImporttype())) {//?????
            doUpdateData(conn, dbtype, configBean.getLstImportSqlObjs(null));
        } else if (dynimportype.trim().equals(Consts_Private.DATAIMPORTTYPE_APPEND)
                || dynimportype.trim().equals(Consts_Private.DATAIMPORTTYPE_OVERWRITE)) {
            doUpdateData(conn, dbtype, configBean.getLstImportSqlObjs(dynimportype));
        } else if (dynimportype.trim().equals(Consts_Private.DATAIMPORTTYPE_DELETE)) {
            doDeleteData(conn, dbtype);
        } else {
            log.warn("?" + this.datafileObj.getAbsolutePath()
                    + "?????");
            doUpdateData(conn, dbtype, configBean.getLstImportSqlObjs(null));
        }
        log.info("?" + datafileObj.getAbsolutePath() + "" + configBean.getReskey()
                + "?");
        try {
            if (configBean.getInterceptor() != null) {
                configBean.getInterceptor().doImportEnd(1, this, null);
            }
        } catch (Exception e) {
            throw new WabacusDataImportException(
                    "?" + datafileObj.getAbsolutePath() + "?", e);
        }
        if (!conn.getAutoCommit())
            conn.commit();
    } catch (Exception e) {
        if (configBean.getInterceptor() != null) {
            configBean.getInterceptor().doImportEnd(-1, this, e);
        }
        StringBuffer errorBuf = new StringBuffer();
        if (this.errorSqlTrace != null && !this.errorSqlTrace.trim().equals("")) {
            errorBuf.append("?SQL" + this.errorSqlTrace + "");
        }
        if (this.lstErrorColValuesTrace != null && this.lstErrorColValuesTrace.size() > 0) {
            errorBuf.append("?");
            for (int i = 0; i < this.lstErrorColValuesTrace.size(); i++) {
                errorBuf.append("[");
                if (this.lstColNamesTrace != null
                        && this.lstColNamesTrace.size() == this.lstErrorColValuesTrace.size()) {
                    errorBuf.append(this.lstColNamesTrace.get(i)).append(":");
                }
                errorBuf.append(this.lstErrorColValuesTrace.get(i)).append("]");
            }
        } else if (this.batchupdatesize != 1) {
            errorBuf.append(
                    "?wabacus.cfg.xmldataimport-batchupdate-size??1");
        }
        log.error(errorBuf.toString(), e);
        throw new WabacusDataImportException("?" + datafileObj.getAbsolutePath() + "");
    } finally {
        fileProcessor.destroy();
        WabacusAssistant.getInstance().release(conn, null);
    }
}