Example usage for java.sql Connection setAutoCommit

List of usage examples for java.sql Connection setAutoCommit

Introduction

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

Prototype

void setAutoCommit(boolean autoCommit) throws SQLException;

Source Link

Document

Sets this connection's auto-commit mode to the given state.

Usage

From source file:com.gtwm.jasperexecute.RunJasperReports.java

private JasperPrint generateReport(String reportDefinitionFile, DatabaseType dbType, String databaseName,
        String databaseUsername, String databasePassword, String dbHost, Map parameters)
        throws FileNotFoundException, JRException, SQLException, ClassNotFoundException {
    // parse JasperReport XML file
    InputStream input = new FileInputStream(new File(reportDefinitionFile));
    System.out.println("Read input file " + reportDefinitionFile);
    JasperDesign design = JRXmlLoader.load(input);
    JasperReport report = JasperCompileManager.compileReport(design);
    System.out.println("Compiled report from file " + reportDefinitionFile);
    // connect to db
    Class.forName(dbType.getDriverName());
    String connectionStatement = dbType.getProtocolUrl() + dbHost + dbType.getSeparator() + databaseName;
    System.out.println("About to connect to database using connection string " + connectionStatement);
    Properties connectionProperties = new Properties();
    if (databaseUsername != null) {
        connectionProperties.setProperty("user", databaseUsername);
    }// ww w  .ja  v a2 s .c  om
    if (databasePassword != null) {
        connectionProperties.setProperty("password", databasePassword);
    }
    if (dbType.equals(DatabaseType.FIREBIRD)) {
        // See issue http://www.firebirdfaq.org/faq320/
        connectionProperties.setProperty("charSet", "UTF-8");
        connectionProperties.setProperty("encoding", "UTF8");
    }
    Connection conn = DriverManager.getConnection(connectionStatement, connectionProperties);
    // Connection conn = DriverManager.getConnection(connectionStatement,
    // databaseUsername,
    // databasePassword);
    System.out.println("Connected to database " + databaseName);
    conn.setAutoCommit(false);
    // run report and write output
    JasperPrint print = JasperFillManager.fillReport(report, parameters, conn);
    System.out.println("Composed report output");
    conn.close();
    return print;
}

From source file:com.opengamma.util.db.management.AbstractDbManagement.java

protected Connection connect(String catalog) throws SQLException {
    Connection conn = DriverManager.getConnection(getCatalogToConnectTo(catalog), _user, _password);
    conn.setAutoCommit(true);
    return conn;/*w  w  w .  ja v  a 2  s . com*/
}

From source file:dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldValueDBDAO.java

/**
 * Read a ExtendedFieldValue in persistent storage.
 * @param aConnection an open connection to the HarvestDatabase
 * @param aExtendedFieldValue The ExtendedFieldValue to update
 * @param aCommit Should we commit this or not
 * @throws SQLException In case of database problems.
 */// w w w.  ja v a 2 s  .  co m
public void update(Connection aConnection, ExtendedFieldValue aExtendedFieldValue, boolean aCommit)
        throws SQLException {
    PreparedStatement statement = null;
    final Long extendedfieldvalueId = aExtendedFieldValue.getExtendedFieldID();
    if (!exists(aConnection, extendedfieldvalueId)) {
        throw new UnknownID(
                "Extended Field Value id " + extendedfieldvalueId + " is not known in persistent storage");
    }

    aConnection.setAutoCommit(false);

    statement = aConnection.prepareStatement(
            "" + "UPDATE extendedfieldvalue " + "SET    extendedfield_id = ?, " + "       instance_id = ?, "
                    + "       content = ? " + "WHERE  extendedfieldvalue_id = ? and instance_id = ?");

    statement.setLong(1, aExtendedFieldValue.getExtendedFieldID());
    statement.setLong(2, aExtendedFieldValue.getInstanceID());
    statement.setString(3, aExtendedFieldValue.getContent());
    statement.setLong(4, aExtendedFieldValue.getExtendedFieldValueID());
    statement.setLong(5, aExtendedFieldValue.getInstanceID());

    statement.executeUpdate();

    if (aCommit) {
        aConnection.commit();
    }
}

From source file:eionet.cr.dao.virtuoso.VirtuosoFolderDAO.java

