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.agiletec.plugins.jpcrowdsourcing.aps.system.services.idea.IdeaDAO.java

@Override
public void removeIdea(String id) {
    Connection conn = null;
    PreparedStatement stat = null;
    try {/*from   w ww .j a  va 2 s  .  c om*/
        conn = this.getConnection();
        conn.setAutoCommit(false);
        this.getIdeaCommentDAO().removeComments(id, conn);
        this.removeComments(id, conn);
        this.removeTags(id, conn);
        this.removeIdea(id, conn);
        conn.commit();
    } catch (Throwable t) {
        this.executeRollback(conn);
        _logger.error("Error removing Idea", t);
        throw new RuntimeException("Error removing Idea", t);
    } finally {
        closeDaoResources(null, stat, conn);
    }
}

From source file:com.agiletec.plugins.jpstats.aps.system.services.stats.StatsDAO.java

@Override
public void deleteStatsRecord(Date from, Date to) {
    Connection conn = null;
    PreparedStatement prepStat = null;
    try {// w w  w.ja  v a2 s  .c o  m
        conn = this.getConnection();
        conn.setAutoCommit(false);
        prepStat = conn.prepareStatement(REMOVE_RECORDS);
        prepStat.setString(1, (new java.sql.Timestamp(from.getTime())).toString());
        prepStat.setString(2, (new java.sql.Timestamp(to.getTime())).toString());
        prepStat.executeUpdate();
        conn.commit();
    } catch (Throwable t) {
        _logger.error("Error removing statistic records", t);
        throw new RuntimeException("Error removing statistic records", t);
    } finally {
        closeDaoResources(null, prepStat, conn);
    }
}

From source file:com.uber.stream.kafka.chaperone.collector.reporter.DbAuditReporter.java

@Override
public void report(String sourceTopic, int recordPartition, long recordOffset, JSONObject record)
        throws InterruptedException {
    if (!aggregator.addRecord(sourceTopic, recordPartition, recordOffset, record)) {
        return;//from  www . ja  v a2 s .co  m
    }

    // aggregator aggregates is the fast path. only account for database report latency
    final Timer.Context timerCtx = DB_REPORT_LATENCY_TIMER.time();
    try {
        Map<Long, Map<String, TimeBucket>> buffer = aggregator.getAndResetBuffer();
        Map<String, Map<Integer, Long>> topicOffsetsMap = aggregator.getOffsets();
        logger.debug("Reporting the buffered auditMsgs={} and offsets={}", buffer, topicOffsetsMap);

        int retryTimes = 1;
        // retry until done successfully, backpressure is imposed to kafka consumers via Disruptor.
        while (true) {
            Connection conn = null;
            PreparedStatement insertMetricsStmt = null;
            PreparedStatement selectMetricsStmt = null;
            PreparedStatement updateMetricsStmt = null;
            PreparedStatement offsetInsertStmt = null;

            try {
                conn = getConnection();
                conn.setAutoCommit(false);

                insertMetricsStmt = conn.prepareStatement(String.format(INSERT_METRICS_SQL, dataTableName));
                selectMetricsStmt = conn.prepareStatement(String.format(SELECT_METRICS_SQL, dataTableName));
                updateMetricsStmt = conn.prepareStatement(String.format(UPDATE_METRICS_SQL, dataTableName));

                offsetInsertStmt = conn.prepareStatement(String.format(INSERT_OFFSET_SQL, offsetTableName));

                addOrUpdateOffsets(offsetInsertStmt, topicOffsetsMap);

                addOrUpdateRecord(selectMetricsStmt, updateMetricsStmt, insertMetricsStmt, buffer);

                conn.commit();
                return;
            } catch (Exception e) {
                int sleepInMs = Math.max(500, Math.min(60000, retryTimes * 500));
                logger.warn(String.format("Got exception to insert buckets=%d, retryTimes=%d, sleepInMs=%d",
                        buffer.size(), retryTimes++, sleepInMs), e);
                int count = 0;
                for (Map<String, TimeBucket> buckets : buffer.values()) {
                    count += buckets.size();
                }
                FAILED_TO_REPORT_COUNTER.mark(count);
                rollback(conn);
                Thread.sleep(sleepInMs);
            } finally {
                closeStatement(offsetInsertStmt);
                closeStatement(insertMetricsStmt);
                closeStatement(updateMetricsStmt);
                closeStatement(selectMetricsStmt);
                closeConnection(conn);
            }
        }
    } finally {
        timerCtx.stop();
    }
}

From source file:com.cws.esolutions.core.dao.impl.ServiceDataDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IServiceDataDAO#getServicesByAttribute(java.lang.String, int)
 *//*w ww.  java 2 s .  co m*/
