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.ralasafe.application.ApplicationManagerImpl.java

public void deleteApplicationUserType(String appName, String userTypeName) {
    Connection conn = null;
    boolean autoCommit = true;
    try {/*from   w  ww . jav  a  2  s.  co m*/
        conn = DBPower.getConnection(table.getId());
        autoCommit = conn.getAutoCommit();
        conn.setAutoCommit(false);

        // delete ApplicationUserType infos
        ApplicationUserType hint = new ApplicationUserType();
        hint.setAppName(appName);
        hint.setUserTypeName(userTypeName);

        applicationUserTypeDeletor.delete(conn, appNameUserTypeNameUserTypeTableWhereEmt, hint);

        // drop userrole tables
        DBUtil.exec(conn, DBUtil.userRoleTableDropSql(appName, userTypeName));

        conn.commit();
    } catch (SQLException e) {
        throw new DBLevelException(e);
    } finally {
        DBUtil.setCommitMode(conn, autoCommit);
        DBUtil.close(conn);
    }

    changed = true;
}

From source file:org.apache.empire.samples.cxf.wssample.server.ServerControl.java

private Connection getJDBCConnection() {
    // Establish a new database connection
    Connection conn = null;
    String jdbcURL = config.getJdbcURL();

    // Connect//from  w ww.j  a  v a 2s. c  o  m
    log.info("Connecting to Database'" + jdbcURL + "' / User=" + config.getJdbcUser());
    try { // Connect to the databse
        Class.forName(config.getJdbcClass()).newInstance();
        conn = DriverManager.getConnection(jdbcURL, config.getJdbcUser(), config.getJdbcPwd());
        log.info("Connected successfully");
        // Set the AutoCommit to false this session. 
        // You must commit explicitly now.
        conn.setAutoCommit(false);
        log.info("AutoCommit is " + conn.getAutoCommit());

    } catch (Exception e) {
        log.error("Failed to connect directly to '" + config.getJdbcURL() + "' / User=" + config.getJdbcUser());
        log.error(e.toString());
        throw new RuntimeException(e);
    }
    return conn;
}

From source file:org.ralasafe.application.ApplicationManagerImpl.java

public void deleteApplication(String name) {
    Application app = getApplication(name);

    // delete infos
    Connection conn = null;
    boolean autoCommit = true;
    try {/*from  w ww  .j av  a  2 s . c o  m*/
        conn = DBPower.getConnection(table.getId());
        autoCommit = conn.getAutoCommit();
        conn.setAutoCommit(false);

        ApplicationUserType appUserType = new ApplicationUserType();
        appUserType.setAppName(name);
        applicationUserTypeDeletor.delete(conn, appNameUserTypeTableWhereEmt, appUserType);

        Application hint = new Application();
        hint.setName(name);
        deletor.delete(conn, appNameWhereEmt, hint);

        conn.commit();
    } catch (SQLException e) {
        DBUtil.rollback(conn);
        throw new DBLevelException(e);
    } finally {
        DBUtil.setCommitMode(conn, autoCommit);
        DBUtil.close(conn);
    }

    changed = true;

    // delete tables
    deleteTablesForApp(app);

    // notify Factory
    org.ralasafe.Factory.applicationChanged(app.getName());
}

From source file:org.ralasafe.application.ApplicationManagerImpl.java

public void updateApplicatonUserType(String appName, UserType userType) {
    Connection conn = null;
    boolean autoCommit = true;
    try {//from ww  w .j  av  a2  s .  com
        conn = DBPower.getConnection(table.getId());
        autoCommit = conn.getAutoCommit();
        conn.setAutoCommit(false);

        ApplicationUserType appUserType = new ApplicationUserType();
        appUserType.setAppName(appName);
        appUserType.setUserTypeName(userType.getName());
        String userMetadataStr = produceUserMetadataStr(userType.getUserMetadata());
        appUserType.setUserMetadataStr(userMetadataStr);

        // delete original app-usertype
        applicationUserTypeDeletor.delete(conn, appNameUserTypeNameUserTypeTableWhereEmt, appUserType);

        // save newly app-usertype
        try {
            applicationUserTypeSaver.save(conn, appUserType);
        } catch (EntityExistException e) {
            // should not happen
            e.printStackTrace();
            throw new DBLevelException(e);
        }

        conn.commit();
    } catch (SQLException e) {
        DBUtil.rollback(conn);
        throw new DBLevelException(e);
    } finally {
        DBUtil.setCommitMode(conn, autoCommit);
        DBUtil.close(conn);
    }

    changed = true;

    // notify Factory
    Factory.applicationUserTypeChanged(appName, userType.getName());
}

