Example usage for org.springframework.jdbc.datasource DataSourceUtils releaseConnection

List of usage examples for org.springframework.jdbc.datasource DataSourceUtils releaseConnection

Introduction

In this page you can find the example usage for org.springframework.jdbc.datasource DataSourceUtils releaseConnection.

Prototype

public static void releaseConnection(@Nullable Connection con, @Nullable DataSource dataSource) 

Source Link

Document

Close the given Connection, obtained from the given DataSource, if it is not managed externally (that is, not bound to the thread).

Usage

From source file:net.tirasa.connid.bundles.soap.wssample.DefaultContentLoader.java

@Override
public void contextInitialized(final ServletContextEvent sce) {
    final WebApplicationContext springContext = WebApplicationContextUtils
            .getWebApplicationContext(sce.getServletContext());

    if (springContext == null) {
        LOG.error("Invalid Spring context");
        return;/*ww w.  ja  va2 s.  c  o m*/
    }

    final DataSource dataSource = springContext.getBean(DataSource.class);
    localDataSource = dataSource;

    final DefaultDataTypeFactory dbUnitDataTypeFactory = (DefaultDataTypeFactory) springContext
            .getBean("dbUnitDataTypeFactory");

    final Connection conn = DataSourceUtils.getConnection(dataSource);

    // create schema
    final StringBuilder statement = new StringBuilder();

    final InputStream dbschema = DefaultContentLoader.class.getResourceAsStream(DBSCHEMA);

    final BufferedReader buff = new BufferedReader(new InputStreamReader(dbschema));

    String line = null;
    try {
        while ((line = buff.readLine()) != null) {
            if (!line.isEmpty() && !line.startsWith("--")) {
                statement.append(line);
            }
        }
    } catch (IOException e) {
        LOG.error("Error reading file " + DBSCHEMA, e);
        return;
    }

    Statement st = null;
    try {
        st = conn.createStatement();
        st.execute(statement.toString());
    } catch (SQLException e) {
        LOG.error("Error creating schema:\n" + statement.toString(), e);
        return;
    } finally {
        try {
            st.close();
        } catch (Throwable t) {
            // ignore exception
        }
    }

    try {
        IDatabaseConnection dbUnitConn = new DatabaseConnection(conn);

        final DatabaseConfig config = dbUnitConn.getConfig();
        config.setProperty("http://www.dbunit.org/properties/datatypeFactory", dbUnitDataTypeFactory);

        boolean existingData = false;
        final IDataSet existingDataSet = dbUnitConn.createDataSet();
        for (final ITableIterator itor = existingDataSet.iterator(); itor.next() && !existingData;) {
            existingData = (itor.getTable().getRowCount() > 0);
        }

        final FlatXmlDataSetBuilder dataSetBuilder = new FlatXmlDataSetBuilder();
        dataSetBuilder.setColumnSensing(true);
        final IDataSet dataSet = dataSetBuilder.build(getClass().getResourceAsStream("/content.xml"));
        DatabaseOperation.REFRESH.execute(dbUnitConn, dataSet);
    } catch (Throwable t) {
        LOG.error("Error loding default content", t);
    } finally {
        DataSourceUtils.releaseConnection(conn, dataSource);
    }
}

From source file:org.grails.orm.hibernate.support.HibernateDialectDetectorFactoryBean.java

public void afterPropertiesSet() throws MetaDataAccessException {
    Assert.notNull(dataSource, "Data source is not set!");
    Assert.notNull(vendorNameDialectMappings, "Vendor name/dialect mappings are not set!");

    Connection connection = null;

    String dbName = (String) JdbcUtils.extractDatabaseMetaData(dataSource, "getDatabaseProductName");

    try {/*from  w  w  w .  j a va2  s .  com*/
        connection = DataSourceUtils.getConnection(dataSource);

        try {
            final DialectFactory dialectFactory = createDialectFactory();
            final Connection finalConnection = connection;
            DialectResolutionInfoSource infoSource = new DialectResolutionInfoSource() {
                @Override
                public DialectResolutionInfo getDialectResolutionInfo() {
                    try {
                        return new DatabaseMetaDataDialectResolutionInfoAdapter(finalConnection.getMetaData());
                    } catch (SQLException e) {
                        throw new CouldNotDetermineHibernateDialectException(
                                "Could not determine Hibernate dialect", e);
                    }
                }
            };
            hibernateDialect = dialectFactory.buildDialect(hibernateProperties, infoSource);
            hibernateDialectClassName = hibernateDialect.getClass().getName();
        } catch (HibernateException e) {
            hibernateDialectClassName = vendorNameDialectMappings.getProperty(dbName);
        }

        if (!StringUtils.hasText(hibernateDialectClassName)) {
            throw new CouldNotDetermineHibernateDialectException(
                    "Could not determine Hibernate dialect for database name [" + dbName + "]!");
        }
    } finally {
        DataSourceUtils.releaseConnection(connection, dataSource);
    }
}

