Example usage for org.springframework.jdbc.support JdbcUtils closeConnection

List of usage examples for org.springframework.jdbc.support JdbcUtils closeConnection

Introduction

In this page you can find the example usage for org.springframework.jdbc.support JdbcUtils closeConnection.

Prototype

public static void closeConnection(@Nullable Connection con) 

Source Link

Document

Close the given JDBC Connection and ignore any thrown exception.

Usage

From source file:net.firejack.platform.core.config.upgrader.SchemaUpgrader.java

/**
 * This method update database package version and increase version number
 *
 * @param packageLookup - Openflame Package lookup
 * @param version       - database version
 * @return version//from   ww w.j  a  v a2 s  . co  m
 */
private Version updateDatabaseVersion(String packageLookup, Version version) {
    try {
        Connection connection = dataSource.getConnection();
        try {
            connection.setAutoCommit(true);

            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);
            statement.addBatch("UPDATE opf_registry_node SET database_version = " + version.getToVersion() + " "
                    + "WHERE lookup = '" + packageLookup + "';");
            try {
                statement.executeBatch();
                return new Version(version.getToVersion());
            } finally {
                JdbcUtils.closeStatement(statement);
            }
        } finally {
            connection.setAutoCommit(false);
            JdbcUtils.closeConnection(connection);
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.spring.data.gemfire.app.dao.provider.JdbcUserDao.java

@Override
public User save(final User user) {
    final boolean update = exists(user.getUsername());

    final String SQL = (update ? UPDATE_USER_SQL : INSERT_USER_SQL);

    Connection connection = createConnectionBuilder().setAutoCommit(false)
            .setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED).build();

    try {/*  w  w  w  . ja  v a  2 s  .  com*/
        PreparedStatement statement = connection.prepareStatement(SQL);

        statement = (update ? prepareUpdate(statement, user) : prepareInsert(statement, user));
        statement.executeUpdate();

        connection.commit();

        return user;
    } catch (SQLException e) {
        rollback(connection);

        throw createDataAccessException(
                String.format("Failed to save (%1$s) User (%2$s)!", (update ? "UPDATE" : "INSERT"), user), e);
    } finally {
        JdbcUtils.closeConnection(connection);
    }
}

From source file:org.lexevs.dao.database.datasource.ErrorReportingDataSourceDecorator.java

@Override
public void afterPropertiesSet() throws Exception {
    Assert.notNull(this.decoratoredDataSource);

    Connection connection = null;
    try {//from w w  w.  j  ava 2s .  c o  m
        connection = this.decoratoredDataSource.getConnection();

        JdbcUtils.closeConnection(connection);
    } catch (Exception e) {
        JdbcUtils.closeConnection(connection);
        logger.fatal(this.printError(e));
        System.exit(1);
    } finally {
        JdbcUtils.closeConnection(connection);
    }
}

From source file:org.opoo.oqs.spring.jdbc.TransactionSupportConnectionManager.java

public void releaseConnection(Connection con) {
    if (dataSource == null) {
        throw new IllegalArgumentException("No DataSource specified");
    }// w w w .ja v a  2  s . c  o  m
    Connection conn = (Connection) TransactionSynchronizationManager.getResource(dataSource);
    if (conn != null && (con == conn || conn.equals(con))) {
        log.debug("Connection in Transaction, do not close.");
    } else {
        JdbcUtils.closeConnection(con);
    }
}

From source file:org.springframework.batch.item.database.AbstractCursorItemReader.java

/**
 * Close the cursor and database connection. Make call to cleanupOnClose so sub classes can cleanup
 * any resources they have allocated./*from w  w  w.j a va 2 s .  c o m*/
 */
@Override
protected void doClose() throws Exception {
    initialized = false;
    JdbcUtils.closeResultSet(this.rs);
    rs = null;
    cleanupOnClose();
    if (useSharedExtendedConnection && dataSource instanceof ExtendedConnectionDataSourceProxy) {
        ((ExtendedConnectionDataSourceProxy) dataSource).stopCloseSuppression(this.con);
        if (!TransactionSynchronizationManager.isActualTransactionActive()) {
            DataSourceUtils.releaseConnection(con, dataSource);
        }
    } else {
        JdbcUtils.closeConnection(this.con);
    }
}

From source file:org.springframework.jdbc.support.DatabaseStartupValidator.java

/**
 * Check whether the validation query can be executed on a Connection
 * from the specified DataSource, with the specified interval between
 * checks, until the specified timeout./* w w w . j  a va  2 s .  com*/
 */
@Override
public void afterPropertiesSet() {
    DataSource dataSource = this.dataSource;
    if (dataSource == null) {
        throw new IllegalArgumentException("Property 'dataSource' is required");
    }
    if (this.validationQuery == null) {
        throw new IllegalArgumentException("Property 'validationQuery' is required");
    }

    try {
        boolean validated = false;
        long beginTime = System.currentTimeMillis();
        long deadLine = beginTime + this.timeout * 1000;
        SQLException latestEx = null;

        while (!validated && System.currentTimeMillis() < deadLine) {
            Connection con = null;
            Statement stmt = null;
            try {
                con = dataSource.getConnection();
                if (con == null) {
                    throw new CannotGetJdbcConnectionException("Failed to execute validation query: "
                            + "DataSource returned null from getConnection(): " + dataSource);
                }
                stmt = con.createStatement();
                stmt.execute(this.validationQuery);
                validated = true;
            } catch (SQLException ex) {
                latestEx = ex;
                logger.debug("Validation query [" + this.validationQuery + "] threw exception", ex);
                float rest = ((float) (deadLine - System.currentTimeMillis())) / 1000;
                if (rest > this.interval) {
                    logger.warn("Database has not started up yet - retrying in " + this.interval
                            + " seconds (timeout in " + rest + " seconds)");
                }
            } finally {
                JdbcUtils.closeStatement(stmt);
                JdbcUtils.closeConnection(con);
            }

            if (!validated) {
                Thread.sleep(this.interval * 1000);
            }
        }

        if (!validated) {
            throw new CannotGetJdbcConnectionException(
                    "Database has not started up within " + this.timeout + " seconds", latestEx);
        }

        float duration = (System.currentTimeMillis() - beginTime) / 1000;
        if (logger.isInfoEnabled()) {
            logger.info("Database startup detected after " + duration + " seconds");
        }
    } catch (InterruptedException ex) {
        // Re-interrupt current thread, to allow other threads to react.
        Thread.currentThread().interrupt();
    }
}

From source file:ru.org.linux.spring.SearchQueueListener.java

public void handleMessage(SearchQueueSender.UpdateMessage msgUpdate)
        throws SQLException, MessageNotFoundException, IOException, SolrServerException {
    logger.info("Indexing " + msgUpdate.getMsgid());

    Connection db = LorDataSource.getConnection();

    try {/*from   ww  w .j a va 2s  .  c  om*/
        reindexMessage(db, msgUpdate.getMsgid(), msgUpdate.isWithComments());
        solrServer.commit();
    } finally {
        JdbcUtils.closeConnection(db);
    }
}

From source file:ru.org.linux.spring.SearchQueueListener.java

public void handleMessage(SearchQueueSender.UpdateComments msgUpdate)
        throws SQLException, MessageNotFoundException, IOException, SolrServerException {
    logger.info("Indexing " + msgUpdate.getMsgids());

    Connection db = LorDataSource.getConnection();
    PreparedStatement pst = null;

    try {//from ww w .jav  a2  s .c o m
        pst = db.prepareStatement("SELECT message FROM msgbase WHERE id=?");

        for (Integer msgid : msgUpdate.getMsgids()) {
            Comment comment = new Comment(db, msgid);

            if (comment.isDeleted()) {
                logger.info("Deleting comment " + comment.getId() + " from solr");
                solrServer.deleteById(Integer.toString(comment.getId()));
            } else {
                //        ? ?? ?
                //  ? ??  -  , ..    ?
                //    
                Message topic = new Message(db, comment.getTopic());

                pst.setInt(1, comment.getId());
                ResultSet rs = pst.executeQuery();
                if (!rs.next()) {
                    throw new RuntimeException("Can't load message text for " + comment.getId());
                }

                String message = rs.getString(1);

                rs.close();

                solrServer.add(processComment(topic, comment, message));
            }
        }

        solrServer.commit();
    } finally {
        JdbcUtils.closeStatement(pst);
        JdbcUtils.closeConnection(db);
    }
}

From source file:ru.org.linux.spring.SearchQueueListener.java

public void handleMessage(SearchQueueSender.UpdateMonth msgUpdate)
        throws SQLException, MessageNotFoundException, IOException, SolrServerException {
    int month = msgUpdate.getMonth();
    int year = msgUpdate.getYear();

    logger.info("Indexing month " + year + '/' + month);

    Connection db = LorDataSource.getConnection();

    try {//from ww  w .j  a  v a2 s. c o  m
        long startTime = System.nanoTime();

        Statement st = db.createStatement();

        ResultSet rs = st.executeQuery("SELECT id FROM topics WHERE postdate>='" + year + '-' + month
                + "-01'::timestamp AND (postdate<'" + year + '-' + month
                + "-01'::timestamp+'1 month'::interval)");

        while (rs.next()) {
            reindexMessage(db, rs.getInt(1), true);
        }

        solrServer.commit();

        long endTime = System.nanoTime();

        logger.info("Reindex month " + year + '/' + month + " done, " + (endTime - startTime) / 1000000
                + " millis");
    } finally {
        JdbcUtils.closeConnection(db);
    }
}