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.wso2.carbon.apimgt.impl.dao.CertificateMgtDAO.java

/**
 * Method to add a new certificate to the database.
 *
 * @param alias    : Alias for the new certificate.
 * @param endpoint : The endpoint/ server url which the certificate will be mapped to.
 * @param tenantId : The Id of the tenant who uploaded the certificate.
 * @return : True if the information is added successfully, false otherwise.
 * @throws CertificateManagementException if existing entry is found for the given endpoint or alias.
 *//*w w w  .  java  2 s.c  o  m*/
public boolean addCertificate(String alias, String endpoint, int tenantId)
        throws CertificateManagementException, CertificateAliasExistsException {

    boolean result = false;
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    String addCertQuery = SQLConstants.CertificateConstants.INSERT_CERTIFICATE;

    //Check whether any certificate is uploaded for the same alias or endpoint by another user/ tenant.
    CertificateMetadataDTO existingCertificate = getCertificate(alias);

    if (existingCertificate != null) {
        if (log.isDebugEnabled()) {
            log.debug("A certificate for the endpoint " + endpoint + " has already added with alias "
                    + existingCertificate.getAlias());
        }
        String message = "Alias or Endpoint exists in the database!";
        if (existingCertificate.getAlias().equals(alias)) {
            throw new CertificateAliasExistsException(message);
        }
    }

    try {
        connection = APIMgtDBUtil.getConnection();
        initialAutoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        preparedStatement = connection.prepareStatement(addCertQuery);
        preparedStatement.setInt(1, tenantId);
        preparedStatement.setString(2, endpoint);
        preparedStatement.setString(3, alias);
        result = preparedStatement.executeUpdate() == 1;
        connection.commit();
    } catch (SQLException e) {
        handleConnectionRollBack(connection);
        if (log.isDebugEnabled()) {
            log.debug("Error occurred while adding certificate metadata to database.", e);
        }
        handleException("Error while persisting certificate metadata.", e);
    } finally {
        APIMgtDBUtil.setAutoCommit(connection, initialAutoCommit);
        APIMgtDBUtil.closeAllConnections(preparedStatement, connection, null);
    }
    return result;
}

From source file:com.egt.core.db.xdp.RecursoCachedRowSet.java

@Override
public void setCommand(String command) throws SQLException {
    boolean autoCommit;
    Bitacora.trace(getClass(), "setCommand", command);
    Connection connection = getConnection();
    Bitacora.trace("connection=" + connection);
    if (connection != null) {
        autoCommit = connection.getAutoCommit();
        Bitacora.trace("autocommit=" + autoCommit);
        if (autoCommit) {
            connection.setAutoCommit(false);
            autoCommit = connection.getAutoCommit();
            Bitacora.trace("autocommit=" + autoCommit);
        }/*from   w  ww .j  a  va2 s  .  c o m*/
    }
    super.setCommand(command);
}

From source file:org.sakaiproject.citation.impl.DbCitationService.java

/**
 * Determine auto-commit state// w w w.  j  a  v a  2s.c o  m
 * @param conn Database Connection
 * @return The original connection auto-commit state
 */
private int getAutoCommit(Connection conn) {
    try {
        boolean wasCommit = conn.getAutoCommit();

        return wasCommit ? AUTO_TRUE : AUTO_FALSE;
    } catch (SQLException exception) {
        M_log.warn("restoreAutoCommit: " + exception);
        return AUTO_UNKNOWN;
    }
}

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

/**
 * Method to retrieve certificate metadata from db for specific tenant which matches alias or endpoint.
 * From alias and endpoint, only one parameter is required.
 *
 * @param tenantId : The id of the tenant which the certificate belongs to.
 * @param alias    : Alias for the certificate. (Optional)
 * @param endpoint : The endpoint/ server url which the certificate is mapped to. (Optional)
 * @return : A CertificateMetadataDTO object if the certificate is retrieved successfully, null otherwise.
 *///  www . j  a  v  a  2s.c  o  m
