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.sakaiproject.db.impl.BasicSqlService.java

/**
 * Read a single field from the db, from a single record, return the value found, and lock for update.
 * //from w w  w  . ja v a2s .c  o  m
 * @param sql
 *        The sql statement.
 * @param field
 *        A StringBuilder that will be filled with the field.
 * @return The Connection holding the lock.
 */
public Connection dbReadLock(String sql, StringBuilder field) {
    // Note: does not support TRANSACTION_CONNECTION -ggolden

    if (LOG.isDebugEnabled()) {
        LOG.debug("dbReadLock(String " + sql + ", StringBuilder " + field + ")");
    }

    Connection conn = null;
    Statement stmt = null;
    ResultSet result = null;
    boolean autoCommit = false;
    boolean resetAutoCommit = false;
    boolean closeConn = false;

    try {
        // get a new connection
        conn = borrowConnection();

        // adjust to turn off auto commit - we need a transaction
        autoCommit = conn.getAutoCommit();
        if (autoCommit) {
            conn.setAutoCommit(false);
            resetAutoCommit = true;
        }

        if (LOG.isDebugEnabled())
            LOG.debug("Sql.dbReadLock():\n" + sql);

        // create a statement and execute
        stmt = conn.createStatement();
        result = stmt.executeQuery(sql);

        // if we have a result record
        if (result.next()) {
            // get the result and pack into the return buffer
            String rv = result.getString(1);
            if ((field != null) && (rv != null))
                field.append(rv);
        }

        // otherwise we fail
        else {
            closeConn = true;
        }
    }

    // this is likely the error when the record is otherwise locked - we fail
    catch (SQLException e) {
        // Note: ORA-00054 gives an e.getErrorCode() of 54, if anyone cares...
        LOG.warn("Sql.dbUpdateLock(): " + e.getErrorCode() + " - " + e);
        closeConn = true;
    } finally {
        // close the result and statement
        if (result != null) {
            try {
                result.close();
            } catch (SQLException e) {
                LOG.warn("Sql.dbReadBinary(): " + e);
            }
        }
        if (null != stmt) {
            try {
                stmt.close();
            } catch (SQLException e) {
                LOG.warn("Sql.dbReadBinary(): " + e);
            }
        }

        // if we are failing, restore and release the connection
        if ((closeConn) && (conn != null)) {
            // just in case we got a lock
            try {
                conn.rollback();
            } catch (SQLException e) {
                LOG.warn("Sql.dbReadBinary(): " + e);
            }
            if (resetAutoCommit)
                try {
                    conn.setAutoCommit(autoCommit);
                } catch (SQLException e) {
                    LOG.warn("Sql.dbReadBinary(): " + e);
                }

        }

        if (conn != null) {
            returnConnection(conn);
        }
    }

    return conn;
}

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

/**
 * Read a single field from the db, from a single record, return the value found, and lock for update.
 * /*from w  w  w . j a  v a  2 s  .  co  m*/
 * @param sql
 *        The sql statement.
 * @param reader
 *        A SqlReader that buils the result.
 * @return The Connection holding the lock.
 */
