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:eionet.acl.PersistenceDB.java

private void close(Connection con, Statement stmt, ResultSet rset) throws SQLException {
    try {/* ww  w.  j  av  a  2  s .  c  om*/
        if (rset != null) {
            rset.close();
        }
        if (stmt != null) {
            stmt.close();
            if (!con.getAutoCommit()) {
                con.commit();
            }
        }
    } catch (Exception e) {
        throw new SQLException("Error" + e.getMessage());
    } finally {
        try {
            con.close();
        } catch (SQLException e) {
            throw new SQLException("Error" + e.getMessage());
        }
    }
}

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

/**
 * To check whether a dashboard contains a gadget that is already deleted
 *
 * @param tenantId    Id of the tenant which the dashboard belongs to
 * @param dashboardId Id of the dashboard
 * @return true if the dashboard contains gadget that is already deleted, otherwise false
 * @throws DashboardPortalException//from   w w  w.  j ava  2s .  c  om
 */
public boolean isDashboardDefective(int tenantId, String dashboardId) throws DashboardPortalException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    String deletedGadgetState = "DELETED";
    try {
        connection = dataBaseInitializer.getDBConnection();
        preparedStatement = connection.prepareStatement(DataSourceConstants.SQL_CHECK_DEFECTIVE_DASHBOARD);
        preparedStatement.setInt(1, tenantId);
        preparedStatement.setString(2, dashboardId);
        preparedStatement.setString(3, deletedGadgetState);
        resultSet = preparedStatement.executeQuery();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
        if (resultSet.first()) {
            return true;
        }
    } catch (SQLException e) {
        log.error("Cannot check defective dashboard ", e);
    } finally {
        closeDatabaseResources(connection, preparedStatement, null);
    }
    return false;
}

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

/**
 * To update the record on a gadget usage
 *
 * @param tenantID    ID of the tenant which the dashboard belongs to
 * @param dashboardID ID of the dashboard
 * @param gadgetId    ID of the gadget//www. jav  a2 s.c om
 * @param gadgetState State of the gadget whether it is deleted or not
 * @param usageData   Usage information of the gadget
 * @throws DashboardPortalException
 */
public void updateGadgetUsageInfo(int tenantID, String dashboardID, String gadgetId, String gadgetState,
        String usageData) throws DashboardPortalException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    try {
        connection = dataBaseInitializer.getDBConnection();
        preparedStatement = connection.prepareStatement(DataSourceConstants.SQL_UPDATE_USAGE_OPERATION);
        preparedStatement.setString(1, gadgetState);
        preparedStatement.setString(2, usageData);
        preparedStatement.setInt(3, tenantID);
        preparedStatement.setString(4, dashboardID);
        preparedStatement.setString(5, gadgetId);
        preparedStatement.executeUpdate();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
    } catch (SQLException e) {
        log.error("Cannot insert the gadget usage info ", e);
    } finally {
        closeDatabaseResources(connection, preparedStatement, null);
    }
}

From source file:org.flowable.cmmn.engine.impl.db.CmmnDbSchemaManager.java

protected Liquibase createLiquibaseInstance(CmmnEngineConfiguration cmmnEngineConfiguration)
        throws SQLException, DatabaseException, LiquibaseException {

    // If a command context is currently active, the current connection needs to be reused.
    Connection jdbcConnection = null;
    CommandContext commandContext = CommandContextUtil.getCommandContext();
    if (commandContext == null) {
        jdbcConnection = cmmnEngineConfiguration.getDataSource().getConnection();
    } else {/*from ww  w. j av  a2s.  c  o  m*/
        jdbcConnection = CommandContextUtil.getDbSqlSession(commandContext).getSqlSession().getConnection();
    }

    // A commit is needed here, because one of the things that Liquibase does when acquiring its lock
    // is doing a rollback, which removes all changes done so far. 
    // For most databases, this is not a problem as DDL statements are not transactional.
    // However for some (e.g. sql server), this would remove all previous statements, which is not wanted,
    // hence the extra commit here.
    if (!jdbcConnection.getAutoCommit()) {
        jdbcConnection.commit();
    }

    DatabaseConnection connection = new JdbcConnection(jdbcConnection);
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection);
    database.setDatabaseChangeLogTableName(
            CmmnEngineConfiguration.LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogTableName());
    database.setDatabaseChangeLogLockTableName(
            CmmnEngineConfiguration.LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogLockTableName());

    String databaseSchema = cmmnEngineConfiguration.getDatabaseSchema();
    if (StringUtils.isNotEmpty(databaseSchema)) {
        database.setDefaultSchemaName(databaseSchema);
        database.setLiquibaseSchemaName(databaseSchema);
    }

    String databaseCatalog = cmmnEngineConfiguration.getDatabaseCatalog();
    if (StringUtils.isNotEmpty(databaseCatalog)) {
        database.setDefaultCatalogName(databaseCatalog);
        database.setLiquibaseCatalogName(databaseCatalog);
    }

    return createLiquibaseInstance(database);
}

From source file:org.hyperic.hq.events.server.session.RegisteredTriggerManagerImpl.java