From source file:me.j360.idgen.impl.SequenceIdGenServiceImpl.java

/**
 * Gets the next id as a Big Decimal. This method will only be called when
 * synchronized and when the data type is configured to be BigDecimal.
 * /*from   w  w  w  . ja  va 2 s  .  c  o  m*/
 * @return the next id as a BigDecimal.
 * @throws IdCreationException
 */
protected BigDecimal getNextBigDecimalIdInner() {
    getLogger().debug("[IDGeneration Service] Requesting an Id using query: {}", query);
    try {
        // 2009.10.08 - without handling connection directly
        Connection conn = DataSourceUtils.getConnection(getDataSource());
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            stmt = conn.prepareStatement(query);
            rs = stmt.executeQuery();
            if (rs.next()) {
                return rs.getBigDecimal(1);
            } else {
                getLogger().error(
                        "[IDGeneration Service] Unable to allocate a block of Ids. Query for Id did not return a value.");
                throw new IdCreationException(
                        "[IDGeneration Service] Unable to allocate a block of Ids. Query for Id did not return a value.");
            }
        } finally {
            if (rs != null) {
                JdbcUtils.closeResultSet(rs);
            }
            if (stmt != null) {
                JdbcUtils.closeStatement(stmt);
            }
            // 2009.10.08 - without handling connection directly
            if (conn != null) {
                DataSourceUtils.releaseConnection(conn, getDataSource());
            }

        }
        // 2009.10.08 - without handling connection directly
    } catch (Exception ex) {
        if (ex instanceof IdCreationException)
            throw (IdCreationException) ex;
        getLogger().error(
                "[IDGeneration Service] We can't get a connection. So, unable to allocate a block of Ids.", ex);
        throw new IdCreationException(
                "[IDGeneration Service] We can't get a connection. So, unable to allocate a block of Ids.", ex);
    }
}

From source file:org.cfr.capsicum.test.AbstractCayenneJUnit4DbUnitSpringContextTests.java

protected void backupDatabase(String charsetName, File file)
        throws SQLException, IOException, DatabaseUnitException {
    mkdir(file.getParent());//from   w w  w  . ja v a2 s. c  o  m
    // initialize your database connection here
    IDatabaseConnection connection = new DatabaseConnection(DataSourceUtils.getConnection(getDataSource()));
    // initialize your dataset here
    try {
        IDataSet dataSet = getDatabaseDataSet(connection, getTableNames(true), false);
        XmlDataSetWriter writer = new XmlDataSetWriter(
                new java.io.OutputStreamWriter(new FileOutputStream(file), charsetName));
        writer.write(dataSet);
    } finally {
        DataSourceUtils.releaseConnection(connection.getConnection(), getDataSource());
    }
}

From source file:org.syncope.core.util.ImportExport.java