public Connection dbReadLock(String sql, SqlReader reader) {
    // Note: does not support TRANSACTION_CONNECTION -ggolden

    if (LOG.isDebugEnabled()) {
        LOG.debug("dbReadLock(String " + sql + ")");
    }

    Connection conn = null;
    Statement stmt = null;
    ResultSet result = null;
    boolean autoCommit = false;
    boolean resetAutoCommit = false;
    boolean closeConn = false;

    try {
        // get a new conncetion
        conn = borrowConnection();

        // adjust to turn off auto commit - we need a transaction
        autoCommit = conn.getAutoCommit();
        if (autoCommit) {
            conn.setAutoCommit(false);
            resetAutoCommit = true;
        }

        if (LOG.isDebugEnabled())
            LOG.debug("Sql.dbReadLock():\n" + sql);

        // create a statement and execute
        stmt = conn.createStatement();
        result = stmt.executeQuery(sql);

        // if we have a result record
        if (result.next()) {
            reader.readSqlResultRecord(result);
        }

        // otherwise we fail
        else {
            closeConn = true;
        }
    }

    // this is likely the error when the record is otherwise locked - we fail
    catch (SQLException e) {
        // Note: ORA-00054 gives an e.getErrorCode() of 54, if anyone cares...
        // LOG.warn("Sql.dbUpdateLock(): " + e.getErrorCode() + " - " + e);
        closeConn = true;
    } catch (SqlReaderFinishedException e) {
        LOG.warn("Sql.dbReadLock(): " + e);
        closeConn = true;
    }

    finally {
        // close the result and statement
        if (null != result) {
            try {
                result.close();
            } catch (SQLException e) {
                LOG.warn("Sql.dbReadBinary(): " + e);
            }
        }
        if (null != stmt) {
            try {
                stmt.close();
            } catch (SQLException e) {
                LOG.warn("Sql.dbReadBinary(): " + e);
            }
        }

        // if we are failing, restore and release the connectoin
        if ((closeConn) && (conn != null)) {
            // just in case we got a lock
            try {
                conn.rollback();
            } catch (SQLException e) {
                LOG.warn("Sql.dbReadBinary(): " + e);
            }
            if (resetAutoCommit)
                try {
                    conn.setAutoCommit(autoCommit);
                } catch (SQLException e) {
                    LOG.warn("Sql.dbReadBinary(): " + e);
                }

        }
        //   LOG.warn("Sql.dbReadLock(): " + e);

        if (conn != null) {
            returnConnection(conn);
        }
    }

    return conn;
}

From source file:org.apache.cocoon.acting.DatabaseAuthenticatorAction.java

/**
 * Main invocation routine.//from  w  ww. ja v  a  2 s . c om
 */
public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String src,
        Parameters parameters) throws Exception {
    DataSourceComponent datasource = null;
    Connection conn = null;
    PreparedStatement st = null;
    ResultSet rs = null;

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

    if (this.settings.containsKey("reloadable")) {
        reloadable = Boolean.valueOf((String) this.settings.get("reloadable")).booleanValue();
    }

    // read local settings
    try {
        Configuration conf = this.getConfiguration(
                parameters.getParameter("descriptor", (String) this.settings.get("descriptor")), resolver,
                parameters.getParameterAsBoolean("reloadable", reloadable));
        boolean cs = true;
        String create_session = parameters.getParameter("create-session",
                (String) this.settings.get("create-session"));
        if (create_session != null) {
            cs = BooleanUtils.toBoolean(create_session.trim());
        }

        datasource = this.getDataSource(conf);
        conn = datasource.getConnection();
        Request req = ObjectModelHelper.getRequest(objectModel);

        /* check request validity */
        if (req == null) {
            getLogger().debug("DBAUTH: no request object");
            return null;
        }

        st = this.getAuthQuery(conn, conf, req);
        if (st == null) {
            getLogger().debug("DBAUTH: have not got query");
            req.setAttribute("message", "The authenticator is misconfigured");
            return null;
        }

        rs = st.executeQuery();

        if (rs.next()) {
            getLogger().debug("DBAUTH: authorized successfully");
            Session session = null;

            if (cs) {
                session = req.getSession(false);
                if (session != null)
                    session.invalidate();
                session = req.getSession(true);
                if (session == null)
                    return null;
                getLogger().debug("DBAUTH: session created");
            } else {
                getLogger().debug("DBAUTH: leaving session untouched");
            }

            HashMap actionMap = this.propagateParameters(conf, rs, session);
            if (!conn.getAutoCommit()) {
                conn.commit();
            }
            return Collections.unmodifiableMap(actionMap);
        }
        if (!conn.getAutoCommit()) {
            conn.rollback();
        }

        req.setAttribute("message",
                "The username or password were incorrect, please check your CAPS LOCK key and try again.");
        getLogger().debug("DBAUTH: no results for query");
    } catch (Exception e) {
        if (conn != null) {
            try {
                if (!conn.getAutoCommit()) {
                    conn.rollback();
                }
            } catch (Exception se) {
                /* ignore */}
        }
        getLogger().debug("exception: ", e);
        return null;
    } finally {
        if (rs != null)
            rs.close();
        if (st != null)
            st.close();
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                /* ignore */}
        }
    }
    return null;
}

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

