This will typically be the native driver Connection * or a wrapper from a connection pool. * * @return the underlying Connection (never {@code null}) */ Connection getTargetConnection(); } PK Hٺ % src/play/db/DelegatingDataSource.java/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package play.db; import javax.sql.DataSource; import java.io.PrintWriter; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.SQLException; import java.util.logging.Logger; /** * JDBC {@link DataSource} implementation that delegates all calls * to a given target {@link DataSource}. * *
This class is meant to be subclassed, with subclasses overriding only
* those methods (such as {@link #getConnection()}) that should not simply
* delegate to the target DataSource.
*
* @author Juergen Hoeller
* @see #getConnection
* @since 1.1
*/
class DelegatingDataSource implements DataSource {
private DataSource targetDataSource;
/**
* Create a new DelegatingDataSource.
*
* @see #setTargetDataSource
*/
public DelegatingDataSource() {
}
/**
* Create a new DelegatingDataSource.
*
* @param targetDataSource the target DataSource
*/
public DelegatingDataSource(DataSource targetDataSource) {
setTargetDataSource(targetDataSource);
}
/**
* Set the target DataSource that this DataSource should delegate to.
*/
public void setTargetDataSource(DataSource targetDataSource) {
this.targetDataSource = targetDataSource;
}
/**
* Return the target DataSource that this DataSource should delegate to.
*/
public DataSource getTargetDataSource() {
return this.targetDataSource;
}
@Override
public Connection getConnection() throws SQLException {
return getTargetDataSource().getConnection();
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return getTargetDataSource().getConnection(username, password);
}
@Override
public PrintWriter getLogWriter() throws SQLException {
return getTargetDataSource().getLogWriter();
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
getTargetDataSource().setLogWriter(out);
}
@Override
public int getLoginTimeout() throws SQLException {
return getTargetDataSource().getLoginTimeout();
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
getTargetDataSource().setLoginTimeout(seconds);
}
//---------------------------------------------------------------------
// Implementation of JDBC 4.0's Wrapper interface
//---------------------------------------------------------------------
@Override
@SuppressWarnings("unchecked")
public This DataSource proxy allows to avoid fetching JDBC Connections from
* a pool unless actually necessary. JDBC transaction control can happen
* without fetching a Connection from the pool or communicating with the
* database; this will be done lazily on first creation of a JDBC Statement.
*
* If you configure both a LazyConnectionDataSourceProxy and a
* TransactionAwareDataSourceProxy, make sure that the latter is the outermost
* DataSource. In such a scenario, data access code will talk to the
* transaction-aware DataSource, which will in turn work with the
* LazyConnectionDataSourceProxy.
*
* Lazy fetching of physical JDBC Connections is particularly beneficial
* in a generic transaction demarcation environment. It allows you to demarcate
* transactions on all methods that could potentially perform data access,
* without paying a performance penalty if no actual data access happens.
*
* This DataSource proxy gives you behavior analogous to JTA and a
* transactional JNDI DataSource (as provided by the J2EE server), even
* with a local transaction strategy like DataSourceTransactionManager or
* HibernateTransactionManager. It does not add value with Spring's
* JtaTransactionManager as transaction strategy.
*
* Lazy fetching of JDBC Connections is also recommended for read-only
* operations with Hibernate, in particular if the chances of resolving the
* result in the second-level cache are high. This avoids the need to
* communicate with the database at all for such read-only operations.
* You will get the same effect with non-transactional reads, but lazy fetching
* of JDBC Connections allows you to still perform reads in transactions.
*
* NOTE: This DataSource proxy needs to return wrapped Connections
* (which implement the {@link ConnectionProxy} interface) in order to handle
* lazy fetching of an actual JDBC Connection. Therefore, the returned Connections
* cannot be cast to a native JDBC Connection type such as OracleConnection or
* to a connection pool implementation type. Use a corresponding
* or JDBC 4's {@link Connection#unwrap} to retrieve the native JDBC Connection.
*
* @author Juergen Hoeller
*/
public class LazyConnectionDataSourceProxy extends DelegatingDataSource {
private static final Log logger = LogFactory.getLog(LazyConnectionDataSourceProxy.class);
private Boolean defaultAutoCommit;
private Integer defaultTransactionIsolation;
/**
* Create a new LazyConnectionDataSourceProxy.
*
* @see #setTargetDataSource
*/
public LazyConnectionDataSourceProxy() {
}
/**
* Create a new LazyConnectionDataSourceProxy.
*
* @param targetDataSource the target DataSource
*/
public LazyConnectionDataSourceProxy(DataSource targetDataSource) {
setTargetDataSource(targetDataSource);
afterPropertiesSet();
}
/**
* Set the default auto-commit mode to expose when no target Connection
* has been fetched yet (-> actual JDBC Connection default not known yet).
* If not specified, the default gets determined by checking a target
* Connection on startup. If that check fails, the default will be determined
* lazily on first access of a Connection.
*
* @see Connection#setAutoCommit
*/
public void setDefaultAutoCommit(boolean defaultAutoCommit) {
this.defaultAutoCommit = defaultAutoCommit;
}
/**
* Set the default transaction isolation level to expose when no target Connection
* has been fetched yet (-> actual JDBC Connection default not known yet).
* This property accepts the int constant value (e.g. 8) as defined in the
* {@link Connection} interface; it is mainly intended for programmatic
* use. Consider using the "defaultTransactionIsolationName" property for setting
* the value by name (e.g. "TRANSACTION_SERIALIZABLE").
* If not specified, the default gets determined by checking a target
* Connection on startup. If that check fails, the default will be determined
* lazily on first access of a Connection.
*
* @see Connection#setTransactionIsolation
*/
public void setDefaultTransactionIsolation(int defaultTransactionIsolation) {
this.defaultTransactionIsolation = defaultTransactionIsolation;
}
public void afterPropertiesSet() {
// Determine default auto-commit and transaction isolation
// via a Connection from the target DataSource, if possible.
if (this.defaultAutoCommit == null || this.defaultTransactionIsolation == null) {
try {
Connection con = getTargetDataSource().getConnection();
try {
checkDefaultConnectionProperties(con);
}
finally {
con.close();
}
}
catch (SQLException ex) {
logger.warn("Could not retrieve default auto-commit and transaction isolation settings", ex);
}
}
}
/**
* Check the default connection properties (auto-commit, transaction isolation),
* keeping them to be able to expose them correctly without fetching an actual
* JDBC Connection from the target DataSource.
* This will be invoked once on startup, but also for each retrieval of a
* target Connection. If the check failed on startup (because the database was
* down), we'll lazily retrieve those settings.
*
* @param con the Connection to use for checking
* @throws SQLException if thrown by Connection methods
*/
protected synchronized void checkDefaultConnectionProperties(Connection con) throws SQLException {
if (this.defaultAutoCommit == null) {
this.defaultAutoCommit = con.getAutoCommit();
}
if (this.defaultTransactionIsolation == null) {
this.defaultTransactionIsolation = con.getTransactionIsolation();
}
}
/**
* Expose the default auto-commit value.
*/
protected Boolean defaultAutoCommit() {
return this.defaultAutoCommit;
}
/**
* Expose the default transaction isolation value.
*/
protected Integer defaultTransactionIsolation() {
return this.defaultTransactionIsolation;
}
/**
* Return a Connection handle that lazily fetches an actual JDBC Connection
* when asked for a Statement (or PreparedStatement or CallableStatement).
* The returned Connection handle implements the ConnectionProxy interface,
* allowing to retrieve the underlying target Connection.
*
* @return a lazy Connection handle
* @see ConnectionProxy#getTargetConnection()
*/
@Override
public Connection getConnection() throws SQLException {
return (Connection) Proxy.newProxyInstance(
ConnectionProxy.class.getClassLoader(),
new Class>[]{ConnectionProxy.class},
new LazyConnectionInvocationHandler());
}
/**
* Return a Connection handle that lazily fetches an actual JDBC Connection
* when asked for a Statement (or PreparedStatement or CallableStatement).
* The returned Connection handle implements the ConnectionProxy interface,
* allowing to retrieve the underlying target Connection.
*
* @param username the per-Connection username
* @param password the per-Connection password
* @return a lazy Connection handle
* @see ConnectionProxy#getTargetConnection()
*/
@Override
public Connection getConnection(String username, String password) throws SQLException {
return (Connection) Proxy.newProxyInstance(
ConnectionProxy.class.getClassLoader(),
new Class>[]{ConnectionProxy.class},
new LazyConnectionInvocationHandler(username, password));
}
/**
* Invocation handler that defers fetching an actual JDBC Connection
* until first creation of a Statement.
*/
private class LazyConnectionInvocationHandler implements InvocationHandler {
private String username;
private String password;
private Boolean readOnly = Boolean.FALSE;
private Integer transactionIsolation;
private Boolean autoCommit;
private boolean closed = false;
private Connection target;
public LazyConnectionInvocationHandler() {
this.autoCommit = defaultAutoCommit();
this.transactionIsolation = defaultTransactionIsolation();
}
public LazyConnectionInvocationHandler(String username, String password) {
this();
this.username = username;
this.password = password;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// Invocation on ConnectionProxy interface coming in...
if (method.getName().equals("equals")) {
// We must avoid fetching a target Connection for "equals".
// Only consider equal when proxies are identical.
return (proxy == args[0]);
}
else if (method.getName().equals("hashCode")) {
// We must avoid fetching a target Connection for "hashCode",
// and we must return the same hash code even when the target
// Connection has been fetched: use hashCode of Connection proxy.
return System.identityHashCode(proxy);
}
else if (method.getName().equals("unwrap")) {
if (((Class>) args[0]).isInstance(proxy)) {
return proxy;
}
}
else if (method.getName().equals("isWrapperFor")) {
if (((Class>) args[0]).isInstance(proxy)) {
return true;
}
}
else if (method.getName().equals("getTargetConnection")) {
// Handle getTargetConnection method: return underlying connection.
return getTargetConnection(method);
}
if (!hasTargetConnection()) {
// No physical target Connection kept yet ->
// resolve transaction demarcation methods without fetching
// a physical JDBC Connection until absolutely necessary.
if (method.getName().equals("toString")) {
return "Lazy Connection proxy for target DataSource [" + getTargetDataSource() + "]";
}
else if (method.getName().equals("isReadOnly")) {
return this.readOnly;
}
else if (method.getName().equals("setReadOnly")) {
this.readOnly = (Boolean) args[0];
return null;
}
else if (method.getName().equals("getTransactionIsolation")) {
if (this.transactionIsolation != null) {
return this.transactionIsolation;
}
// Else fetch actual Connection and check there,
// because we didn't have a default specified.
}
else if (method.getName().equals("setTransactionIsolation")) {
this.transactionIsolation = (Integer) args[0];
return null;
}
else if (method.getName().equals("getAutoCommit")) {
if (this.autoCommit != null) {
return this.autoCommit;
}
// Else fetch actual Connection and check there,
// because we didn't have a default specified.
}
else if (method.getName().equals("setAutoCommit")) {
this.autoCommit = (Boolean) args[0];
return null;
}
else if (method.getName().equals("commit")) {
// Ignore: no statements created yet.
return null;
}
else if (method.getName().equals("rollback")) {
// Ignore: no statements created yet.
return null;
}
else if (method.getName().equals("getWarnings")) {
return null;
}
else if (method.getName().equals("clearWarnings")) {
return null;
}
else if (method.getName().equals("close")) {
this.closed = true;
return null;
}
else if (method.getName().equals("isClosed")) {
return this.closed;
}
else if (this.closed) {
// Connection proxy closed, without ever having fetched a
// physical JDBC Connection: throw corresponding SQLException.
throw new SQLException("Illegal operation: connection is closed");
}
}
// Target Connection already fetched,
// or target Connection necessary for current operation ->
// invoke method on target connection.
try {
return method.invoke(getTargetConnection(method), args);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
/**
* Return whether the proxy currently holds a target Connection.
*/
private boolean hasTargetConnection() {
return (this.target != null);
}
/**
* Return the target Connection, fetching it and initializing it if necessary.
*/
private Connection getTargetConnection(Method operation) throws SQLException {
if (this.target == null) {
// No target Connection held -> fetch one.
if (logger.isDebugEnabled()) {
logger.debug("Connecting to database for operation '" + operation.getName() + "'");
}
// Fetch physical Connection from DataSource.
this.target = (this.username != null) ?
getTargetDataSource().getConnection(this.username, this.password) :
getTargetDataSource().getConnection();
// If we still lack default connection properties, check them now.
checkDefaultConnectionProperties(this.target);
// Apply kept transaction settings, if any.
if (this.readOnly) {
try {
this.target.setReadOnly(this.readOnly);
}
catch (Exception ex) {
// "read-only not supported" -> ignore, it's just a hint anyway
logger.debug("Could not set JDBC Connection read-only", ex);
}
}
if (this.transactionIsolation != null &&
!this.transactionIsolation.equals(defaultTransactionIsolation())) {
this.target.setTransactionIsolation(this.transactionIsolation);
}
if (this.autoCommit != null && this.autoCommit != this.target.getAutoCommit()) {
this.target.setAutoCommit(this.autoCommit);
}
}
else {
// Target Connection already held -> return it.
if (logger.isDebugEnabled()) {
logger.debug("Using existing database connection for operation '" + operation.getName() + "'");
}
}
return this.target;
}
}
}
PK Hm!
!
+ src/play/db/OracleConnectionCustomizer.javapackage play.db;
import com.mchange.v2.c3p0.ConnectionCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import play.mvc.Http;
import play.mvc.Scope;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import static org.apache.commons.lang.StringUtils.substring;
/**
* Can be used with C3P0 in order to see who is using Oracle connections on the DB side (End to End metrics)
*/
public class OracleConnectionCustomizer implements ConnectionCustomizer {
private static final Logger logger = LoggerFactory.getLogger(OracleConnectionCustomizer.class);
private int arrayLength;
private int actionIndex;
private int moduleIndex;
private int clientIdIndex;
private Method setEndToEndMetrics;
public OracleConnectionCustomizer() {
try {
Class connClass = Class.forName("oracle.jdbc.driver.OracleConnection");
arrayLength = (Integer) connClass.getField("END_TO_END_STATE_INDEX_MAX").get(null);
actionIndex = (Integer) connClass.getField("END_TO_END_ACTION_INDEX").get(null);
moduleIndex = (Integer) connClass.getField("END_TO_END_MODULE_INDEX").get(null);
clientIdIndex = (Integer) connClass.getField("END_TO_END_CLIENTID_INDEX").get(null);
setEndToEndMetrics = connClass.getMethod("setEndToEndMetrics", String[].class, short.class);
setEndToEndMetrics.setAccessible(true);
}
catch (Exception e) {
logger.warn("Cannot access OracleConnection fields", e);
}
}
@Override public void onAcquire(Connection conn, String s) {
}
@Override public void onDestroy(Connection conn, String s) {
}
@Override public void onCheckOut(Connection conn, String s) {
if (setEndToEndMetrics == null) return;
try {
String[] e2eMetrics = new String[arrayLength];
Http.Request request = Http.Request.current();
e2eMetrics[actionIndex] = request != null ? (String) request.args.get("requestId") : null; // set by RequestLogPlugin
e2eMetrics[moduleIndex] = substring("IBANK/" + Thread.currentThread().getName(), 0, 64);
Scope.Session session = Scope.Session.current();
e2eMetrics[clientIdIndex] = session != null ? session.get("username") : null;
setEndToEndMetrics.invoke(conn, e2eMetrics, (short) 0);
}
catch (InvocationTargetException e) {
logger.warn("Cannot set Oracle end-to-end metrics", e.getCause());
}
catch (Exception e) {
logger.warn("Cannot set Oracle end-to-end metrics", e);
}
}
@Override public void onCheckIn(Connection conn, String s) {
}
}
PK JHWqO qO lib/play-db.jarPK
JH META-INF/ PK
JH> META-INF/MANIFEST.MFM= F %:nmJBP'