From source file:org.etudes.jforum.EtudesJForumBaseServlet.java

/**
 * write to database// www . j  a v a 2  s.  co  m
 * 
 * @param conn
 *            connection
 * @param sql
 *            sql
 * @return true if database write is success false if database write fails
 */
private boolean dbWrite(Connection conn, String sql) {
    if (logger.isInfoEnabled())
        if (logger.isDebugEnabled())
            logger.debug("JForum issuing SQL: " + sql);

    PreparedStatement pstmt = null;
    boolean autoCommit = false;
    boolean resetAutoCommit = false;

    boolean success = false;

    try {
        // make sure we do not have auto commit - will change and reset if
        // needed
        autoCommit = conn.getAutoCommit();
        if (autoCommit) {
            conn.setAutoCommit(false);
            resetAutoCommit = true;
        }

        pstmt = conn.prepareStatement(sql);

        pstmt.executeUpdate();

        if (conn != null) {
            conn.commit();
        }

        // indicate success
        success = true;
    } catch (Exception e) {
        //if (logger.isWarnEnabled()) logger.warn(this.getClass().getName()+".dbWrite(): " + e);
        //e.printStackTrace();
        return false;
    } finally {
        try {
            if (null != pstmt)
                pstmt.close();
            if ((conn != null)) {
                // rollback on failure
                if (!success)
                    conn.rollback();

                // reset the autocommit
                if (resetAutoCommit)
                    conn.setAutoCommit(autoCommit);
            }
        } catch (Exception e) {
            if (logger.isWarnEnabled())
                logger.warn(this.getClass().getName() + ".dbWrite(): " + e);
        }
    }
    return true;
}

From source file:org.sakaiproject.assignment.impl.DbAssignmentService.java

/**
 * fill in the context field for any record missing it
 *//*from   w w w  .  j  a va 2s . c om*/