public List<CertificateMetadataDTO> getCertificates(String alias, String endpoint, int tenantId)
        throws CertificateManagementException {

    Connection connection = null;
    String getCertQuery;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    CertificateMetadataDTO certificateMetadataDTO;
    List<CertificateMetadataDTO> certificateMetadataList = new ArrayList<>();

    if (StringUtils.isNotEmpty(alias) || StringUtils.isNotEmpty(endpoint)) {
        if (log.isDebugEnabled()) {
            log.debug("The alias and endpoint are not empty. Invoking the search query with parameters "
                    + "alias = " + alias + " endpoint = " + endpoint);
        }
        getCertQuery = SQLConstants.CertificateConstants.GET_CERTIFICATE_TENANT;
    } else {
        if (log.isDebugEnabled()) {
            log.debug("The alias and endpoint are empty. Invoking the get all certificates for tenant "
                    + tenantId);
        }
        getCertQuery = SQLConstants.CertificateConstants.GET_CERTIFICATES;
    }

    try {
        connection = APIMgtDBUtil.getConnection();
        initialAutoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        connection.commit();
        preparedStatement = connection.prepareStatement(getCertQuery);
        preparedStatement.setInt(1, tenantId);

        if (StringUtils.isNotEmpty(alias) || StringUtils.isNotEmpty(endpoint)) {
            preparedStatement.setString(2, alias);
            preparedStatement.setString(3, endpoint);
        }
        resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) {
            certificateMetadataDTO = new CertificateMetadataDTO();
            certificateMetadataDTO.setAlias(resultSet.getString("ALIAS"));
            certificateMetadataDTO.setEndpoint(resultSet.getString("END_POINT"));
            certificateMetadataList.add(certificateMetadataDTO);
        }
    } catch (SQLException e) {
        handleException("Error while retrieving certificate metadata.", e);
    } finally {
        APIMgtDBUtil.setAutoCommit(connection, initialAutoCommit);
        APIMgtDBUtil.closeAllConnections(preparedStatement, connection, resultSet);
    }
    return certificateMetadataList;
}

From source file:org.sakaiproject.lessonbuildertool.model.SimplePageToolDaoImpl.java

public int clearNeedsFixup(String siteId) {
    Object[] fields = new Object[1];
    fields[0] = siteId;//ww  w  . ja  v a 2  s  .com

    List<String> needsList = sqlService.dbRead(
            "select VALUE from SAKAI_SITE_PROPERTY where SITE_ID=? and NAME='lessonbuilder-needsfixup'", fields,
            null);

    // normal case -- no flag
    if (needsList == null || needsList.size() == 0) {
        return 0;
    }

    // there is a flag, do something more carefully avoiding race conditions
    //   There is a possible timing issue if someone copies data into the site after the
    // last test. If so, we'll get it next time someone uses the site.
    // we need to be provably sure that if the flag is set, this code returns 1 exactly once.
    // I believe that is the case.

    int retval = 0;
    Connection conn = null;
    boolean wasCommit = true;

    try {
        conn = sqlService.borrowConnection();
        needsList = sqlService.dbRead(conn,
                "select VALUE from SAKAI_SITE_PROPERTY where SITE_ID=? and NAME='lessonbuilder-needsfixup' for update",
                fields, null);
        wasCommit = conn.getAutoCommit();
        conn.setAutoCommit(false);

        if (needsList != null && needsList.size() > 0) {
            retval = 1;
            try {
                retval = Integer.parseInt(needsList.get(0));
            } catch (Exception ignore) {
            }
            sqlService.dbWrite(conn,
                    "delete from SAKAI_SITE_PROPERTY where SITE_ID=? and NAME='lessonbuilder-needsfixup'",
                    fields);
        }

        conn.commit();

        // I don't think we need to handle errrors explicitly. They will result in
        // returning 0, which is about the best we can do
    } catch (Exception e) {
    } finally {

        if (conn != null) {

            try {
                conn.setAutoCommit(wasCommit);
            } catch (Exception e) {
                System.out.println("transact: (setAutoCommit): " + e);
            }

            sqlService.returnConnection(conn);
        }

    }

    return retval;

}

From source file:localdomain.localhost.CasInitializer.java

@Override
public void afterPropertiesSet() throws Exception {
    System.err.println(/* ww  w  . j  av a2  s.c om*/
            "##############################################################################################");
    System.err.println(
            "##############################################################################################");
    System.err.println(
            "#                                                                                            #");
    System.err.println(
            "# CLOUDBEES JASIG CAS SSO SERVER CLICKSTART                                                  #");
    System.err.println(
            "#                                                                                            #");
    System.err.println(
            "# See documentation at https://github.com/CloudBees-community/jasig-cas-clickstart/wiki      #");
    System.err.println(
            "#                                                                                            #");
    System.err.println(
            "##############################################################################################");
    System.err.println(
            "##############################################################################################");

    try {
        authenticationHandler = applicationContext.getBean(SearchModeSearchDatabaseAuthenticationHandler.class);
    } catch (NoSuchBeanDefinitionException e) {
        String msg = "No Spring bean of type " + SearchModeSearchDatabaseAuthenticationHandler.class
                + " found, initializer can not run";
        logger.warn(msg);
        throw new IllegalStateException(msg, e);
    }

    dataSource = (DataSource) ReflectionUtils.getField(dataSourceField, authenticationHandler);
    fieldUser = (String) ReflectionUtils.getField(fieldUserField, authenticationHandler);
    fieldPassword = (String) ReflectionUtils.getField(fieldPasswordField, authenticationHandler);
    tableUsers = (String) ReflectionUtils.getField(tableUsersField, authenticationHandler);
    passwordEncoder = (PasswordEncoder) ReflectionUtils.getField(passwordEncoderField, authenticationHandler);

    final Connection cnn = dataSource.getConnection();
    Statement stmt = null;
    ResultSet rst = null;

    try {
        logger.info("Create table " + tableUsers + " if not exist");
        stmt = cnn.createStatement();
        String createTableDdl = "CREATE TABLE IF NOT EXISTS `" + tableUsers + "` (" + " `" + fieldUser
                + "` varchar(255) DEFAULT NULL,\n" + " `" + fieldPassword + "` varchar(255) DEFAULT NULL,\n"
                + " PRIMARY KEY (`" + fieldUser + "`)\n" + ")";
        stmt.execute(createTableDdl);
        closeQuietly(stmt);

        logger.info("Validate table columns");
        stmt = cnn.createStatement();
        String sqlCheckDatabaseTable = "select `" + fieldUser + "`,`" + fieldPassword + "`" + " from `"
                + tableUsers + "` where 0=1";
        try {
            stmt.execute(sqlCheckDatabaseTable);
        } catch (SQLException e) {
            throw new IllegalStateException("Invalid table structure:" + sqlCheckDatabaseTable, e);
        }
        closeQuietly(stmt);

        stmt = cnn.createStatement();
        String sqlCountUsers = "select count(*) from `" + tableUsers + "`";
        rst = stmt.executeQuery(sqlCountUsers);
        rst.next();
        int usersCount = rst.getInt(1);
        closeQuietly(stmt, rst);

        if (usersCount == 0) {
            insertUser("demo", "mode", cnn);
        }

        if (!cnn.getAutoCommit()) {
            cnn.commit();
        }
        logger.info("CAS CLICKSTART INITIALIZED");

    } finally {
        closeQuietly(cnn, stmt, rst);
    }

}

