List of usage examples for org.springframework.jdbc.datasource DataSourceUtils releaseConnection
public static void releaseConnection(@Nullable Connection con, @Nullable DataSource dataSource)
From source file:org.danann.cernunnos.sql.OpenConnectionTask.java
protected void performCreateConnection(TaskRequest req, TaskResponse res, DataSource dataSource) { final Connection connection = DataSourceUtils.getConnection(dataSource); try {/*from w w w . j a v a 2 s. c o m*/ // Make it available as a request attribute... final String connectionAttrName = (String) attribute_name.evaluate(req, res); res.setAttribute(connectionAttrName, connection); // Invoke subtasks... super.performSubtasks(req, res); } finally { DataSourceUtils.releaseConnection(connection, dataSource); } }
From source file:com.saysth.commons.quartz.LocalDataSourceJobStore.java
@Override protected void closeConnection(Connection con) { // Will work for transactional and non-transactional connections. DataSourceUtils.releaseConnection(con, this.dataSource); }
From source file:org.sakaiproject.orm.ibatis.SqlMapClientTemplate.java
/** * Execute the given data access action on a SqlMapSession. * @param action callback object that specifies the data access action * @return a result object returned by the action, or <code>null</code> * @throws DataAccessException in case of SQL Maps errors *///from w w w . j a va 2s .c om public Object execute(SqlMapClientCallback action) throws DataAccessException { Assert.notNull(this.sqlMapClient, "No SqlMapClient specified"); // We always needs to use a SqlMapSession, as we need to pass a Spring-managed // Connection (potentially transactional) in. This shouldn't be necessary if // we run against a TransactionAwareDataSourceProxy underneath, but unfortunately // we still need it to make iBATIS batch execution work properly: If iBATIS // doesn't recognize an existing transaction, it automatically executes the // batch for every single statement... SqlMapSession session = this.sqlMapClient.openSession(); try { Connection con = DataSourceUtils.getConnection(getDataSource()); try { session.setUserConnection(con); return action.doInSqlMapClient(session); } catch (SQLException ex) { throw getExceptionTranslator().translate("SqlMapClient operation", null, ex); } finally { DataSourceUtils.releaseConnection(con, getDataSource()); } } finally { session.close(); } }
From source file:me.j360.idgen.impl.SequenceIdGenServiceImpl.java
/** * Gets the next id as a long. This method will only be called when * synchronized and when the data type is configured to be long. * /*from w w w . j a v a 2 s.c o m*/ * @return the next id as a long. * @throws IdCreationException */ protected long getNextLongIdInner() { 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.getLong(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.mifos.test.framework.util.DatabaseTestUtils.java
/** * Verify that a database table matches a dataSet table. dataSetXml must be formatted as a DBUnit * xml dataset. This method can be safely invoked inside a Spring-managed transaction. * @param dataSetXml//from w w w. j a v a2s .co m * @param tableName * @param dataSource * @throws Exception */ @SuppressWarnings("PMD.SignatureDeclareThrowsException") // one of the dependent methods throws Exception public void verifyTable(String dataSetXml, String tableName, DriverManagerDataSource dataSource) throws Exception { Connection jdbcConnection = null; StringReader dataSetXmlStream = new StringReader(dataSetXml); try { jdbcConnection = DataSourceUtils.getConnection(dataSource); IDatabaseTester databaseTester = new DataSourceDatabaseTester(dataSource); IDatabaseConnection databaseConnection = databaseTester.getConnection(); IDataSet databaseDataSet = databaseConnection.createDataSet(); ITable actualTable = databaseDataSet.getTable(tableName); IDataSet expectedDataSet = new FlatXmlDataSet(dataSetXmlStream); ITable expectedTable = expectedDataSet.getTable(tableName); Assertion.assertEqualsIgnoreCols(expectedTable, actualTable, new String[] { "id" }); } finally { if (null != jdbcConnection) { jdbcConnection.close(); } DataSourceUtils.releaseConnection(jdbcConnection, dataSource); } }
From source file:com.qualogy.qafe.business.integration.rdb.SQLQueryDAO.java
private Object execute(RDBDatasource ds, SQLQuery stmt, Map<String, AdaptedToService> paramsIn, Set outputMapping, Filters filters, DataIdentifier dataId) { Long oldChecksum = null;//from w w w.j a v a2 s. com if (isConcurrentModificationEnabled()) { oldChecksum = ConflictDetectionUtil.removeChecksum(paramsIn); } String[] inputKeys = null; Map<String, Object> paramIns = new HashMap<String, Object>(); if (paramsIn != null) { paramIns = narrow(paramsIn); inputKeys = (String[]) paramIns.keySet().toArray(new String[paramIns.size()]); } MapSqlParameterSource namedParameters = new MapSqlParameterSource(paramIns); Object result = null; isCountOnly = DataStore.findValue(dataId, DataStore.KEY_WORD_COUNT) != null; String sql = QueryToStringCreator.toString(stmt, namedParameters, inputKeys, outputMapping); Map values = namedParameters.getValues(); if ((values != null) && (values.size() > 0)) { Map replacementMap = new HashMap<String, Object>(); for (String key : inputKeys) { if (values.containsKey(key.toUpperCase())) { replacementMap.put(key, values.get(key.toUpperCase())); } if (values.containsKey(key.toLowerCase())) { replacementMap.put(key, values.get(key.toLowerCase())); } } namedParameters.addValues(replacementMap); } logger.info("Executing SQL: " + sql); SimpleJdbcTemplate template = new SimpleJdbcTemplate(ds.getDataSource()); try { Connection conn = ds.getDataSource().getConnection(); dialect = getDatabaseDialect(conn); DataSourceUtils.releaseConnection(conn, ds.getDataSource()); } catch (SQLException e) { ExceptionHelper.printStackTrace(e); } if (stmt instanceof Select) { result = handleSelect(sql, namedParameters, (Select) stmt, template, filters); if (!isCountOnly && isConcurrentModificationEnabled()) { ConflictDetectionUtil.addChecksums((List<Map<String, Object>>) result, sql); } } else if (stmt instanceof Insert) { result = handleInsert(sql, namedParameters, (Insert) stmt, template); if (isConcurrentModificationEnabled()) { DataStore.store(dataId, DataStore.KEY_SERVICE_MODIFY); } } else if (stmt instanceof SQLOnly) { result = handleQueryTag(sql, namedParameters, template); } else { if (isConcurrentModificationEnabled()) { ConflictDetectionUtil.validateChecksum(template, sql, namedParameters.getValues(), oldChecksum); } template.update(sql, namedParameters); if (isConcurrentModificationEnabled()) { DataStore.store(dataId, DataStore.KEY_SERVICE_MODIFY); } } return result; }
From source file:org.mifos.test.framework.util.DatabaseTestUtils.java
/** * Return the current contents of the specified tables as a DBUnit dataset as XML string. * This method can be invoked safely inside a Spring-managed transaction. * /*from w ww . j a va 2 s . co m*/ * @param dataSource * @param tableNames variable parameter list of table names * @return XML string containing the current contents of the specified tables * @throws IOException * @throws DataSetException * @throws SQLException * @throws DatabaseUnitException */ @SuppressWarnings("PMD.DataflowAnomalyAnalysis") //Rationale: You cannot define new local variables in the try block because the finally block must reference it. public String saveTables(DriverManagerDataSource dataSource, String... tableNames) throws IOException, DataSetException, SQLException, DatabaseUnitException { Connection jdbcConnection = null; try { jdbcConnection = DataSourceUtils.getConnection(dataSource); ByteArrayOutputStream stream = new ByteArrayOutputStream(); FlatXmlDataSet.write(new DatabaseConnection(jdbcConnection).createDataSet(tableNames), stream); return stream.toString(); } finally { if (null != jdbcConnection) { jdbcConnection.close(); } DataSourceUtils.releaseConnection(jdbcConnection, dataSource); } }
From source file:au.org.ala.layers.dao.ObjectDAOImpl.java
public void writeObjectsToCSV(OutputStream output, String fid) throws Exception { String sql = MessageFormat.format("COPY (select o.pid as pid, o.id as id, o.name as name, " + "o.desc as description, " + "ST_AsText(ST_Centroid(o.the_geom)) as centroid, " + "GeometryType(o.the_geom) as featureType from objects o " + "where o.fid = ''{0}'') TO STDOUT WITH CSV HEADER", fid); DataSource ds = (DataSource) applicationContext.getBean("dataSource"); Connection conn = DataSourceUtils.getConnection(ds); try {/*from w ww .j a va2 s.co m*/ BaseConnection baseConn = (BaseConnection) new C3P0NativeJdbcExtractor().getNativeConnection(conn); Writer csvOutput = new OutputStreamWriter(output); CopyManager copyManager = new CopyManager(baseConn); copyManager.copyOut(sql, csvOutput); csvOutput.flush(); conn.close(); } catch (SQLException ex) { // something has failed and we print a stack trace to analyse the error logger.error(ex.getMessage(), ex); // ignore failure closing connection try { conn.close(); } catch (SQLException e) { /*do nothing for failure to close */ } } finally { // properly release our connection DataSourceUtils.releaseConnection(conn, ds); } }