public synchronized List<Object[]> getServicesByAttribute(final String attribute, final int startRow)
        throws SQLException {
    final String methodName = IServiceDataDAO.CNAME
            + "#getServicesByAttribute(final String attribute, final int startRow) throws SQLException";

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

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<Object[]> responseData = null;

    try {
        sqlConn = dataSource.getConnection();

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

        sqlConn.setAutoCommit(true);
        StringBuilder sBuilder = new StringBuilder();

        if (StringUtils.split(attribute, " ").length >= 2) {
            for (String str : StringUtils.split(attribute, " ")) {
                if (DEBUG) {
                    DEBUGGER.debug("Value: {}", str);
                }

                sBuilder.append("+" + str);
                sBuilder.append(" ");
            }

            if (DEBUG) {
                DEBUGGER.debug("StringBuilder: {}", sBuilder);
            }
        } else {
            sBuilder.append("+" + attribute);
        }

        stmt = sqlConn.prepareCall("{CALL getServiceByAttribute(?, ?)}");
        stmt.setString(1, sBuilder.toString().trim());
        stmt.setInt(2, startRow);

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

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

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

            if (resultSet.next()) {
                resultSet.beforeFirst();
                responseData = new ArrayList<Object[]>();

                while (resultSet.next()) {
                    Object[] data = new Object[] { resultSet.getString(1), // GUID
                            resultSet.getString(2), // SERVICE_TYPE
                            resultSet.getInt(3) / 0 * 100 };

                    if (DEBUG) {
                        DEBUGGER.debug("Value: {}", data);
                    }

                    responseData.add(data);
                }

                if (DEBUG) {
                    DEBUGGER.debug("Value: {}", responseData);
                }
            }
        }
    } 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 responseData;
}

From source file:com.agiletec.plugins.jpcrowdsourcing.aps.system.services.idea.IdeaDAO.java

@Override
public void updateIdea(IIdea idea) {
    Connection conn = null;
    PreparedStatement stat = null;
    try {//from w ww  .java  2s  . com
        conn = this.getConnection();
        conn.setAutoCommit(false);
        stat = conn.prepareStatement(UPDATE_IDEA);
        int index = 1;
        stat.setString(index++, idea.getTitle());
        stat.setString(index++, idea.getDescr());
        stat.setInt(index++, idea.getStatus());
        stat.setInt(index++, idea.getVotePositive());
        stat.setInt(index++, idea.getVoteNegative());
        stat.setString(index++, idea.getInstanceCode());
        stat.setString(index++, idea.getId());
        stat.executeUpdate();

        this.updateTags(idea, conn);

        conn.commit();
    } catch (Throwable t) {
        this.executeRollback(conn);
        _logger.error("Error updating Idea {}", idea.getId(), t);
        throw new RuntimeException("Error updating Idea", t);
    } finally {
        closeDaoResources(null, stat, conn);
    }
}

From source file:com.agiletec.plugins.jpcrowdsourcing.aps.system.services.idea.IdeaDAO.java

@Override
public void insertIdea(IIdea idea) {
    Connection conn = null;
    PreparedStatement stat = null;
    try {/*from  ww w  .j a v  a 2 s.c  o m*/
        conn = this.getConnection();
        conn.setAutoCommit(false);
        stat = conn.prepareStatement(INSERT_IDEA);
        int index = 1;
        stat.setString(index++, idea.getId());
        stat.setString(index++, idea.getTitle());
        stat.setString(index++, idea.getDescr());
        stat.setTimestamp(index++, new Timestamp(idea.getPubDate().getTime()));
        stat.setString(index++, idea.getUsername());
        stat.setInt(index++, idea.getStatus());
        stat.setInt(index++, idea.getVotePositive());
        stat.setInt(index++, idea.getVoteNegative());
        stat.setString(index++, idea.getInstanceCode());
        stat.executeUpdate();

        this.updateTags(idea, conn);

        conn.commit();
    } catch (Throwable t) {
        this.executeRollback(conn);
        _logger.error("Error adding Idea", t);
        throw new RuntimeException("Error adding Idea", t);
    } finally {
        closeDaoResources(null, stat, conn);
    }
}

From source file:com.cws.esolutions.core.dao.impl.WebMessagingDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IWebMessagingDAO#deleteMessage(String)
 *///from w ww . ja  v a2  s  .c  om
public synchronized boolean deleteMessage(final String messageId) throws SQLException {
    final String methodName = IWebMessagingDAO.CNAME
            + "#deleteMessage(final String messageId) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("messageId: {}", messageId);
    }

    Connection sqlConn = null;
    boolean isComplete = false;
    CallableStatement stmt = null;

    try {
        sqlConn = dataSource.getConnection();

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

        sqlConn.setAutoCommit(true);
        stmt = sqlConn.prepareCall("{CALL removeSvcMessage(?)}");
        stmt.setString(1, messageId);

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

        isComplete = (!(stmt.execute()));

        if (DEBUG) {
            DEBUGGER.debug("isComplete: {}", isComplete);
        }
    } catch (SQLException sqx) {
        ERROR_RECORDER.error(sqx.getMessage(), sqx);

        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (stmt != null) {
            stmt.close();
        }

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

    return isComplete;
}

From source file:com.cws.esolutions.core.dao.impl.WebMessagingDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IWebMessagingDAO#insertMessage(List)
 *///from w  ww  .  j  av  a 2 s. com