/**
 * Execute the "write" sql - no response. a long binary field is set to "?" - fill it in with var
 * //from   ww  w  .java  2  s  .  co  m
 * @param sql
 *        The sql statement.
 * @param fields
 *        The array of fields for parameters.
 * @param var
 *        The value to bind to the last parameter in the sql statement.
 * @param offset
 *        The start within the var to write
 * @param len
 *        The number of bytes of var, starting with index, to write
 * @return true if successful, false if not.
 */
public boolean dbWriteBinary(String sql, Object[] fields, byte[] var, int offset, int len) {
    // Note: does not support TRANSACTION_CONNECTION -ggolden

    if (LOG.isDebugEnabled()) {
        LOG.debug("dbWriteBinary(String " + sql + ", Object[] " + Arrays.toString(fields) + ", byte[] "
                + Arrays.toString(var) + ", int " + offset + ", int " + len + ")");
    }

    // for DEBUG
    long start = 0;
    long connectionTime = 0;

    if (LOG.isDebugEnabled()) {
        String userId = usageSessionService().getSessionId();
        LOG.debug("Sql.dbWriteBinary(): " + userId + "\n" + sql + "  size:" + var.length);
    }

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

    // stream from the var
    InputStream varStream = new ByteArrayInputStream(var, offset, len);

    boolean success = false;

    try {
        if (m_showSql)
            start = System.currentTimeMillis();
        conn = borrowConnection();
        if (m_showSql)
            connectionTime = System.currentTimeMillis() - start;

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

        if (m_showSql)
            start = System.currentTimeMillis();
        pstmt = conn.prepareStatement(sql);

        // put in all the fields
        int pos = prepareStatement(pstmt, fields);

        // last, put in the binary
        pstmt.setBinaryStream(pos, varStream, len);

        //int result = 
        pstmt.executeUpdate();

        // commit and indicate success
        conn.commit();
        success = true;
    } catch (SQLException e) {
        // this is likely due to a key constraint problem...
        return false;
    } catch (Exception e) {
        LOG.warn("Sql.dbWriteBinary(): " + e);
        return false;
    } finally {
        //try
        //{
        if (null != pstmt) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                LOG.warn("Sql.dbWriteBinary(): " + e);
            }
        }
        if (null != varStream) {
            try {
                varStream.close();
            } catch (IOException e) {
                LOG.warn("Sql.dbWriteBinary(): " + e);
            }
        }

        if (null != conn) {
            // rollback on failure
            if (!success) {
                try {
                    conn.rollback();
                } catch (SQLException e) {
                    LOG.warn("Sql.dbWriteBinary(): " + e);
                }
            }

            // if we changed the auto commit, reset here
            if (resetAutoCommit) {
                try {
                    conn.setAutoCommit(autoCommit);
                } catch (SQLException e) {
                    LOG.warn("Sql.dbWriteBinary(): " + e);
                }
            }
            returnConnection(conn);
        }

    }

    if (m_showSql)
        debug("sql write binary: len: " + len + "  time: " + connectionTime + " / "
                + (System.currentTimeMillis() - start), sql, fields);

    return true;
}

From source file:org.hyperic.hq.measurement.server.session.DataManagerImpl.java