protected void convertToContext() {
    M_log.info(this + " convertToContext");

    try {
        // get a connection
        final Connection connection = m_sqlService.borrowConnection();
        boolean wasCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);

        // read all assignment records
        String sql = "select XML from ASSIGNMENT_ASSIGNMENT where CONTEXT is null";
        m_sqlService.dbRead(connection, sql, null, new SqlReader() {
            public Object readSqlResultRecord(ResultSet result) {
                try {
                    // create the Resource from the db xml
                    String xml = result.getString(1);

                    // read the xml
                    Document doc = Xml.readDocumentFromString(xml);

                    // verify the root element
                    Element root = doc.getDocumentElement();
                    if (!root.getTagName().equals("assignment")) {
                        M_log.warn(this + " convertToContext(): XML root element not assignment: "
                                + root.getTagName());
                        return null;
                    }
                    Assignment a = new BaseAssignment(root);
                    // context is context
                    String context = a.getContext();
                    String id = a.getId();

                    // update
                    String update = "update ASSIGNMENT_ASSIGNMENT set CONTEXT = ? where ASSIGNMENT_ID = ?";
                    Object fields[] = new Object[2];
                    fields[0] = context;
                    fields[1] = id;
                    boolean ok = m_sqlService.dbWrite(connection, update, fields);

                    M_log.info(this + " convertToContext: assignment id: " + id + " context: " + context
                            + " ok: " + ok);

                    return null;
                } catch (SQLException ignore) {
                    M_log.warn(this + ":convertToContext " + ignore.getMessage());
                    return null;
                }
            }
        });

        // read all content records
        sql = "select XML from ASSIGNMENT_CONTENT where CONTEXT is null";
        m_sqlService.dbRead(connection, sql, null, new SqlReader() {
            public Object readSqlResultRecord(ResultSet result) {
                try {
                    // create the Resource from the db xml
                    String xml = result.getString(1);

                    // read the xml
                    Document doc = Xml.readDocumentFromString(xml);

                    // verify the root element
                    Element root = doc.getDocumentElement();
                    if (!root.getTagName().equals("content")) {
                        M_log.warn(this + " convertToContext(): XML root element not content: "
                                + root.getTagName());
                        return null;
                    }
                    AssignmentContent c = new BaseAssignmentContent(root);
                    // context is creator
                    String context = c.getCreator();
                    String id = c.getId();

                    // update
                    String update = "update ASSIGNMENT_CONTENT set CONTEXT = ? where CONTENT_ID = ?";
                    Object fields[] = new Object[2];
                    fields[0] = context;
                    fields[1] = id;
                    boolean ok = m_sqlService.dbWrite(connection, update, fields);

                    M_log.info(this + " convertToContext: content id: " + id + " context: " + context + " ok: "
                            + ok);

                    return null;
                } catch (SQLException ignore) {
                    M_log.warn(this + ":convertToContext SqlReader " + ignore.getMessage());
                    return null;
                }
            }
        });

        // read all submission records
        sql = "select XML from ASSIGNMENT_SUBMISSION where CONTEXT is null";
        m_sqlService.dbRead(connection, sql, null, new SqlReader() {
            public Object readSqlResultRecord(ResultSet result) {
                try {
                    // create the Resource from the db xml
                    String xml = result.getString(1);

                    // read the xml
                    Document doc = Xml.readDocumentFromString(xml);

                    // verify the root element
                    Element root = doc.getDocumentElement();
                    if (!root.getTagName().equals("submission")) {
                        M_log.warn(this + " convertToContext(): XML root element not submission: "
                                + root.getTagName());
                        return null;
                    }
                    AssignmentSubmission s = new BaseAssignmentSubmission(root);
                    // context is assignment id
                    String context = s.getAssignmentId();
                    String id = s.getId();

                    // update
                    String update = "update ASSIGNMENT_SUBMISSION set CONTEXT = ? where SUBMISSION_ID = ?";
                    Object fields[] = new Object[2];
                    fields[0] = context;
                    fields[1] = id;
                    boolean ok = m_sqlService.dbWrite(connection, update, fields);

                    M_log.info(this + " convertToContext: submission id: " + id + " context: " + context
                            + " ok: " + ok);

                    return null;
                } catch (SQLException ignore) {
                    M_log.warn(this + ":convertToContext:SqlReader " + ignore.getMessage());
                    return null;
                }
            }
        });

        connection.commit();
        connection.setAutoCommit(wasCommit);
        m_sqlService.returnConnection(connection);
    } catch (Throwable t) {
        M_log.warn(this + " convertToContext: failed: " + t);
    }

    // TODO:
    M_log.info(this + " convertToContext: done");
}

From source file:eionet.gdem.dcm.conf.DbTest.java

public void tstDbParams(String url, String user, String psw) throws Exception {

    Connection con = null;
    Statement stmt = null;//ww w.java2 s . c  o  m
    ResultSet rset = null;

    try {
        // Class.forName(Properties.dbDriver);
        Class.forName(Properties.dbDriver);

        con = DriverManager.getConnection(url, user, psw);
        stmt = con.createStatement();
        String sql = "SELECT 1";
        rset = stmt.executeQuery(sql);

    } catch (Exception e) {
        LOGGER.debug("Testing database connection failed!", e);
        e.printStackTrace();
        throw new DCMException(BusinessConstants.EXCEPTION_PARAM_DB_TEST_FAILED);
    } finally {
        // Close connection
        if (rset != null) {
            rset.close();
        }
        if (stmt != null) {
            stmt.close();
            if (!con.getAutoCommit()) {
                con.commit();
            }
        }
        if (con != null) {
            con.close();
            con = null;
        }

    }
}

From source file:org.wso2.carbon.identity.application.authenticator.fido.dao.DeviceStoreDAO.java

/**
 * Update registration entry once domain name changed.
 *
 * @param tenantId/*from w w w.  j  ava2s.  co m*/
 * @param currentUserStoreName
 * @param newUserStoreName
 * @throws FIDOAuthenticatorServerException
 */
public void updateDomainNameOfRegistration(int tenantId, String currentUserStoreName, String newUserStoreName)
        throws FIDOAuthenticatorServerException {
    if (log.isDebugEnabled()) {
        log.debug("updateDomainNameOfRegistration inputs {tenantId: " + tenantId + ", currentUserStoreName: "
                + currentUserStoreName + ", newUserStoreName: " + newUserStoreName + "}");
    }
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement preparedStatement = null;

    try {
        preparedStatement = connection
                .prepareStatement(FIDOAuthenticatorConstants.SQLQueries.UPDATE_USER_DOMAIN_NAME);
        preparedStatement.setString(1, newUserStoreName.toUpperCase());
        preparedStatement.setString(2, currentUserStoreName.toUpperCase());
        preparedStatement.setInt(3, tenantId);
        preparedStatement.executeUpdate();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }

    } catch (SQLException e) {
        throw new FIDOAuthenticatorServerException("Error when executing FIDO update domain name SQL : "
                + FIDOAuthenticatorConstants.SQLQueries.UPDATE_USER_DOMAIN_NAME, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, preparedStatement);
    }

}