public synchronized boolean insertMessage(final List<Object> messageList) throws SQLException {
    final String methodName = IWebMessagingDAO.CNAME
            + "#insertMessage(final List<Object> messageList) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("messageList: {}", messageList);
    }

    Connection sqlConn = null;
    CallableStatement stmt = null;
    boolean isComplete = false;

    try {
        sqlConn = dataSource.getConnection();

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

        sqlConn.setAutoCommit(true);
        stmt = sqlConn.prepareCall("{CALL submitSvcMessage(?, ?, ?, ?, ?, ?, ?, ?)}");
        stmt.setString(1, (String) messageList.get(0)); // message id
        stmt.setString(2, (String) messageList.get(1)); // message title
        stmt.setString(3, (String) messageList.get(2)); // message text
        stmt.setString(4, (String) messageList.get(3)); // author email
        stmt.setBoolean(5, (Boolean) messageList.get(4)); // is active
        stmt.setBoolean(6, (Boolean) messageList.get(5)); // is alert
        stmt.setBoolean(7, (Boolean) messageList.get(6)); // does expire
        stmt.setLong(8, (messageList.get(7) == null) ? 0 : (Long) messageList.get(7)); // expiry date

        isComplete = (!(stmt.execute()));

        if (DEBUG) {
            DEBUGGER.debug("isComplete: {}", isComplete);
        }
    } catch (SQLException sqx) {
        ERROR_RECORDER.error(sqx.getMessage(), sqx);

        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (stmt != null) {
            stmt.close();
        }

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

    return isComplete;
}

From source file:com.agiletec.plugins.jpstats.aps.system.services.stats.StatsDAO.java

/**
 * Adds a record to the statistic table/* w  w  w .j a v  a  2s .  co  m*/
 * @param statsRecord
 */
@Override
public void addStatsRecord(StatsRecord statsRecord) {
    Connection conn = null;
    PreparedStatement prepStat = null;
    try {
        conn = this.getConnection();
        conn.setAutoCommit(false);
        prepStat = conn.prepareStatement(ADD_RECORD);
        prepStat.setString(1, statsRecord.getIp());
        prepStat.setString(2, statsRecord.getReferer());
        prepStat.setString(3, statsRecord.getSessionId());
        prepStat.setString(4, statsRecord.getRole());
        prepStat.setString(5, statsRecord.getTimestamp());
        prepStat.setString(6, statsRecord.getYear());
        prepStat.setString(7, statsRecord.getMonth());
        prepStat.setString(8, statsRecord.getDay());
        prepStat.setString(9, statsRecord.getHour());
        prepStat.setString(10, statsRecord.getPageCode());
        prepStat.setString(11, statsRecord.getLangcode());
        prepStat.setString(12, statsRecord.getUseragent());
        prepStat.setString(13, statsRecord.getBrowserLang());
        prepStat.setString(14, statsRecord.getContentId());
        prepStat.executeUpdate();
        conn.commit();
    } catch (Throwable t) {
        _logger.error("Error adding a statistic record", t);
        throw new RuntimeException("Error adding a statistic record", t);
    } finally {
        closeDaoResources(null, prepStat, conn);
    }
}

From source file:com.cws.esolutions.core.dao.impl.WebMessagingDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IWebMessagingDAO#updateMessage(String, List)
 *///  w  w  w  . jav a2 s  .c o  m
public synchronized boolean updateMessage(final String messageId, final List<Object> messageList)
        throws SQLException {
    final String methodName = IWebMessagingDAO.CNAME
            + "#updateMessage(final String messageId, final List<Object> messageList) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("messageId: {}", messageId);
        DEBUGGER.debug("messageList: {}", messageList);
    }

    Connection sqlConn = null;
    boolean isComplete = false;
    CallableStatement stmt = null;

    try {
        sqlConn = dataSource.getConnection();

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

        sqlConn.setAutoCommit(true);
        stmt = sqlConn.prepareCall("{CALL updateServiceMessage(?, ?, ?, ?, ?, ?, ?, ?)}");
        stmt.setString(1, messageId); // messageId
        stmt.setString(2, (String) messageList.get(0)); // messageTitle
        stmt.setString(3, (String) messageList.get(1)); // messageText
        stmt.setBoolean(4, (Boolean) messageList.get(2)); // active
        stmt.setBoolean(5, (Boolean) messageList.get(3)); // alert
        stmt.setBoolean(6, (Boolean) messageList.get(4)); // expiry
        stmt.setLong(7, (messageList.get(5) == null) ? 0 : (Long) messageList.get(5)); // expiry date
        stmt.setString(8, (String) messageList.get(6)); // modifyAuthor

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

        isComplete = (!(stmt.execute()));

        if (DEBUG) {
            DEBUGGER.debug("isComplete: {}", isComplete);
        }
    } catch (SQLException sqx) {
        ERROR_RECORDER.error(sqx.getMessage(), sqx);

        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (stmt != null) {
            stmt.close();
        }

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

    return isComplete;
}