/**
 * Write metric datapoints to the DB without transaction
 * //from   ww  w.  j  ava  2s . c om
 * @param data a list of {@link DataPoint}s
 * @param overwrite If true, attempt to over-write values when an insert of
 *        the data fails (i.e. it already exists). You may not want to
 *        over-write values when, for instance, the back filler is inserting
 *        data.
 * @throws NumberFormatException if the value from the
 *         DataPoint.getMetricValue() cannot instantiate a BigDecimal
 * 
 * 
 */
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void addData(List<DataPoint> data, boolean overwrite) {
    /**
     * We have to account for 2 types of metric data insertion here: 1 - New
     * data, using 'insert' 2 - Old data, using 'update'
     * 
     * We optimize the amount of DB roundtrips here by executing in batch,
     * however there are some serious gotchas:
     * 
     * 1 - If the 'insert' batch update fails, a BatchUpdateException can be
     * thrown instead of just returning an error within the executeBatch()
     * array. 2 - This is further complicated by the fact that some drivers
     * will throw the exception at the first instance of an error, and some
     * will continue with the rest of the batch.
     */
    if (shouldAbortDataInsertion(data)) {
        return;
    }

    log.debug("Attempting to insert/update data outside a transaction.");

    data = enforceUnmodifiable(data);

    Connection conn = safeGetConnection();

    if (conn == null) {
        log.debug("Inserting/Updating data outside a transaction failed.");
        return;
    }

    try {
        boolean autocommit = conn.getAutoCommit();

        try {
            conn.setAutoCommit(true);
            addDataWithCommits(data, overwrite, conn);
        } finally {
            conn.setAutoCommit(autocommit);
        }
    } catch (SQLException e) {
        log.debug("Inserting/Updating data outside a transaction failed "
                + "because autocommit management failed.", e);
    } finally {
        DBUtil.closeConnection(LOG_CTX, conn);
    }
}

From source file:org.apache.roller.weblogger.business.startup.DatabaseInstaller.java

/**
 * Upgrade database for Roller 1.3.0/*from  w  w w . j a v a 2s  . c o m*/
 */
private void upgradeTo130(Connection con, boolean runScripts) throws StartupException {
    SQLScriptRunner runner = null;
    try {
        if (runScripts) {
            String handle = getDatabaseHandle(con);
            String scriptPath = handle + "/120-to-130-migration.sql";
            successMessage("Running database upgrade script: " + scriptPath);
            runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath));
            runner.runScript(con, true);
            messages.addAll(runner.getMessages());
        }

        /*
         * The new theme management code is going into place and it uses
         * the old website.themeEditor attribute to store a users theme.
         *
         * In pre-1.3 Roller *all* websites are considered to be using a
         * custom theme, so we need to make sure this is properly defined
         * by setting the theme on all websites to custom.
         *
         * NOTE: If we don't do this then nothing would break, but some users
         * would be suprised that their template customizations are no longer
         * in effect because they are using a shared theme instead.
         */

        successMessage("Doing upgrade to 130 ...");
        successMessage("Ensuring that all website themes are set to custom");

        PreparedStatement setCustomThemeStmt = con.prepareStatement("update website set editortheme = ?");

        setCustomThemeStmt.setString(1, org.apache.roller.weblogger.pojos.WeblogTheme.CUSTOM);
        setCustomThemeStmt.executeUpdate();

        if (!con.getAutoCommit())
            con.commit();

        successMessage("Upgrade to 130 complete.");

    } catch (Exception e) {
        log.error("ERROR running 310 database upgrade script", e);
        if (runner != null)
            messages.addAll(runner.getMessages());

        errorMessage("Problem upgrading database to version 130", e);
        throw new StartupException("Problem upgrading database to version 130", e);
    }

    updateDatabaseVersion(con, 130);
}

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

/**
 * Execute the "write/update" sql - no response, using a set of fields from an array plus one more as params and connection.
 * /*  www.j  a  va  2  s.com*/
 * @param sql
 *        The sql statement.
 * @param fields
 *        The array of fields for parameters.
 * @param lastField
 *        The value to bind to the last parameter in the sql statement.
 * @param callerConnection
 *        The connection to use.
 * @param failQuiet
 *        If true, don't log errors from statement failure
 * @return the number of records affected or -1 if something goes wrong if not due to unique constraint 
 * violation or duplicate key (i.e. the record already exists) OR we are instructed to fail quiet.
 */