From source file:org.sakaiproject.genericdao.springjdbc.JdbcGenericDao.java

/**
 * This will do a commit on the current DB Connection on this thread,
 * allows the developer to force a commit immediately <br/>
 * Remember to close your connection if you are completely done with it
 * //from  w  w w .ja v a 2 s.c  o  m
 * @return true if it committed successfully
 */
public boolean commitTransaction() {
    boolean success = false;
    Connection conn = getConnection();
    boolean previousAutocommit = false;
    try {
        previousAutocommit = conn.getAutoCommit();
        conn.commit();
        conn.setAutoCommit(previousAutocommit);
        success = true;
    } catch (SQLException e) {
        logWarn("Could not commit sucessfully: " + e.getMessage());
        success = false;
        try {
            conn.setAutoCommit(previousAutocommit);
        } catch (SQLException e1) {
            // nothing to do here but continue
        }
    }
    // removed: try-finally-releaseConnection(conn);
    return success;
}

From source file:org.sakaiproject.genericdao.springjdbc.JdbcGenericDao.java

/**
 * This will do a rollback on the DB Connection on this thread,
 * allows the developer to force an immediate rollback <br/>
 * Remember to close your connection if you are completely done with it
 * //from  w w w .  j  a  v a  2 s  .c o m
 * @return true if the rollback executed successfully
 */
public boolean rollbackTransaction() {
    boolean success = false;
    Connection conn = getConnection();
    boolean previousAutocommit = false;
    try {
        previousAutocommit = conn.getAutoCommit();
        conn.rollback();
        conn.setAutoCommit(previousAutocommit);
        success = true;
    } catch (SQLException e) {
        logWarn("Could not rollback sucessfully: " + e.getMessage());
        success = false;
        try {
            conn.setAutoCommit(previousAutocommit);
        } catch (SQLException e1) {
            // nothing to do here but continue
        }
    }
    // removed: try-finally-releaseConnection(conn);
    return success;
}

From source file:com.frameworkset.commons.dbcp2.datasources.PerUserPoolDataSource.java

@Override
protected void setupDefaults(Connection con, String username) throws SQLException {
    Boolean defaultAutoCommit = isDefaultAutoCommit();
    if (username != null) {
        Boolean userMax = getPerUserDefaultAutoCommit(username);
        if (userMax != null) {
            defaultAutoCommit = userMax;
        }/*ww w.  ja v  a2  s . c  o m*/
    }

    Boolean defaultReadOnly = isDefaultReadOnly();
    if (username != null) {
        Boolean userMax = getPerUserDefaultReadOnly(username);
        if (userMax != null) {
            defaultReadOnly = userMax;
        }
    }

    int defaultTransactionIsolation = getDefaultTransactionIsolation();
    if (username != null) {
        Integer userMax = getPerUserDefaultTransactionIsolation(username);
        if (userMax != null) {
            defaultTransactionIsolation = userMax.intValue();
        }
    }

    if (defaultAutoCommit != null && con.getAutoCommit() != defaultAutoCommit.booleanValue()) {
        con.setAutoCommit(defaultAutoCommit.booleanValue());
    }

    if (defaultTransactionIsolation != UNKNOWN_TRANSACTIONISOLATION) {
        con.setTransactionIsolation(defaultTransactionIsolation);
    }

    if (defaultReadOnly != null && con.isReadOnly() != defaultReadOnly.booleanValue()) {
        con.setReadOnly(defaultReadOnly.booleanValue());
    }
}