@Override
public void createUserHomeFolder(String userName) throws DAOException {

    if (StringUtils.isBlank(userName)) {
        throw new IllegalArgumentException("User name must not be blank!");
    }/*from  ww  w  .  j  av a  2  s .c o m*/
    CRUser user = new CRUser(userName);

    Connection sqlConn = null;
    RepositoryConnection repoConn = null;
    try {
        sqlConn = SesameUtil.getSQLConnection();
        sqlConn.setAutoCommit(false);

        repoConn = SesameUtil.getRepositoryConnection();
        repoConn.setAutoCommit(false);
        ValueFactory vf = repoConn.getValueFactory();

        List<Statement> statements = getHomeFolderCreationStatements(user, vf);
        repoConn.add(statements);

        createNeverHarvestedSources(sqlConn, statements);

        repoConn.commit();
        sqlConn.commit();

    } catch (OpenRDFException e) {
        SesameUtil.rollback(repoConn);
        throw new DAOException(e.getMessage(), e);
    } catch (SQLException e) {
        SQLUtil.rollback(sqlConn);
        throw new DAOException(e.getMessage(), e);
    } finally {
        SQLUtil.close(sqlConn);
        SesameUtil.close(repoConn);
    }
}

From source file:com.cws.esolutions.security.dao.reference.impl.SecurityReferenceDAOImpl.java

/**
 * @see com.cws.esolutions.security.dao.reference.interfaces.ISecurityReferenceDAO#listAvailableServices()
 *//*  w  ww  . j a v  a2s  .co  m*/
public synchronized Map<String, String> listAvailableServices() throws SQLException {
    final String methodName = ISecurityReferenceDAO.CNAME + "#listAvailableServices() throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    Map<String, String> serviceMap = null;

    try {
        sqlConn = dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);
        stmt = sqlConn.prepareCall("{CALL retrAvailableServices()}");

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        if (stmt.execute()) {
            resultSet = stmt.getResultSet();

            if (DEBUG) {
                DEBUGGER.debug("ResultSet: {}", resultSet);
            }

            if (resultSet.next()) {
                resultSet.beforeFirst();
                serviceMap = new HashMap<String, String>();

                while (resultSet.next()) {
                    serviceMap.put(resultSet.getString(1), resultSet.getString(2));
                }

                if (DEBUG) {
                    DEBUGGER.debug("Map<String, String>: {}", serviceMap);
                }
            }
        }
    } catch (SQLException sqx) {
        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }

        if (stmt != null) {
            stmt.close();
        }

        if ((sqlConn != null) && (!(sqlConn.isClosed()))) {
            sqlConn.close();
        }
    }

    return serviceMap;
}

From source file:gridool.db.sql.ParallelSQLMapTask.java