public int dbWriteCount(String sql, Object[] fields, String lastField, Connection callerConnection,
        boolean failQuiet) {
    int retval = -1;
    // check for a transaction connection
    if (callerConnection == null) {
        callerConnection = (Connection) threadLocalManager().get(TRANSACTION_CONNECTION);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("dbWrite(String " + sql + ", Object[] " + Arrays.toString(fields) + ", String " + lastField
                + ", Connection " + callerConnection + ", boolean " + failQuiet + ")");
    }

    // for DEBUG
    long start = 0;
    long connectionTime = 0;

    if (LOG.isDebugEnabled()) {
        String userId = usageSessionService().getSessionId();
        StringBuilder buf = new StringBuilder();
        if (fields != null) {
            buf.append(fields[0]);
            for (int i = 1; i < fields.length; i++) {
                buf.append(", ");
                buf.append(fields[i]);
            }
            if (lastField != null) {
                buf.append(", ");
                buf.append(lastField);
            }
        } else if (lastField != null) {
            buf.append(lastField);
        }
        LOG.debug("Sql.dbWrite(): " + userId + "\n" + sql + "\n" + buf);
    }

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

    boolean success = false;

    try {
        if (callerConnection != null) {
            conn = callerConnection;
        } else {
            if (m_showSql)
                start = System.currentTimeMillis();
            conn = borrowConnection();
            if (m_showSql)
                connectionTime = System.currentTimeMillis() - start;

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

        if (m_showSql)
            start = System.currentTimeMillis();
        pstmt = conn.prepareStatement(sql);

        // put in all the fields
        int pos = prepareStatement(pstmt, fields);

        // last, put in the string value
        if (lastField != null) {
            sqlServiceSql.setBytes(pstmt, lastField, pos);
            pos++;
        }

        retval = pstmt.executeUpdate();

        // commit unless we are in a transaction (provided with a connection)
        if (callerConnection == null) {
            conn.commit();
        }

        // indicate success
        success = true;
    } catch (SQLException e) {
        // is this due to a key constraint problem?... check each vendor's error codes
        boolean recordAlreadyExists = sqlServiceSql.getRecordAlreadyExists(e);

        if (m_showSql) {
            LOG.warn("Sql.dbWrite(): error code: " + e.getErrorCode() + " sql: " + sql + " binds: "
                    + debugFields(fields) + " " + e);
        }

        // if asked to fail quietly, just return -1 if we find this error.
        if (recordAlreadyExists || failQuiet) {
            LOG.warn("Sql.dbWrite(): recordAlreadyExists: " + recordAlreadyExists + ", failQuiet: " + failQuiet
                    + ", : error code: " + e.getErrorCode() + ", " + "sql: " + sql + ", binds: "
                    + debugFields(fields) + ", error: " + e.toString());
            return -1;
        }

        // perhaps due to a mysql deadlock?
        if (sqlServiceSql.isDeadLockError(e.getErrorCode())) {
            // just a little fuss
            LOG.warn("Sql.dbWrite(): deadlock: error code: " + e.getErrorCode() + " sql: " + sql + " binds: "
                    + debugFields(fields) + " " + e.toString());
            throw new SqlServiceDeadlockException(e);
        }

        else if (recordAlreadyExists) {
            // just a little fuss
            LOG.warn("Sql.dbWrite(): unique violation: error code: " + e.getErrorCode() + " sql: " + sql
                    + " binds: " + debugFields(fields) + " " + e.toString());
            throw new SqlServiceUniqueViolationException(e);
        } else {
            // something ELSE went wrong, so lest make a fuss
            LOG.warn("Sql.dbWrite(): error code: " + e.getErrorCode() + " sql: " + sql + " binds: "
                    + debugFields(fields) + " ", e);
            throw new RuntimeException("SqlService.dbWrite failure", e);
        }
    } catch (Exception e) {
        LOG.warn("Sql.dbWrite(): " + e);
        throw new RuntimeException("SqlService.dbWrite failure", e);
    } finally {
        try {
            if (null != pstmt)
                pstmt.close();
            if ((null != conn) && (callerConnection == null)) {
                // rollback on failure
                if (!success) {
                    conn.rollback();
                }

                // if we changed the auto commit, reset here
                if (resetAutoCommit) {
                    conn.setAutoCommit(autoCommit);
                }
                returnConnection(conn);
            }
        } catch (Exception e) {
            LOG.warn("Sql.dbWrite(): " + e);
            throw new RuntimeException("SqlService.dbWrite failure", e);
        }
    }

    if (m_showSql)
        debug("Sql.dbWrite(): len: " + ((lastField != null) ? "" + lastField.length() : "null") + "  time: "
                + connectionTime + " /  " + (System.currentTimeMillis() - start), sql, fields);

    return retval;
}

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

/**
 * Execute the "insert" sql, returning a possible auto-update field Long value
 * /*from  w  w  w  .j ava  2  s  .  co  m*/
 * @param sql
 *        The sql statement.
 * @param fields
 *        The array of fields for parameters.
 * @param callerConnection
 *        The connection to use.
 * @param autoColumn
 *        The name of the db column that will have auto-update - we will return the value used (leave null to disable this feature).
 * @param last
 *        A stream to set as the last field.
 * @return The auto-update value, or null
 */
public Long dbInsert(Connection callerConnection, String sql, Object[] fields, String autoColumn,
        InputStream last, int lastLength) {
    boolean connFromThreadLocal = false;

    // check for a transaction conncetion
    if (callerConnection == null) {
        callerConnection = (Connection) threadLocalManager().get(TRANSACTION_CONNECTION);

        if (callerConnection != null) {
            // KNL-492 We set this so we can avoid returning a connection that is being managed elsewhere
            connFromThreadLocal = true;
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("dbInsert(String " + sql + ", Object[] " + Arrays.toString(fields) + ", Connection "
                + callerConnection + ")");
    }

    // for DEBUG
    long start = 0;
    long connectionTime = 0;

    if (LOG.isDebugEnabled()) {
        String userId = usageSessionService().getSessionId();
        StringBuilder buf = new StringBuilder();
        if (fields != null) {
            buf.append(fields[0]);
            for (int i = 1; i < fields.length; i++) {
                buf.append(", ");
                buf.append(fields[i]);
            }
        }
        LOG.debug("Sql.dbInsert(): " + userId + "\n" + sql + "\n" + buf);
    }

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

    boolean success = false;
    Long rv = null;

    try {
        if (callerConnection != null) {
            conn = callerConnection;
        } else {
            if (m_showSql)
                start = System.currentTimeMillis();
            conn = borrowConnection();
            if (m_showSql)
                connectionTime = System.currentTimeMillis() - start;

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

        if (m_showSql)
            start = System.currentTimeMillis();

        pstmt = sqlServiceSql.prepareAutoColumn(conn, sql, autoColumn);

        // put in all the fields
        int pos = prepareStatement(pstmt, fields);

        // and the last one
        if (last != null) {
            pstmt.setBinaryStream(pos, last, lastLength);
        }

        int result = pstmt.executeUpdate();

        rv = sqlServiceSql.getGeneratedKey(pstmt, sql);

        // commit unless we are in a transaction (provided with a connection)
        if (callerConnection == null) {
            conn.commit();
        }

        // indicate success
        success = true;
    } catch (SQLException e) {
        // is this due to a key constraint problem... check each vendor's error codes
        boolean recordAlreadyExists = sqlServiceSql.getRecordAlreadyExists(e);

        if (m_showSql) {
            LOG.warn("Sql.dbInsert(): error code: " + e.getErrorCode() + " sql: " + sql + " binds: "
                    + debugFields(fields) + " " + e);
        }

        if (recordAlreadyExists)
            return null;

        // perhaps due to a mysql deadlock?
        if (("mysql".equals(m_vendor)) && (e.getErrorCode() == 1213)) {
            // just a little fuss
            LOG.warn("Sql.dbInsert(): deadlock: error code: " + e.getErrorCode() + " sql: " + sql + " binds: "
                    + debugFields(fields) + " " + e.toString());
            throw new SqlServiceDeadlockException(e);
        }

        else if (recordAlreadyExists) {
            // just a little fuss
            LOG.warn("Sql.dbInsert(): unique violation: error code: " + e.getErrorCode() + " sql: " + sql
                    + " binds: " + debugFields(fields) + " " + e.toString());
            throw new SqlServiceUniqueViolationException(e);
        }

        else {
            // something ELSE went wrong, so lest make a fuss
            LOG.warn("Sql.dbInsert(): error code: " + e.getErrorCode() + " sql: " + sql + " binds: "
                    + debugFields(fields) + " ", e);
            throw new RuntimeException("SqlService.dbInsert failure", e);
        }
    } catch (Exception e) {
        LOG.warn("Sql.dbInsert(): " + e);
        throw new RuntimeException("SqlService.dbInsert failure", e);
    } finally {
        try {
            if (null != pstmt)
                pstmt.close();
            if ((null != conn) && (callerConnection == null)) {
                // rollback on failure
                if (!success) {
                    conn.rollback();
                }

                // if we changed the auto commit, reset here
                if (resetAutoCommit) {
                    conn.setAutoCommit(autoCommit);
                }

            }
        } catch (Exception e) {
            LOG.warn("Sql.dbInsert(): " + e);
            throw new RuntimeException("SqlService.dbInsert failure", e);
        }
        //make sure we return the connection even if the rollback etc above
        // KNL-492 connFromThreadLocal is tested so we can avoid returning a
        // connection that is being managed elsewhere
        if (conn != null && !connFromThreadLocal) {
            returnConnection(conn);
        }

    }

    if (m_showSql)
        debug("Sql.dbWrite(): len: " + "  time: " + connectionTime + " /  "
                + (System.currentTimeMillis() - start), sql, fields);

    return rv;
}

From source file:org.hyperic.hq.measurement.server.session.DataManagerImpl.java

protected boolean _addTopData(List<TopNData> topNData, Connection conn) {

    if (log.isDebugEnabled()) {
        log.debug("Attempting to insert topN data in a single transaction.");
    }//from w  w  w  .  ja  v a 2s  .c  o m
    boolean succeeded = false;
    final boolean debug = log.isDebugEnabled();

    if (conn == null) {
        return false;
    }

    try {
        boolean autocommit = conn.getAutoCommit();

        try {
            final long start = System.currentTimeMillis();
            conn.setAutoCommit(false);

            succeeded = insertTopData(conn, topNData, false);

            if (succeeded) {
                conn.commit();
                final long end = System.currentTimeMillis();
                if (debug) {
                    log.debug("Inserting TopN data in a single transaction " + "succeeded");
                    log.debug("TopN Data Insertion process took " + (end - start) + " ms");
                }

                concurrentStatsCollector.addStat(end - start, DATA_MANAGER_INSERT_TIME);
            } else {
                if (debug) {
                    log.debug("Inserting TopN data in a single transaction failed."
                            + "  Rolling back transaction" + ".");
                }
                conn.rollback();
            }

        } catch (SQLException e) {
            conn.rollback();
            throw e;
        } finally {
            conn.setAutoCommit(autocommit);
        }
    } catch (SQLException e) {
        log.debug("Transaction failed around inserting TopN data.", e);
    } finally {
        DBUtil.closeConnection(LOG_CTX, conn);
    }
    return succeeded;
}

From source file:org.sakaiproject.content.impl.DbContentService.java

protected void setUuidInternal(String id, String uuid) {
    // get a connection for the updates
    Connection connection = null;

    try {/*from ww  w  . j  a va 2s .  c o  m*/
        connection = m_sqlService.borrowConnection();

        boolean wasCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);

        // set any existing one to null
        String sql = contentServiceSql.getUpdateContentResource1Sql();
        Object[] fields = new Object[2];
        fields[0] = null;
        fields[1] = uuid;
        m_sqlService.dbWrite(connection, sql, fields);

        sql = contentServiceSql.getUpdateContentResource2Sql();
        fields = new Object[2];
        fields[0] = uuid;
        fields[1] = id;
        m_sqlService.dbWrite(connection, sql, fields);

        connection.commit();
        connection.setAutoCommit(wasCommit);

    } catch (SQLException e) {
        M_log.warn("setUuid: failed: " + e);
    } finally {
        if (connection != null) {
            m_sqlService.returnConnection(connection);
        }
    }
}