@PostConstruct
public void cleanupRegisteredTriggers() {
    Connection conn = null;
    Statement stmt = null;// ww  w .j  ava 2 s .c o  m
    Boolean autocommit = null;
    boolean commit = false;
    try {
        conn = dbUtil.getConnection();
        autocommit = Boolean.valueOf(conn.getAutoCommit());
        conn.setAutoCommit(false);
        stmt = conn.createStatement();
        stmt.addBatch("update EAM_ALERT_CONDITION set trigger_id = null " + "WHERE exists ("
                + "select 1 from EAM_ALERT_DEFINITION WHERE deleted = '1' "
                + "AND EAM_ALERT_CONDITION.alert_definition_id = id" + ")");
        stmt.addBatch("delete from EAM_REGISTERED_TRIGGER WHERE exists ("
                + "select 1 from EAM_ALERT_DEFINITION WHERE deleted = '1' "
                + "AND EAM_REGISTERED_TRIGGER.alert_definition_id = id" + ")");
        int[] rows = stmt.executeBatch();
        conn.commit();
        commit = true;
        log.info("disassociated " + rows[0] + " triggers in EAM_ALERT_CONDITION"
                + " from their deleted alert definitions");
        log.info("deleted " + rows[1] + " rows from EAM_REGISTERED_TRIGGER");
    } catch (SQLException e) {
        log.error(e, e);
    } finally {
        resetAutocommit(conn, autocommit);
        if (!commit)
            rollback(conn);
        DBUtil.closeJDBCObjects(RegisteredTriggerManagerImpl.class.getName(), conn, stmt, null);
    }
}

From source file:migration.RepositoryUpgrader.java

/**
        //from   ww  w.j a  v a  2  s  . c  om
 * This should be ordered by uri, always.  the folder always comes first
        
 * @param parentId String of the parent folder structure id
        
 * @return List of class Folder
        
 * @throws SQLException
        
 */

protected List getChildren(ReFolder parentFolder) //throws SQLException

{

    Connection connection = null;
    boolean wasCommit = false;
    try {
        connection = SqlService.borrowConnection();

        wasCommit = connection.getAutoCommit();

        connection.setAutoCommit(false);

        String sql = "select row_id, parent,  osp_tree_node.id, osp_tree_node.name, uri, " +

                "creation, last_modified, owner_id, worksiteId, typeId " +

                "from osp_tree_node join osp_node_metadata on osp_tree_node.id=osp_node_metadata.id " +

                "where parent ";

        Object[] fields = null;

        if (parentFolder != null) {

            sql += "=? ";

            fields = new Object[1];

            fields[0] = parentFolder.getFolderStructureId();

        } else

            sql += "is null ";

        sql += "order by uri";

        List children = SqlService.dbRead(connection, sql, fields, new SqlReader() {

            public Object readSqlResultRecord(ResultSet result)

            {

                try

                {

                    RepositoryEntity ent = null;

                    String type = result.getString(10);

                    if (type.equals("folder")) {

                        ent = new ReFolder();

                    } else if (type.equals("fileArtifact")) {

                        ent = new ReFile();

                    } else {

                        ent = new ReForm(type);

                    }

                    ent.setFolderStructureId(result.getString(1));

                    ent.setParentFolderId(result.getString(2));

                    ent.setArtifactId(result.getString(3));

                    ent.setTitle(result.getString(4));

                    ent.setUri(result.getString(5));

                    ent.setCreationDate(result.getDate(6));

                    ent.setLastModifiedDate(result.getDate(7));

                    ent.setOwnerId(result.getString(8));

                    ent.setWorksiteId(result.getString(9));

                    return ent;

                } catch (SQLException ignore) {

                    return null;

                }

            }

        });

        for (Iterator i = children.iterator(); i.hasNext();) {

            RepositoryEntity ent = (RepositoryEntity) i.next();

            ent.setParentFolder(parentFolder);

        }

        return children;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            connection.commit();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            connection.setAutoCommit(wasCommit);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        SqlService.returnConnection(connection);
    }
    return null;
}

From source file:org.wso2.carbon.apimgt.impl.dao.CertificateMgtDAO.java

/**
 * To remove the entries of updated certificates from gateway.
 *
 * @param apiIdentifier : Identifier of the API.
 * @param tenantId      : ID of the tenant.
 * @throws CertificateManagementException Certificate Management Exception.
 *//*from w  ww  .j  a  v a2  s  . co m*/
