List of usage examples for org.springframework.jdbc.datasource DataSourceUtils getConnection
public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException
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 ww w . j a va 2s.com*/ * @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:es.upm.fiware.rss.common.test.DatabaseLoader.java
/** * Method to insert data before test. throws Exception from DB. * /*from www . j a v a 2 s .co m*/ * @throws Exception * the exception */ public void init() throws Exception { DatabaseLoader.logger.debug("DatabaseLoader.init()"); try { DatabaseLoader.logger.debug("starting init() in DatabaseLoader..."); this.dbConn = new DatabaseConnection(DataSourceUtils.getConnection(dataSource), this.schema); DatabaseConfig config = dbConn.getConfig(); config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new MySqlDataTypeFactory()); config.setProperty(DatabaseConfig.PROPERTY_METADATA_HANDLER, new MySqlMetadataHandler()); config.setProperty(DatabaseConfig.FEATURE_CASE_SENSITIVE_TABLE_NAMES, Boolean.TRUE); DatabaseLoader.logger.debug("DATASOURCE." + dataSource.toString()); this.loader = new FlatXmlDataSetBuilder(); dbConn.getConnection().createStatement().execute("DELETE FROM dbe_transaction"); deleteAll("dbunit/CREATE_DATATEST_III.xml", false); deleteAll("dbunit/CREATE_DATATEST_II.xml", false); deleteAll("dbunit/CREATE_DATATEST_I.xml", false); cleanInsert("dbunit/CREATE_DATATEST_I.xml", false); cleanInsert("dbunit/CREATE_DATATEST_II.xml", false); cleanInsert("dbunit/CREATE_DATATEST_III.xml", true); DatabaseLoader.logger.debug("ending init() in DatabaseLoader..."); } catch (Exception e) { DatabaseLoader.logger.error("Error loading data init in DatabaseLoader"); dbConn.getConnection().rollback(); e.printStackTrace(); throw e; } }
From source file:com.bt.aloha.testing.JdbcHelper.java
protected int executeUpdate(DataSource ds, String createScript) throws SQLException { Connection conn = null;//from w ww .j a va 2 s. c o m Statement st = null; int rowCount = -1; try { conn = DataSourceUtils.getConnection(ds); st = conn.createStatement(); rowCount = st.executeUpdate(createScript); assert rowCount > 0; } catch (SQLException e) { log.warn("Unable to execute create sctipt: " + e.getMessage()); } finally { try { if (st != null) st.close(); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (conn != null) DataSourceUtils.releaseConnection(conn, ds); } } return rowCount; }
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 ww w .j ava 2 s . 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.mifos.test.framework.util.DatabaseTestUtils.java
private void cleanAndInsertDataSet(DriverManagerDataSource dataSource, IDataSet dataSet) throws DatabaseUnitException, SQLException { Connection jdbcConnection = null; ReplacementDataSet replacementDataSet = getDataSetWithNullsReplaced(dataSet); try {//from www . jav a 2s .c o m jdbcConnection = DataSourceUtils.getConnection(dataSource); IDatabaseConnection databaseConnection = new DatabaseConnection(jdbcConnection); DatabaseOperation.CLEAN_INSERT.execute(databaseConnection, replacementDataSet); } finally { if (null != jdbcConnection) { jdbcConnection.close(); } DataSourceUtils.releaseConnection(jdbcConnection, dataSource); } }
From source file:es.upm.fiware.rss.expenditureLimit.processing.test.ProcessingLimitServiceTest.java
/** * @throws Exception/*from ww w . j av a2 s .c o m*/ */ @After public void tearDown() throws Exception { FlatXmlDataSetBuilder loader = new FlatXmlDataSetBuilder(); IDatabaseConnection dbConn = new DatabaseConnection(DataSourceUtils.getConnection(dataSource), this.schema); URL url = this.getClass().getClassLoader().getResource("dbunit/CREATE_DATATEST_EXPLIMIT.xml"); IDataSet ds = loader.build(url); DatabaseOperation.DELETE_ALL.execute(dbConn, ds); dbConn.getConnection().commit(); }
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 ww .jav a 2 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.hengdao.utils.SqlSessionUtils.java
/** * If a Spring transaction is active it uses {@code DataSourceUtils} to get * a Spring managed {@code Connection}, then creates a new * {@code SqlSession} with this connection and synchronizes it with the * transaction. If there is not an active transaction it gets a connection * directly from the {@code DataSource} and creates a {@code SqlSession} * with it.//from w w w .j a v a2 s .co m * * @param sessionFactory * a MyBatis {@code SqlSessionFactory} to create new sessions * @param executorType * The executor type of the SqlSession to create * @param exceptionTranslator * Optional. Translates SqlSession.commit() exceptions to Spring * exceptions. * @throws TransientDataAccessResourceException * if a transaction is active and the {@code SqlSessionFactory} * is not using a {@code SpringManagedTransactionFactory} * @see SpringManagedTransactionFactory */ public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) { Assert.notNull(sessionFactory, "No SqlSessionFactory specified"); Assert.notNull(executorType, "No ExecutorType specified"); SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); if (holder != null && holder.isSynchronizedWithTransaction()) { if (holder.getExecutorType() != executorType) { throw new TransientDataAccessResourceException( "Cannot change the ExecutorType when there is an existing transaction"); } holder.requested(); if (logger.isDebugEnabled()) { logger.debug("Fetched SqlSession [" + holder.getSqlSession() + "] from current transaction"); } return holder.getSqlSession(); } DataSource dataSource = sessionFactory.getConfiguration().getEnvironment().getDataSource(); // SqlSessionFactoryBean unwraps TransactionAwareDataSourceProxies but // we keep this check for the case that SqlSessionUtils is called from // custom code boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy); Connection conn; try { conn = transactionAware ? dataSource.getConnection() : DataSourceUtils.getConnection(dataSource); } catch (SQLException e) { throw new CannotGetJdbcConnectionException("Could not get JDBC Connection for SqlSession", e); } if (logger.isDebugEnabled()) { logger.debug("Creating SqlSession with JDBC Connection [" + conn + "]"); } // Assume either DataSourceTransactionManager or the underlying // connection pool already dealt with enabling auto commit. // This may not be a good assumption, but the overhead of checking // connection.getAutoCommit() again may be expensive (?) in some drivers // (see DataSourceTransactionManager.doBegin()). One option would be to // only check for auto commit if this function is being called outside // of DSTxMgr, but to do that we would need to be able to call // ConnectionHolder.isTransactionActive(), which is protected and not // visible to this class. SqlSession session = sessionFactory.openSession(executorType, conn); // Register session holder and bind it to enable synchronization. // // Note: The DataSource should be synchronized with the transaction // either through DataSourceTxMgr or another tx synchronization. // Further assume that if an exception is thrown, whatever started the // transaction will // handle closing / rolling back the Connection associated with the // SqlSession. if (TransactionSynchronizationManager.isSynchronizationActive()) { if (!(sessionFactory.getConfiguration().getEnvironment() .getTransactionFactory() instanceof SpringManagedTransactionFactory) && DataSourceUtils.isConnectionTransactional(conn, dataSource)) { throw new TransientDataAccessResourceException( "SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization"); } if (logger.isDebugEnabled()) { logger.debug("Registering transaction synchronization for SqlSession [" + session + "]"); } holder = new SqlSessionHolder(session, executorType, exceptionTranslator); TransactionSynchronizationManager.bindResource(sessionFactory, holder); TransactionSynchronizationManager .registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory)); holder.setSynchronizedWithTransaction(true); holder.requested(); } else { if (logger.isDebugEnabled()) { logger.debug("SqlSession [" + session + "] was not registered for synchronization because synchronization is not active"); } } return session; }
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; }