List of usage examples for org.springframework.jdbc.datasource DataSourceUtils getConnection
public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException
From source file:com.p5solutions.core.jpa.orm.oracle.ConversionUtilityImpl.java
/** * If blob./* w w w .ja va 2 s .co m*/ * * @param pb * the pb * @param value * the value * @return the object */ protected Object toSqlBlob(ParameterBinder pb, Object value) { if (value == null) { return null; } int type = getSqlType(pb); // if the sql target type is blob if (Types.BLOB == type) { Class<?> clazz = value.getClass(); boolean isByteArray = ReflectionUtility.isByteArray(clazz); boolean isBlob = isByteArray ? false : ReflectionUtility.isBlob(clazz); boolean isString = isByteArray | isBlob ? false : ReflectionUtility.isBlob(clazz); boolean isInputStream = isByteArray | isBlob | isString ? false : ReflectionUtility.isStringClass(clazz); // if the datasource is not set, then throw an error if (dataSource == null) { logger.error("Required datasource has not been set for " // + getClass() + ", when dealing with Lob values, datasource " // + "is required for creation of lob space in DB."); return null; } // scope variables BLOB blob = null; OutputStream os = null; // get a database connection Connection conn = DataSourceUtils.getConnection(dataSource); try { // activate the connection and create an empty blob pointer blob = BLOB.createTemporary(conn, false, BLOB.DURATION_SESSION); blob.open(BLOB.MODE_READWRITE); os = blob.setBinaryStream(0); } catch (Exception e) { logger.error("Unable to create temporary blob when accessing entity " + pb.getEntityClass() + " on paramater " + pb.getBindingPath() + " and column " + pb.getColumnName()); blob = null; os = null; return null; } InputStream is = null; // if the source is of type byte[] if (isByteArray) { blob.setBytes((byte[]) value); } else if (isBlob) { Blob sourceBlob = (Blob) value; try { is = sourceBlob.getBinaryStream(); } catch (Exception e) { logger.error( "Unable to copy input stream to output when accessing entity " + pb.getEntityClass() + " on paramater " + pb.getBindingPath() + " and column " + pb.getColumnName()); is = null; } } else if (isString) { String v = (String) value; blob.setBytes(v.getBytes()); } else if (isInputStream) { is = (InputStream) value; } // if the input stream is set if (is != null) { try { IOUtils.copy(is, os); } catch (Exception e) { logger.error( "Unable to copy input stream to output when accessing entity " + pb.getEntityClass() + " on paramater " + pb.getBindingPath() + " and column " + pb.getColumnName()); } } if (os != null) { try { os.close(); blob.close(); } catch (Exception e) { logger.error("Unable to close stream properly when accessing entity " + pb.getEntityClass() + " on paramater " + pb.getBindingPath() + " and column " + pb.getColumnName()); } } return blob; } return null; }
From source file:com.baoqilai.core.dao.BaseJdbcDao.java
/** * Get a JDBC Connection, either from the current transaction or a new one. * // w w w . j av a2 s .c o m * @return the JDBC Connection * @throws CannotGetJdbcConnectionException * if the attempt to get a Connection failed * @see org.springframework.jdbc.datasource.DataSourceUtils#getConnection(javax.sql.DataSource) */ protected final Connection getConnection() throws CannotGetJdbcConnectionException { return DataSourceUtils.getConnection(getDataSource()); }
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 www. jav a2s . co 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.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 ava 2 s.c om*/ // 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: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 *//* ww w . j a v a 2 s . c o m*/ 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:com.jfinal.plugin.activerecord.Config.java
/** * Get Connection. Support transaction if Connection in ThreadLocal *///from www.j av a2 s. c om public final Connection getConnection() throws SQLException { // Connection conn = threadLocal.get(); // if (conn != null) // return conn; // return showSql ? new SqlReporter(dataSource.getConnection()).getConnection() : dataSource.getConnection(); return DataSourceUtils.getConnection(dataSource); }
From source file:uk.org.rbc1b.roms.controller.report.ReportsController.java
private ReportResults extractResults(String sql) throws SQLException { Connection con = DataSourceUtils.getConnection(dataSource); Statement s = con.createStatement(); ResultSet rs = s.executeQuery(sql); ReportResults reportResults = new ReportResults(); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); List<Integer> columnTypeIds = new ArrayList<Integer>(); for (int i = 0; i < columnCount; i++) { columnTypeIds.add(rsmd.getColumnType(i + 1)); }//from w w w.j ava 2 s . co m reportResults.columnNames = new ArrayList<String>(); for (int i = 0; i < columnCount; i++) { reportResults.columnNames.add(rsmd.getColumnLabel(i + 1)); } reportResults.resultRows = new ArrayList<List<String>>(); while (rs.next()) { List<String> resultRow = new ArrayList<String>(); for (int i = 0; i < columnCount; i++) { Integer columnTypeId = columnTypeIds.get(i); if (columnTypeId.intValue() == Types.BOOLEAN || columnTypeId.intValue() == Types.BIT) { resultRow.add(Boolean.valueOf(rs.getBoolean(i + 1)).toString()); } else { resultRow.add(rs.getString(i + 1)); } } reportResults.resultRows.add(resultRow); } return reportResults; }
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//ww w. ja v a 2 s . c o 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.jfinal.plugin.activerecord.Config.java
/** * Helps to implement nested transaction. * Tx.intercept(...) and Db.tx(...) need this method to detected if it in nested transaction. *//*from w ww. j ava2 s. c o m*/ public final Connection getThreadLocalConnection() { return DataSourceUtils.getConnection(dataSource); }