public void updateRemovedCertificatesFromGateways(APIIdentifier apiIdentifier, int tenantId)
        throws CertificateManagementException {
    Connection connection = null;
    String getCertQuery = SQLConstants.ClientCertificateConstants.DELETE_CERTIFICATES_FOR_API;
    PreparedStatement preparedStatement = null;

    try {
        connection = APIMgtDBUtil.getConnection();
        initialAutoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        int apiId = ApiMgtDAO.getInstance().getAPIID(apiIdentifier, connection);
        preparedStatement = connection.prepareStatement(getCertQuery);
        preparedStatement.setInt(1, tenantId);
        preparedStatement.setInt(2, apiId);
        preparedStatement.setBoolean(3, true);
        preparedStatement.executeUpdate();
        connection.commit();
    } catch (SQLException e) {
        handleConnectionRollBack(connection);
        handleException("SQL exception while updating removed certificates from gateway for the api "
                + apiIdentifier.toString(), e);
    } catch (APIManagementException e) {
        handleConnectionRollBack(connection);
        handleException("API management exception while updating removed certificates from gateway for the api "
                + apiIdentifier.toString(), e);
    } finally {
        APIMgtDBUtil.setAutoCommit(connection, initialAutoCommit);
        APIMgtDBUtil.closeAllConnections(preparedStatement, connection, null);
    }
}

From source file:org.wso2.carbon.apimgt.impl.dao.CertificateMgtDAO.java

/**
 * Method to delete a certificate from the database.
 *
 * @param alias    : Alias for the certificate.
 * @param endpoint : The endpoint/ server url which the certificate is mapped to.
 * @param tenantId : The Id of the tenant who owns the certificate.
 * @return : true if certificate deletion is successful, false otherwise.
 *///  w  w w . j a v  a  2s. c  o  m
public boolean deleteCertificate(String alias, String endpoint, int tenantId)
        throws CertificateManagementException {

    Connection connection = null;
    PreparedStatement preparedStatement = null;
    boolean result = false;
    String deleteCertQuery = SQLConstants.CertificateConstants.DELETE_CERTIFICATES;

    try {
        connection = APIMgtDBUtil.getConnection();
        initialAutoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        preparedStatement = connection.prepareStatement(deleteCertQuery);
        preparedStatement.setInt(1, tenantId);
        preparedStatement.setString(2, alias);
        result = preparedStatement.executeUpdate() == 1;
        connection.commit();
        connection.setAutoCommit(initialAutoCommit);
    } catch (SQLException e) {
        handleConnectionRollBack(connection);
        handleException("Error while deleting certificate metadata. ", e);
    } finally {
        APIMgtDBUtil.closeStatement(preparedStatement);
        APIMgtDBUtil.closeAllConnections(preparedStatement, connection, null);
    }
    return result;
}

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

/**
 * To get the details of the defective usage data
 * @param tenantId Id of the tenant which dashboard belongs to
 * @param dashboardId Id of the dashboard
 * @return Array list of usage data which has the deleted gadgets
 * @throws DashboardPortalException/*  w  w  w .  ja  v  a2s.  com*/
 */
public List<String> getDefectiveUsageData(int tenantId, String dashboardId) throws DashboardPortalException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    List<String> defectiveUsageData = new ArrayList<String>();
    String deletedGadgetState = "DELETED";

    try {
        connection = dataBaseInitializer.getDBConnection();
        preparedStatement = connection.prepareStatement(DataSourceConstants.SQL_CHECK_DEFECTIVE_DASHBOARD);
        preparedStatement.setInt(1, tenantId);
        preparedStatement.setString(2, dashboardId);
        preparedStatement.setString(3, deletedGadgetState);
        resultSet = preparedStatement.executeQuery();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
        while (resultSet.next()) {
            defectiveUsageData.add(resultSet.getString("USAGE_DATA"));
        }
    } catch (SQLException e) {
        log.error("Cannot check defective dashboard ", e);
    } finally {
        closeDatabaseResources(connection, preparedStatement, resultSet);
    }
    return defectiveUsageData;
}

From source file:org.artifactory.storage.db.util.JdbcHelper.java

@Nonnull
public ResultSet executeSelect(String query, boolean allowDirtyReads, Object... params) throws SQLException {
    selectQueriesCounter.incrementAndGet();
    debugSql(query, params);/*from w  w  w.  j  a va  2  s. c  o  m*/

    PerfTimer timer = null;
    if (log.isDebugEnabled()) {
        timer = new PerfTimer();
    }
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
        con = getConnection();
        // allow dirty reads in case of non transactional aql query
        //@Todo need to a fine better (elegant) way to force this
        TxHelper.allowDirtyReads(allowDirtyReads, con);
        if (params == null || params.length == 0) {
            stmt = con.createStatement();
            rs = stmt.executeQuery(query);
        } else {
            PreparedStatement pstmt = con.prepareStatement(parseInListQuery(query, params));
            stmt = pstmt;
            setParamsToStmt(pstmt, params);
            rs = pstmt.executeQuery();
        }
        if (!TxHelper.isInTransaction() && !con.getAutoCommit()) {
            con.commit();
        }
        if (timer != null && log.isDebugEnabled()) {
            timer.stop();
            log.debug("Query returned in {} : '{}'", timer, resolveQuery(query, params));
        }
        return ResultSetWrapper.newInstance(con, stmt, rs, dataSource);
    } catch (Exception e) {
        // update isolation level back to read committed
        updateConnectionIsolationLevelToReadCommitted(allowDirtyReads, con);
        DbUtils.close(con, stmt, rs, dataSource);
        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException("Unexpected exception: " + e.getMessage(), e);
        }
    }
}