@Override
protected ParallelSQLMapTaskResult execute() throws GridException {
    assert (registry != null);

    final File tmpFile;
    try {// w ww. j  a  v  a  2  s. c  o m
        tmpFile = File.createTempFile("PSQLMap" + taskNumber + '_', '_' + NetUtils.getLocalHostAddress());
    } catch (IOException e) {
        throw new GridException(e);
    }

    final QueryString[] queries = SQLTranslator.divideQuery(query, true);
    final boolean singleStatement = (queries.length == 1);
    final String selectQuery = singleStatement ? query : SQLTranslator.selectFirstSelectQuery(queries);

    GridNode localNode = config.getLocalNode();
    GridNode senderNode = getSenderNode();
    assert (senderNode != null);
    final boolean useCreateTableAS = senderNode.equals(localNode);

    final int fetchedRows;
    final LockManager lockMgr = registry.getLockManager();
    final ReadWriteLock rwlock = lockMgr.obtainLock(DBAccessor.SYS_TABLE_SYMBOL);
    final Lock lock = rwlock.writeLock(); // REVIEWME tips: exclusive lock for system table in MonetDB
    long startQueryTime = System.currentTimeMillis();
    final Connection dbConn = getDbConnection(taskMasterNode, registry);
    try {
        lock.lock();
        if (singleStatement) {
            // #1 invoke COPY INTO file
            if (useCreateTableAS) {
                dbConn.setAutoCommit(true);
                fetchedRows = executeCreateTableAs(dbConn, selectQuery, taskTableName);
            } else {
                dbConn.setAutoCommit(false);
                fetchedRows = executeCopyIntoFile(dbConn, selectQuery, taskTableName, tmpFile);
                dbConn.commit();
            }
        } else {
            dbConn.setAutoCommit(false);
            // #1-1 DDL before map SELECT queries (e.g., create view)
            issueDDLBeforeSelect(dbConn, queries);
            // #1-2 invoke COPY INTO file
            if (useCreateTableAS) {
                fetchedRows = executeCreateTableAs(dbConn, selectQuery, taskTableName);
            } else {
                fetchedRows = executeCopyIntoFile(dbConn, selectQuery, taskTableName, tmpFile);
            }
            // #1-3 DDL after map SELECT queries (e.g., drop view)
            issueDDLAfterSelect(dbConn, queries);
            dbConn.commit();
        }
        assert (fetchedRows != -1);
    } catch (SQLException sqle) {
        String errmsg = "Failed to execute a query: \n" + query;
        LOG.error(errmsg, sqle);
        if (singleStatement) {
            try {
                dbConn.rollback();
            } catch (SQLException rbe) {
                LOG.warn("Rollback failed", rbe);
            }
        }
        new FileDeletionThread(tmpFile, LOG).start();
        throw new GridException(errmsg, sqle);
    } catch (Throwable e) {
        String errmsg = "Failed to execute a query: \n" + query;
        LOG.fatal(errmsg, e);
        if (singleStatement) {
            try {
                dbConn.rollback();
            } catch (SQLException rbe) {
                LOG.warn("Rollback failed", rbe);
            }
        }
        new FileDeletionThread(tmpFile, LOG).start();
        throw new GridException(errmsg, e);
    } finally {
        lock.unlock();
        JDBCUtils.closeQuietly(dbConn);
    }
    long queryExecTime = System.currentTimeMillis() - startQueryTime;

    String sentFileName = null;
    long sendResultTime = -1L; // would be null for a local task
    if (fetchedRows > 0) {
        // #2 send file
        long startResultTime = System.currentTimeMillis();
        try {
            TransferUtils.sendfile(tmpFile, dstAddr, dstPort, false, true);
            sendResultTime = System.currentTimeMillis() - startResultTime;
            sentFileName = tmpFile.getName();
        } catch (IOException e) {
            throw new GridException("failed to sending a file", e);
        } finally {
            new FileDeletionThread(tmpFile, LOG).start();
        }
    }
    return new ParallelSQLMapTaskResult(taskMasterNode, sentFileName, taskNumber, fetchedRows, queryExecTime,
            sendResultTime);
}

From source file:com.cws.esolutions.security.dao.reference.impl.SecurityReferenceDAOImpl.java

/**
 * @see com.cws.esolutions.security.dao.reference.interfaces.ISecurityReferenceDAO#obtainApprovedServers()
 *//*from   w w  w.j  a  v  a  2 s.  co  m*/
public synchronized List<String> obtainApprovedServers() throws SQLException {
    final String methodName = ISecurityReferenceDAO.CNAME + "#obtainApprovedServers() throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<String> securityList = null;

    try {
        sqlConn = dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);
        stmt = sqlConn.prepareCall("{CALL retrApprovedServers()}");

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        if (stmt.execute()) {
            resultSet = stmt.getResultSet();

            if (DEBUG) {
                DEBUGGER.debug("ResultSet: {}", resultSet);
            }

            if (resultSet.next()) {
                resultSet.beforeFirst();

                securityList = new ArrayList<String>();

                while (resultSet.next()) {
                    if (DEBUG) {
                        DEBUGGER.debug(resultSet.getString(1));
                    }

                    // check if column is null
                    securityList.add(resultSet.getString(1));
                }

                if (DEBUG) {
                    DEBUGGER.debug("securityList: {}", securityList);
                }
            }
        }
    } catch (SQLException sqx) {
        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }

        if (stmt != null) {
            stmt.close();
        }

        if ((sqlConn != null) && (!(sqlConn.isClosed()))) {
            sqlConn.close();
        }
    }

    return securityList;
}

From source file:com.cws.esolutions.security.dao.reference.impl.SecurityReferenceDAOImpl.java

/**
 * @see com.cws.esolutions.security.dao.reference.interfaces.ISecurityReferenceDAO#obtainSecurityQuestionList()
 *//* ww w. j  a  va2 s . c  o  m*/