private void setParameters(final String tableName, final Attributes atts, final Query query) {

    Map<String, Integer> colTypes = new HashMap<String, Integer>();

    Connection conn = DataSourceUtils.getConnection(dataSource);
    ResultSet rs = null;/*from  w  w w . j  a va  2s .  c  o m*/
    Statement stmt = null;
    try {
        stmt = conn.createStatement();
        rs = stmt.executeQuery("SELECT * FROM " + tableName);
        for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
            colTypes.put(rs.getMetaData().getColumnName(i + 1).toUpperCase(),
                    rs.getMetaData().getColumnType(i + 1));
        }
    } catch (SQLException e) {
        LOG.error("While", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                LOG.error("While closing statement", e);
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
        DataSourceUtils.releaseConnection(conn, dataSource);
    }

    for (int i = 0; i < atts.getLength(); i++) {
        Integer colType = colTypes.get(atts.getQName(i).toUpperCase());
        if (colType == null) {
            LOG.warn("No column type found for {}", atts.getQName(i).toUpperCase());
            colType = Types.VARCHAR;
        }

        switch (colType) {
        case Types.NUMERIC:
        case Types.REAL:
        case Types.INTEGER:
        case Types.TINYINT:
            try {
                query.setParameter(i + 1, Integer.valueOf(atts.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Integer '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.DECIMAL:
        case Types.BIGINT:
            try {
                query.setParameter(i + 1, Long.valueOf(atts.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Long '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.DOUBLE:
            try {
                query.setParameter(i + 1, Double.valueOf(atts.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Double '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.FLOAT:
            try {
                query.setParameter(i + 1, Float.valueOf(atts.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Float '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            try {
                query.setParameter(i + 1, DateUtils.parseDate(atts.getValue(i), SyncopeConstants.DATE_PATTERNS),
                        TemporalType.TIMESTAMP);
            } catch (ParseException e) {
                LOG.error("Unparsable Date '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.BIT:
        case Types.BOOLEAN:
            query.setParameter(i + 1, "1".equals(atts.getValue(i)) ? Boolean.TRUE : Boolean.FALSE);
            break;

        default:
            query.setParameter(i + 1, atts.getValue(i));
        }
    }
}

From source file:org.silverpeas.migration.contentmanagement.DuplicatedContentRemovingTest.java

protected ITable getActualTable(String tableName) throws Exception {
    Connection connection = DataSourceUtils.getConnection(dataSource);
    IDatabaseConnection databaseConnection = new DatabaseConnection(connection);
    IDataSet dataSet = databaseConnection.createDataSet();
    ITable table = dataSet.getTable(tableName);
    DataSourceUtils.releaseConnection(connection, dataSource);
    return table;
}

From source file:org.syncope.core.init.ContentLoader.java

@Transactional
public void load() {
    // 0. DB connection, to be used below
    Connection conn = DataSourceUtils.getConnection(dataSource);

    // 1. Check wether we are allowed to load default content into the DB
    Statement statement = null;//w  ww.  ja  v  a  2s  .  c o  m
    ResultSet resultSet = null;
    boolean existingData = false;
    try {
        statement = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

        resultSet = statement.executeQuery("SELECT * FROM " + SyncopeConf.class.getSimpleName());
        resultSet.last();

        existingData = resultSet.getRow() > 0;
    } catch (SQLException e) {
        LOG.error("Could not access to table " + SyncopeConf.class.getSimpleName(), e);

        // Setting this to true make nothing to be done below
        existingData = true;
    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            LOG.error("While closing SQL result set", e);
        }
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            LOG.error("While closing SQL statement", e);
        }
    }

    if (existingData) {
        LOG.info("Data found in the database, leaving untouched");
        return;
    }

    LOG.info("Empty database found, loading default content");

    // 2. Create views
    LOG.debug("Creating views");
    try {
        InputStream viewsStream = getClass().getResourceAsStream("/views.xml");
        Properties views = new Properties();
        views.loadFromXML(viewsStream);

        for (String idx : views.stringPropertyNames()) {
            LOG.debug("Creating view {}", views.get(idx).toString());

            try {
                statement = conn.createStatement();
                statement.executeUpdate(views.get(idx).toString().replaceAll("\\n", " "));
                statement.close();
            } catch (SQLException e) {
                LOG.error("Could not create view ", e);
            }
        }

        LOG.debug("Views created, go for indexes");
    } catch (Throwable t) {
        LOG.error("While creating views", t);
    }

    // 3. Create indexes
    LOG.debug("Creating indexes");
    try {
        InputStream indexesStream = getClass().getResourceAsStream("/indexes.xml");
        Properties indexes = new Properties();
        indexes.loadFromXML(indexesStream);

        for (String idx : indexes.stringPropertyNames()) {
            LOG.debug("Creating index {}", indexes.get(idx).toString());

            try {
                statement = conn.createStatement();
                statement.executeUpdate(indexes.get(idx).toString());
                statement.close();
            } catch (SQLException e) {
                LOG.error("Could not create index ", e);
            }
        }

        LOG.debug("Indexes created, go for default content");
    } catch (Throwable t) {
        LOG.error("While creating indexes", t);
    } finally {
        DataSourceUtils.releaseConnection(conn, dataSource);
    }

    try {
        conn.close();
    } catch (SQLException e) {
        LOG.error("While closing SQL connection", e);
    }

    // 4. Load default content
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
        SAXParser parser = factory.newSAXParser();
        parser.parse(getClass().getResourceAsStream("/content.xml"), importExport);
        LOG.debug("Default content successfully loaded");
    } catch (Throwable t) {
        LOG.error("While loading default content", t);
    }
}

From source file:com.baoqilai.core.dao.BaseJdbcDao.java

/**
 * Close the given JDBC Connection, created via this DAO's DataSource, if it
 * isn't bound to the thread.//from  w ww  . ja v  a2 s.  co m
 * 
 * @param con
 *            Connection to close
 * @see org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection
 */
protected final void releaseConnection(Connection con) {
    DataSourceUtils.releaseConnection(con, getDataSource());
}