From source file:org.wso2.carbon.identity.application.authenticator.fido.dao.DeviceStoreDAO.java

/**
 * Remove all registered device from store.
 *
 * @param username// w w  w  .  j a  v a 2s .  com
 * @param tenantDomain
 * @param userStoreDomain
 * @throws FIDOAuthenticatorServerException
 */
public void removeAllRegistrations(String username, String tenantDomain, String userStoreDomain)
        throws FIDOAuthenticatorServerException {

    if (log.isDebugEnabled()) {
        log.debug("removeRegistration inputs {username:" + username + "}");
    }
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement preparedStatement = null;

    try {
        preparedStatement = connection
                .prepareStatement(FIDOAuthenticatorConstants.SQLQueries.REMOVE_ALL_REGISTRATION_QUERY);
        preparedStatement.setInt(1, IdentityTenantUtil.getTenantId(tenantDomain));
        preparedStatement.setString(2, userStoreDomain);
        preparedStatement.setString(3, username);
        preparedStatement.executeUpdate();

        if (!connection.getAutoCommit()) {
            connection.commit();
        }
    } catch (SQLException e) {
        throw new FIDOAuthenticatorServerException("Error executing remove all registrations SQL : "
                + FIDOAuthenticatorConstants.SQLQueries.REMOVE_ALL_REGISTRATION_QUERY, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, preparedStatement);
    }
}

From source file:org.ralasafe.application.ApplicationManagerImpl.java

public void addApplication(Locale locale, Application app) throws EntityExistException {
    loadIntoMemory();/*w w  w .  ja  v a 2s .c om*/

    // Already exist?
    if (store.keySet().contains(app.getName())) {
        throw new EntityExistException("The name '" + app.getName() + "' already exists.");
    }

    Connection conn = null;
    boolean commitMode = true;
    try {
        conn = DBPower.getConnection(table.getId());
        commitMode = conn.getAutoCommit();
        conn.setAutoCommit(false);

        // save application info
        saver.save(conn, app);

        // save usertypes info
        Collection userTypes = app.getUserTypes();
        if (userTypes != null && userTypes.size() > 0) {
            List appUserTypes = new ArrayList(userTypes.size());
            for (Iterator iter = userTypes.iterator(); iter.hasNext();) {
                UserType userType = (UserType) iter.next();

                ApplicationUserType appUserType = new ApplicationUserType();
                appUserType.setAppName(app.getName());
                appUserType.setUserTypeName(userType.getName());
                String produceUserMetadataStr = produceUserMetadataStr(userType.getUserMetadata());
                appUserType.setUserMetadataStr(produceUserMetadataStr);

                appUserTypes.add(appUserType);
            }

            applicationUserTypeSaver.batchSave(conn, appUserTypes);
        }

        conn.commit();
    } catch (SQLException e) {
        DBUtil.rollback(conn);
        throw new DBLevelException(e);
    } finally {
        DBUtil.setCommitMode(conn, commitMode);
        DBUtil.close(conn);
    }

    changed = true;

    // create tables
    createTablesForApp(app);

    Iterator itr = app.getUserTypes().iterator();
    while (itr.hasNext()) {
        UserType userType = (UserType) itr.next();
        // create reserved query
        QueryManager queryManager = Factory.getQueryManager(app.getName());
        queryManager.addReservedQuery(userType.getName());

        // create reserved usercategory
        UserCategoryManager userCategoryManager = Factory.getUserCategoryManager(app.getName());
        userCategoryManager.addReservedUserCategory(locale);

        // create reserved privilege
        PrivilegeManager privilegeManager = Factory.getPrivilegeManager(app.getName());
        privilegeManager.addReservedPrivilege(locale);

        // create reserved roles
        RoleManager roleManager = Factory.getRoleManager(app.getName());
        roleManager.addReservedRole(locale);
    }
}