public synchronized List<String> obtainSecurityQuestionList() throws SQLException {
    final String methodName = ISecurityReferenceDAO.CNAME + "#obtainSecurityQuestionList() throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<String> questionList = null;

    try {
        sqlConn = dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);
        stmt = sqlConn.prepareCall("{CALL retrieve_user_questions()}");

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        if (stmt.execute()) {
            resultSet = stmt.getResultSet();
            resultSet.last();
            int iRowCount = resultSet.getRow();

            if (iRowCount == 0) {
                throw new SQLException("No security questions are currently configured.");
            }

            resultSet.first();
            ResultSetMetaData resultData = resultSet.getMetaData();

            int iColumns = resultData.getColumnCount();

            questionList = new ArrayList<String>();

            for (int x = 1; x < iColumns + 1; x++) {
                if (DEBUG) {
                    DEBUGGER.debug("resultSet.getObject: {}", resultSet.getObject(resultData.getColumnName(x)));
                }

                // check if column is null
                resultSet.getObject(resultData.getColumnName(x));

                // if the column was null, insert n/a, otherwise, insert the column's contents
                questionList.add((String) (resultSet.wasNull() ? "N/A"
                        : resultSet.getObject(resultData.getColumnName(x))));
            }
        }
    } catch (SQLException sqx) {
        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }

        if (stmt != null) {
            stmt.close();
        }

        if ((sqlConn != null) && (!(sqlConn.isClosed()))) {
            sqlConn.close();
        }
    }

    return questionList;
}

From source file:com.cws.esolutions.security.dao.userauth.impl.SQLAuthenticator.java

/**
 * @see com.cws.esolutions.security.dao.userauth.interfaces.Authenticator#obtainOtpSecret(java.lang.String, java.lang.String)
 *//*from w  w w  .j a  v  a  2  s .c om*/
public synchronized String obtainOtpSecret(final String userName, final String userGuid)
        throws AuthenticatorException {
    final String methodName = SQLAuthenticator.CNAME
            + "#obtainOtpSecret(final String userName, final String userGuid) throws AuthenticatorException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", userName);
        DEBUGGER.debug("Value: {}", userGuid);
    }

    String otpSecret = null;
    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;

    try {
        sqlConn = SQLAuthenticator.dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);

        stmt = sqlConn.prepareCall("{CALL getOtpSecret(?, ?)}");
        stmt.setString(1, userGuid); // guid
        stmt.setString(2, userName);

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        if (stmt.execute()) {
            resultSet = stmt.getResultSet();

            if (DEBUG) {
                DEBUGGER.debug("ResultSet: {}", resultSet);
            }

            if (resultSet.next()) {
                resultSet.first();

                otpSecret = resultSet.getString(1);
            }
        }
    } catch (SQLException sqx) {
        throw new AuthenticatorException(sqx.getMessage(), sqx);
    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
            }

            if (stmt != null) {
                stmt.close();
            }

            if (!(sqlConn == null) && (!(sqlConn.isClosed()))) {
                sqlConn.close();
            }
        } catch (SQLException sqx) {
            throw new AuthenticatorException(sqx.getMessage(), sqx);
        }
    }

    return otpSecret;
}

From source file:com.amazon.carbonado.repo.jdbc.JDBCRepository.java

/**
 * Any connection returned by this method must be closed by calling
 * yieldConnection on this repository.//from ww  w .  ja v a  2s . co  m
 */
public Connection getConnection() throws FetchException {
    try {
        if (mOpenConnections == null) {
            throw new FetchException("Repository is closed");
        }

        JDBCTransaction txn = localTransactionScope().getTxn();
        if (txn != null) {
            // Return the connection used by the current transaction.
            return txn.getConnection();
        }

        // Get connection outside lock section since it may block.
        Connection con = mDataSource.getConnection();
        con.setAutoCommit(true);

        mOpenConnectionsLock.lock();
        try {
            if (mOpenConnections == null) {
                con.close();
                throw new FetchException("Repository is closed");
            }
            mOpenConnections.put(con, null);
        } finally {
            mOpenConnectionsLock.unlock();
        }

        return con;
    } catch (Exception e) {
        throw toFetchException(e);
    }
}