db-ojb-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From arm...@apache.org
Subject cvs commit: jakarta-ojb/src/java/org/apache/ojb/broker/accesslayer ConnectionFactoryPooledImpl.java ConnectionFactoryNotPooledImpl.java ConnectionFactoryManagedImpl.java ConnectionFactoryDBCPImpl.java ConnectionFactoryAbstractImpl.java ConnectionManagerIF.java ConnectionManager.java ConnectionFactoryFactory.java ConnectionFactory.java
Date Thu, 28 Nov 2002 22:25:53 GMT
arminw      2002/11/28 14:25:53

  Modified:    src/java/org/apache/ojb/broker/accesslayer
                        ConnectionManagerIF.java ConnectionManager.java
                        ConnectionFactoryFactory.java
                        ConnectionFactory.java
  Added:       src/java/org/apache/ojb/broker/accesslayer
                        ConnectionFactoryPooledImpl.java
                        ConnectionFactoryNotPooledImpl.java
                        ConnectionFactoryManagedImpl.java
                        ConnectionFactoryDBCPImpl.java
                        ConnectionFactoryAbstractImpl.java
  Log:
  remove unused methods, improve connection
  pooling
  
  Revision  Changes    Path
  1.5       +12 -20    jakarta-ojb/src/java/org/apache/ojb/broker/accesslayer/ConnectionManagerIF.java
  
  Index: ConnectionManagerIF.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/accesslayer/ConnectionManagerIF.java,v
  retrieving revision 1.4
  retrieving revision 1.5
  diff -u -r1.4 -r1.5
  --- ConnectionManagerIF.java	25 Jul 2002 17:06:57 -0000	1.4
  +++ ConnectionManagerIF.java	28 Nov 2002 22:25:53 -0000	1.5
  @@ -54,28 +54,20 @@
    * <http://www.apache.org/>.
    */
   
  -import org.apache.ojb.broker.PersistenceBrokerException;
  -import org.apache.ojb.broker.metadata.ClassDescriptor;
  -
   import java.sql.Connection;
   
   public interface ConnectionManagerIF
   {
  -	/**
	 * return a Connection for the given ClassDescriptor cld.
	 * @param cld the ClassDescriptor
to look up
	 * @return the resulting Connection object
  -     *
  -     * @deprecated use {@link #getConnection} instead
	 */
  -	Connection getConnectionForClassDescriptor(ClassDescriptor cld) throws PersistenceBrokerException;
  -
  -	/**
  -	 * checks if Connection conn is still open.
  -	 * returns true, if connection is open, else false.
  -	 */
  -	boolean isAlive(Connection conn);
  +    /**
  +     * checks if Connection conn is still open.
  +     * returns true, if connection is open, else false.
  +     */
  +    boolean isAlive(Connection conn);
   
       /**
  -	 * Return a connection.
  -	 */
  -	public Connection getConnection() throws LookupException;
  +     * Return a connection.
  +     */
  +    public Connection getConnection() throws LookupException;
   
       /**
        * Hold connection is in local transaction.
  @@ -98,8 +90,8 @@
        */
       public void localRollback();
   
  -	/**
  -	 * Release the hold connection.
  -	 */
  -	public void releaseConnection();
  +    /**
  +     * Release the hold connection.
  +     */
  +    public void releaseConnection();
   }
  
  
  
  1.14      +15 -58    jakarta-ojb/src/java/org/apache/ojb/broker/accesslayer/ConnectionManager.java
  
  Index: ConnectionManager.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/accesslayer/ConnectionManager.java,v
  retrieving revision 1.13
  retrieving revision 1.14
  diff -u -r1.13 -r1.14
  --- ConnectionManager.java	5 Oct 2002 22:32:14 -0000	1.13
  +++ ConnectionManager.java	28 Nov 2002 22:25:53 -0000	1.14
  @@ -54,16 +54,12 @@
    * <http://www.apache.org/>.
    */
   
  -import java.sql.Connection;
  -import java.sql.SQLException;
  -
   import org.apache.ojb.broker.PBKey;
   import org.apache.ojb.broker.PersistenceBroker;
   import org.apache.ojb.broker.PersistenceBrokerException;
   import org.apache.ojb.broker.TransactionAbortedException;
   import org.apache.ojb.broker.TransactionInProgressException;
   import org.apache.ojb.broker.TransactionNotInProgressException;
  -import org.apache.ojb.broker.metadata.ClassDescriptor;
   import org.apache.ojb.broker.metadata.JdbcConnectionDescriptor;
   import org.apache.ojb.broker.platforms.Platform;
   import org.apache.ojb.broker.platforms.PlatformConfiguration;
  @@ -75,13 +71,16 @@
   import org.apache.ojb.broker.util.logging.Logger;
   import org.apache.ojb.broker.util.logging.LoggerFactory;
   
  +import java.sql.Connection;
  +import java.sql.SQLException;
  +
   /**
    * Manages Connection ressources.
    *
    * @author: Thomas Mahler
    * @version $Id$
    */
  -public class ConnectionManager implements ConnectionManagerIF , Configurable
  +public class ConnectionManager implements ConnectionManagerIF, Configurable
   {
       private Logger log = LoggerFactory.getLogger(ConnectionManager.class);
       private PersistenceBroker broker = null;
  @@ -93,13 +92,13 @@
       private int useAutoCommit;
       private boolean originalAutoCommitState;
       private boolean isInLocalTransaction;
  -    public static int CONN_COUNT = 0;
  +
       public ConnectionManager(PersistenceBroker broker)
       {
           this.broker = broker;
           this.pbKey = broker.getPBKey();
           this.jcd = broker.getDescriptorRepository().getDefaultJdbcConnection();
  -        this.connectionFactory = ConnectionFactoryFactory.getConnectionFactory(jcd);
  +        this.connectionFactory = ConnectionFactoryFactory.getInstance();
           this.platform = PlatformFactory.getPlatformFor(jcd);
           OjbConfigurator.getInstance().configure(this);
       }
  @@ -110,47 +109,6 @@
       }
   
       /**
  -     *
  -     * @param cld the ClassDescriptor to look up
  -     * @return the resulting Connection object
  -     *
  -     * @deprecated
  -     */
  -    public Connection getConnectionForClassDescriptor(ClassDescriptor cld)
  -            throws PersistenceBrokerException
  -    {
  -        if (con == null || !isAlive(con))
  -        {
  -            JdbcConnectionDescriptor jcd = cld.getConnectionDescriptor();
  -            try
  -            {
  -                CONN_COUNT++;
  -                con = this.connectionFactory.lookupConnection(jcd);
  -            }
  -            catch (LookupException e)
  -            {
  -                throw new PersistenceBrokerException("Connection lookup failed", e);
  -            }
  -            if (con == null)
  -            {
  -                log.error("Cannot obtain connection from the connection factory");
  -                throw new PersistenceBrokerException("Cannot get connection for ClassDescriptor
" + cld);
  -            }
  -            try
  -            {
  -                this.originalAutoCommitState = con.getAutoCommit();
  -            }
  -            catch (SQLException e)
  -            {
  -                log.error("Cannot check autoCommit state",e);
  -                throw new PersistenceBrokerException("Cannot request autoCommit state on
the connection");
  -            }
  -            if (log.isDebugEnabled()) log.debug("Request new connection from ConnectionFactory:
"+con);
  -        }
  -        return con;
  -    }
  -
  -    /**
        * Returns the underlying connection, requested at the
        * {@link org.apache.ojb.broker.accesslayer.ConnectionFactory}.
        */
  @@ -158,9 +116,8 @@
       {
           if (con == null || !isAlive(con))
           {
  -            CONN_COUNT++;
               con = this.connectionFactory.lookupConnection(jcd);
  -            if (con == null) throw new PersistenceBrokerException("Cannot get connection");
  +            if (con == null) throw new PersistenceBrokerException("Cannot get connection
for " + jcd);
               try
               {
                   this.originalAutoCommitState = con.getAutoCommit();
  @@ -169,7 +126,7 @@
               {
                   throw new PersistenceBrokerException("Cannot request autoCommit state on
the connection");
               }
  -            if (log.isDebugEnabled()) log.debug("Request new connection from ConnectionFactory:
"+con);
  +            if (log.isDebugEnabled()) log.debug("Request new connection from ConnectionFactory:
" + con);
           }
           return con;
       }
  @@ -193,9 +150,9 @@
           {
               log.error("Can't get connection", e);
           }
  -        if(platform.useAutoCommit() == Platform.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE)
  +        if (platform.useAutoCommit() == Platform.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE)
           {
  -            if(log.isDebugEnabled()) log.debug("Try to change autoCommit state to 'false'");
  +            if (log.isDebugEnabled()) log.debug("Try to change autoCommit state to 'false'");
               platform.changeAutoCommitState(connection, false);
           }
           this.isInLocalTransaction = true;
  @@ -225,7 +182,7 @@
           finally
           {
               this.isInLocalTransaction = false;
  -            if(platform.useAutoCommit() == Platform.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE
&&
  +            if (platform.useAutoCommit() == Platform.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE
&&
                       originalAutoCommitState == true)
               {
                   platform.changeAutoCommitState(con, true);
  @@ -239,7 +196,7 @@
        */
       public void localRollback()
       {
  -        log.info("Rollback was called, do rollback on current connection "+con);
  +        log.info("Rollback was called, do rollback on current connection " + con);
           if (!this.isInLocalTransaction)
           {
               throw new PersistenceBrokerException("Not in transaction, cannot abort");
  @@ -257,7 +214,7 @@
           }
           finally
           {
  -            if(platform.useAutoCommit() == Platform.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE
&&
  +            if (platform.useAutoCommit() == Platform.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE
&&
                       originalAutoCommitState == true)
               {
                   platform.changeAutoCommitState(con, true);
  @@ -301,5 +258,5 @@
           this.connectionFactory.releaseConnection(this.jcd, this.con);
           this.con = null;
       }
  -    
  +
   }
  
  
  
  1.6       +15 -97    jakarta-ojb/src/java/org/apache/ojb/broker/accesslayer/ConnectionFactoryFactory.java
  
  Index: ConnectionFactoryFactory.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/accesslayer/ConnectionFactoryFactory.java,v
  retrieving revision 1.5
  retrieving revision 1.6
  diff -u -r1.5 -r1.6
  --- ConnectionFactoryFactory.java	21 Sep 2002 15:35:14 -0000	1.5
  +++ ConnectionFactoryFactory.java	28 Nov 2002 22:25:53 -0000	1.6
  @@ -54,18 +54,17 @@
    * <http://www.apache.org/>.
    */
   
  -import java.util.HashMap;
  -import java.util.Iterator;
  -import java.util.Map;
  -
  -import org.apache.ojb.broker.PersistenceBrokerException;
  +import org.apache.ojb.broker.OJBRuntimeException;
   import org.apache.ojb.broker.PersistenceBrokerFactory;
  -import org.apache.ojb.broker.metadata.JdbcConnectionDescriptor;
   import org.apache.ojb.broker.singlevm.PersistenceBrokerConfiguration;
   import org.apache.ojb.broker.util.logging.LoggerFactory;
   
  +import java.util.HashMap;
  +import java.util.Map;
  +
   /**
    * Factory for {@link org.apache.ojb.broker.accesslayer.ConnectionFactory} implementations.
  + *
    * @version $Id$
    */
   public class ConnectionFactoryFactory
  @@ -74,107 +73,26 @@
       public static ConnectionFactory defaultConnFactory = null;
       public static Map factoryInstances = new HashMap();
   
  -    /**
  -     * @deprecated use {@link ConnectionFactoryFactory#getConnectionFactory(JdbcConnectionDescriptor
jcd)}
  -     */
  -    public static synchronized ConnectionFactory getConnectionFactory()
  -    {
  -        if (defaultConnFactory == null)
  -        {
  -            try
  -            {
  -                PersistenceBrokerConfiguration config =
  -                    (PersistenceBrokerConfiguration) PersistenceBrokerFactory.getConfigurator().getConfigurationFor(
  -                        null);
  -                Class clazz = config.getConnectionFactoryClass();
  -                defaultConnFactory = (ConnectionFactory) clazz.newInstance();
  -            }
  -            catch (Exception e)
  -            {
  -                defaultConnFactory = new ConnectionFactoryDefaultImpl();
  -            }
  -        }
  -        return defaultConnFactory;
  -    }
  +    private static ConnectionFactory singleton;
   
  -    private static ConnectionFactory defaultConnectionFactory()
  +    public static ConnectionFactory getInstance()
       {
  -        if (defaultConnFactory == null)
  +        if (singleton == null)
           {
               try
               {
                   PersistenceBrokerConfiguration config =
  -                    (PersistenceBrokerConfiguration) PersistenceBrokerFactory.getConfigurator().getConfigurationFor(
  -                        null);
  +                        (PersistenceBrokerConfiguration) PersistenceBrokerFactory.getConfigurator().getConfigurationFor(
  +                                null);
                   Class clazz = config.getConnectionFactoryClass();
  -                defaultConnFactory = (ConnectionFactory) clazz.newInstance();
  +                singleton = (ConnectionFactory) clazz.newInstance();
               }
               catch (Exception e)
               {
  -                LoggerFactory.getDefaultLogger().error(
  -                        "Cannot instantiate default connection factory, use default one",
e);
  -                defaultConnFactory = new ConnectionFactoryDefaultImpl();
  -            }
  -        }
  -        return defaultConnFactory;
  -    }
  -
  -    /**
  -     * Returns a {@link ConnectionFactory} for the given
  -     * {@link org.apache.ojb.broker.metadata.JdbcConnectionDescriptor}.
  -     * @param jcd descriptor contains connection factory implementation class. If jcd <i>null</i>
  -     * the default ConnectionFactory, specified in the runtime configuration.
  -     *
  -     */
  -    public static synchronized ConnectionFactory getConnectionFactory(JdbcConnectionDescriptor
jcd)
  -    {
  -        if(jcd == null) return defaultConnectionFactory();
  -
  -        Class conFacClass;
  -        conFacClass = jcd.getConnectionPoolDescriptor().getConnectionFactory();
  -        if(conFacClass == null) return defaultConnectionFactory();
  -        else
  -        {
  -            ConnectionFactory conFac = (ConnectionFactory)factoryInstances.get(jcd.getDescriptorKey());
  -            if(conFac == null)
  -            {
  -                try
  -                {
  -                    conFac = (ConnectionFactory) conFacClass.newInstance();
  -                }
  -                catch (Exception e)
  -                {
  -                    LoggerFactory.getDefaultLogger().error("Instantiation of connection
factory failed", e);
  -                    //should never be thrown
  -                    throw new PersistenceBrokerException(e);
  -                }
  -                factoryInstances.put(jcd.getDescriptorKey(), conFac);
  -            }
  -            return conFac;
  -        }
  -    }
  -
  -    /**
  -     * Release all resources used by this factory factory.
  -     */
  -    public static void releaseAllResources()
  -    {
  -        synchronized (ConnectionFactoryFactory.class)
  -        {
  -            if(defaultConnFactory != null)
  -            {
  -                defaultConnectionFactory().releaseAllResources();
  -                defaultConnFactory = null;
  -            }
  -            if(factoryInstances != null)
  -            {
  -                for (Iterator iterator = factoryInstances.values().iterator(); iterator.hasNext();)
  -                {
  -                    ((ConnectionFactory) iterator.next()).releaseAllResources();
  -                }
  -                factoryInstances.clear();
  -                factoryInstances = null;
  +                LoggerFactory.getDefaultLogger().error("Could not instantiate ConnectionFactory",
e);
  +                throw new OJBRuntimeException(e);
               }
           }
  +        return singleton;
       }
   }
  
  
  
  1.7       +0 -9      jakarta-ojb/src/java/org/apache/ojb/broker/accesslayer/ConnectionFactory.java
  
  Index: ConnectionFactory.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/accesslayer/ConnectionFactory.java,v
  retrieving revision 1.6
  retrieving revision 1.7
  diff -u -r1.6 -r1.7
  --- ConnectionFactory.java	30 Jul 2002 17:06:39 -0000	1.6
  +++ ConnectionFactory.java	28 Nov 2002 22:25:53 -0000	1.7
  @@ -54,9 +54,7 @@
    * <http://www.apache.org/>.
    */
   
  -import org.apache.ojb.broker.PersistenceBrokerException;
   import org.apache.ojb.broker.metadata.JdbcConnectionDescriptor;
  -import org.apache.ojb.broker.singlevm.PersistenceBrokerImpl;
   
   import java.sql.Connection;
   
  @@ -70,13 +68,6 @@
    */
   public interface ConnectionFactory
   {
  -    /**
  -     *
  -     * @deprecated use {@link #lookupConnection} instead
  -     */
  -    public Connection newConnection(JdbcConnectionDescriptor jcd, PersistenceBrokerImpl
broker)
  -            throws PersistenceBrokerException;
  -
       /**
        * Lookup a connection from the connection factory implementation.
        */
  
  
  
  1.1                  jakarta-ojb/src/java/org/apache/ojb/broker/accesslayer/ConnectionFactoryPooledImpl.java
  
  Index: ConnectionFactoryPooledImpl.java
  ===================================================================
  package org.apache.ojb.broker.accesslayer;
  
  import org.apache.commons.pool.BasePoolableObjectFactory;
  import org.apache.commons.pool.ObjectPool;
  import org.apache.commons.pool.PoolableObjectFactory;
  import org.apache.commons.pool.impl.GenericObjectPool;
  import org.apache.ojb.broker.metadata.JdbcConnectionDescriptor;
  import org.apache.ojb.broker.util.logging.Logger;
  import org.apache.ojb.broker.util.logging.LoggerFactory;
  import org.apache.ojb.broker.util.logging.LoggingHelper;
  
  import java.sql.Connection;
  import java.sql.SQLException;
  import java.util.Collection;
  import java.util.HashMap;
  import java.util.Iterator;
  import java.util.Map;
  
  /**
   * Connection factory which pools the requested
   * connections for different JdbcConnectionDescriptors
   * using jakarta-commons-pool api.
   *
   * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>.
   * @version $Id: ConnectionFactoryPooledImpl.java,v 1.1 2002/11/28 22:25:53 arminw Exp $
   */
  public class ConnectionFactoryPooledImpl extends ConnectionFactoryAbstractImpl
  {
      /* @todo make the pools configureable, enhance the JdbcConnectionDescriptor */
      private Logger log = LoggerFactory.getLogger(ConnectionFactoryPooledImpl.class);
      private Map connectionPools = new HashMap();
  
      public ConnectionFactoryPooledImpl()
      {
  
      }
  
      public void returnConnectionToPool(JdbcConnectionDescriptor jcd, Connection con)
              throws LookupException
      {
          try
          {
              ((ObjectPool) this.connectionPools.get(jcd.getDescriptorKey())).returnObject(con);
          }
          catch (Exception e)
          {
              throw new LookupException(e);
          }
      }
  
      public Connection getConnectionFromPool(JdbcConnectionDescriptor jcd) throws LookupException
      {
          ObjectPool op = (ObjectPool) connectionPools.get(jcd.getDescriptorKey());
          if (op == null)
          {
              log.info("Create connection pool for JdbcDescriptorKey " + jcd.getDescriptorKey());
              op = createConnectionPool(jcd);
              synchronized (connectionPools)
              {
                  connectionPools.put(jcd.getDescriptorKey(), op);
              }
          }
          try
          {
              return (Connection) op.borrowObject();
          }
          catch (Exception e)
          {
              throw new LookupException("Could not borrow connection from pool - " +
                      JdbcConnectionDescriptor.class.getName() + ":  " + jcd, e);
          }
      }
  
      /**
       * Create the pool for pooling the connections of the given connection descriptor.
       * Override this method to implement your on {@link org.apache.commons.pool.ObjectPool}.
       */
      public ObjectPool createConnectionPool(JdbcConnectionDescriptor jcd)
      {
          if (log.isDebugEnabled()) log.debug("createPool was called");
          PoolableObjectFactory pof = new ConPoolFactory(this, jcd);
          GenericObjectPool.Config conf = jcd.getConnectionPoolDescriptor().getObjectPoolConfig();
          ObjectPool op = new GenericObjectPool(pof, conf);
          log.info(buildPoolInfo(op, jcd));
          return op;
      }
  
      /**
       * Closes all managed pools.
       */
      public void releaseAllResources()
      {
          super.releaseAllResources();
          synchronized (connectionPools)
          {
              Collection pools = connectionPools.values();
              connectionPools = new HashMap();
              ObjectPool op = null;
              for (Iterator iterator = pools.iterator(); iterator.hasNext();)
              {
                  try
                  {
                      op = ((ObjectPool) iterator.next());
                      op.close();
                  }
                  catch (Exception e)
                  {
                      log.error("Exception occured while closing pool " + op, e);
                  }
              }
          }
      }
  
      /**
       * Helper method, builds a bunch information properties about the
       * pool and jdbc-descriptor
       */
      public String buildPoolInfo(ObjectPool op, JdbcConnectionDescriptor jcd)
      {
          StringBuffer buf = new StringBuffer();
          buf.append("Create new connection pool for ");
          buf.append(JdbcConnectionDescriptor.class.getName() + ",");
          buf.append(LoggingHelper.LINE_SEPARATOR + " used descriptor: " + jcd);
          buf.append(LoggingHelper.LINE_SEPARATOR + "pool configuration was: " + jcd.getConnectionPoolDescriptor());
          return buf.toString();
      }
  
  
      //**************************************************************************************
      // Inner classes
      //************************************************************************************
  
      /**
       * Inner class - {@link org.apache.commons.pool.PoolableObjectFactory}
       * used as factory for connection pooling
       */
      class ConPoolFactory extends BasePoolableObjectFactory
      {
          JdbcConnectionDescriptor jcd;
          ConnectionFactoryPooledImpl cf;
  
          public ConPoolFactory(ConnectionFactoryPooledImpl cf, JdbcConnectionDescriptor jcd)
          {
              this.cf = cf;
              this.jcd = jcd;
          }
  
          public boolean validateObject(Object obj)
          {
              try
              {
                  return !((Connection) obj).isClosed();
              }
              catch (SQLException e)
              {
                  log.error("Connection validation failed, remove connection from pool");
                  return false;
              }
          }
  
          public Object makeObject() throws Exception
          {
              if (log.isDebugEnabled()) log.debug("makeObject called");
              return cf.newConnectionFromDriverManager(jcd);
          }
  
          public void destroyObject(Object obj)
                  throws Exception
          {
              log.info("Destroy object was called, try to close connection: " + obj);
              try
              {
                  ((Connection) obj).close();
              }
              catch (SQLException e)
              {
              }
          }
      }
  }
  
  
  
  1.1                  jakarta-ojb/src/java/org/apache/ojb/broker/accesslayer/ConnectionFactoryNotPooledImpl.java
  
  Index: ConnectionFactoryNotPooledImpl.java
  ===================================================================
  package org.apache.ojb.broker.accesslayer;
  
  import org.apache.ojb.broker.metadata.JdbcConnectionDescriptor;
  
  import java.sql.Connection;
  import java.sql.SQLException;
  
  /**
   * Base implementation without connection pooling.
   *
   * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>
   * @version $Id: ConnectionFactoryNotPooledImpl.java,v 1.1 2002/11/28 22:25:53 arminw Exp
$
   */
  public class ConnectionFactoryNotPooledImpl extends ConnectionFactoryAbstractImpl
  {
      public Connection getConnectionFromPool(JdbcConnectionDescriptor jcd) throws LookupException
      {
          return this.newConnectionFromDriverManager(jcd);
      }
  
      public void returnConnectionToPool(JdbcConnectionDescriptor jcd, Connection con)
              throws LookupException
      {
          try
          {
              con.close();
          }
          catch (SQLException e)
          {
              // ignore
          }
      }
  }
  
  
  
  1.1                  jakarta-ojb/src/java/org/apache/ojb/broker/accesslayer/ConnectionFactoryManagedImpl.java
  
  Index: ConnectionFactoryManagedImpl.java
  ===================================================================
  package org.apache.ojb.broker.accesslayer;
  
  import org.apache.ojb.broker.metadata.JdbcConnectionDescriptor;
  import org.apache.ojb.broker.util.pooling.ByPassConnection;
  
  import java.sql.Connection;
  
  /**
   * ConnectionFactory for use in managed environments - e.g. jboss.
   *
   * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>
   * @version $Id: ConnectionFactoryManagedImpl.java,v 1.1 2002/11/28 22:25:53 arminw Exp
$
   */
  public class ConnectionFactoryManagedImpl extends ConnectionFactoryNotPooledImpl
  {
      public Connection lookupConnection(JdbcConnectionDescriptor jcd) throws LookupException
      {
          return new ByPassConnection(super.lookupConnection(jcd));
      }
  
      protected Connection newConnectionFromDriverManager(JdbcConnectionDescriptor jcd)
              throws LookupException
      {
          throw new UnsupportedOperationException("Not supported in managed environment");
      }
  }
  
  
  
  1.1                  jakarta-ojb/src/java/org/apache/ojb/broker/accesslayer/ConnectionFactoryDBCPImpl.java
  
  Index: ConnectionFactoryDBCPImpl.java
  ===================================================================
  package org.apache.ojb.broker.accesslayer;
  
  import org.apache.commons.dbcp.AbandonedConfig;
  import org.apache.commons.dbcp.DriverManagerConnectionFactory;
  import org.apache.commons.dbcp.PoolableConnectionFactory;
  import org.apache.commons.dbcp.PoolingDataSource;
  import org.apache.commons.pool.KeyedObjectPoolFactory;
  import org.apache.commons.pool.ObjectPool;
  import org.apache.commons.pool.impl.GenericKeyedObjectPoolFactory;
  import org.apache.commons.pool.impl.GenericObjectPool;
  import org.apache.ojb.broker.metadata.JdbcConnectionDescriptor;
  import org.apache.ojb.broker.util.logging.Logger;
  import org.apache.ojb.broker.util.logging.LoggerFactory;
  
  import javax.naming.InitialContext;
  import javax.sql.DataSource;
  import java.sql.Connection;
  import java.sql.SQLException;
  import java.util.HashMap;
  import java.util.Map;
  
  /**
   * ConnectionFactory implementation using jakarta-DBCP
   * based on a part of Dirk Verbeek's OJB redesign-proposal (Thanks).
   *
   * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>
   * @version $Id: ConnectionFactoryDBCPImpl.java,v 1.1 2002/11/28 22:25:53 arminw Exp $
   */
  public class ConnectionFactoryDBCPImpl implements ConnectionFactory
  {
      private Logger log = LoggerFactory.getLogger(ConnectionFactoryDBCPImpl.class);
  
      private Map ds_map = new HashMap();
      /* @todo make objectPool configurable at runtime */
      private ObjectPool connectionPool;
  
      public Connection lookupConnection(JdbcConnectionDescriptor jcd) throws LookupException
      {
          DataSource ds = (DataSource) ds_map.get(jcd.getDescriptorKey());
          if (ds == null)
          {
              try
              {
                  ds = jcd.getDatasourceName() != null ? setupDataSource(jcd.getDatasourceName())
:
                          setupDriver(jcd);
                  ds_map.put(jcd.getDescriptorKey(), ds);
              }
              catch (Exception e)
              {
                  log.error("Could not setup DataSource for " + jcd, e);
                  throw new LookupException(e);
              }
          }
          try
          {
              return ds.getConnection();
          }
          catch (SQLException e)
          {
              throw new LookupException("Can't get connection from DataSource", e);
          }
      }
  
      public void releaseConnection(JdbcConnectionDescriptor jcd, Connection con)
      {
          try
          {
              con.close();
          }
          catch (SQLException e)
          {
              //ignore
          }
      }
  
      public void releaseAllResources()
      {
          ds_map = new HashMap();
      }
  
      private DataSource setupDataSource(String datasourceName) throws Exception
      {
          if (log.isDebugEnabled()) log.debug("JNDI lookup for " + datasourceName);
          InitialContext ic = new InitialContext();
          DataSource ds = (DataSource) ic.lookup(datasourceName);
          return ds;
      }
  
      private DataSource setupDriver(JdbcConnectionDescriptor jcd) throws Exception
      {
          if (log.isDebugEnabled()) log.debug("Create pool for " + jcd);
          try
          {
              Class.forName(jcd.getDriver(), true, Thread.currentThread().getContextClassLoader()).newInstance();
          }
          catch (Exception e)
          {
              log.error("Could not instantiate jdbc driver", e);
          }
  
          // get the configuration for the connection pool
          GenericObjectPool.Config conf = jcd.getConnectionPoolDescriptor().getObjectPoolConfig();
          //
          // First, we'll need a ObjectPool that serves as the
          // actual pool of connections.
          //
          // We'll use a GenericObjectPool instance, although
          // any ObjectPool implementation will suffice.
          //
  
          connectionPool = new GenericObjectPool(null, conf);
  
          //
          // Next, we'll create a ConnectionFactory that the
          // pool will use to create Connections.
          // We'll use the DriverManagerConnectionFactory,
          //
          org.apache.commons.dbcp.ConnectionFactory connectionFactory =
                  new DriverManagerConnectionFactory(getDbURL(jcd), jcd.getUserName(), jcd.getPassWord());
  
  
          KeyedObjectPoolFactory statementPoolFactory = new GenericKeyedObjectPoolFactory(null);
  
          // TODO: get this query from the "platform" (database config)
          //String validationQuery = "select 1 from dual";
          String validationQuery = null;
          boolean defaultReadOnly = false;
          boolean defaultAutoCommit = true;
  
          /* @todo make this configurable */
          // Abandoned configuration
          AbandonedConfig ac = new AbandonedConfig();
          ac.setLogAbandoned(false);
          ac.setRemoveAbandoned(false);
          ac.setRemoveAbandonedTimeout(100);
  
          //
          // Now we'll create the PoolableConnectionFactory, which wraps
          // the "real" Connections created by the ConnectionFactory with
          // the classes that implement the pooling functionality.
          //
          PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
                  connectionFactory,
                  connectionPool,
                  statementPoolFactory,
                  validationQuery,
                  defaultReadOnly,
                  defaultAutoCommit);
  
          //
          // Finally, we create the PoolingDriver itself,
          // passing in the object pool we created.
          //
          PoolingDataSource dataSource = new PoolingDataSource(connectionPool);
          return dataSource;
      }
  
      private String getDbURL(JdbcConnectionDescriptor jcd)
      {
          return jcd.getProtocol() + ":" + jcd.getSubProtocol() + ":" + jcd.getDbAlias();
      }
  
  }
  
  
  
  1.1                  jakarta-ojb/src/java/org/apache/ojb/broker/accesslayer/ConnectionFactoryAbstractImpl.java
  
  Index: ConnectionFactoryAbstractImpl.java
  ===================================================================
  package org.apache.ojb.broker.accesslayer;
  
  import org.apache.ojb.broker.metadata.JdbcConnectionDescriptor;
  import org.apache.ojb.broker.platforms.PlatformException;
  import org.apache.ojb.broker.platforms.PlatformFactory;
  import org.apache.ojb.broker.util.logging.Logger;
  import org.apache.ojb.broker.util.logging.LoggerFactory;
  
  import javax.naming.InitialContext;
  import javax.naming.NamingException;
  import javax.sql.DataSource;
  import java.sql.Connection;
  import java.sql.SQLException;
  import java.util.HashMap;
  import java.util.Map;
  
  /**
   * Abstract base class to simplify implementation of {@link ConnectionFactory}'s.
   *
   * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>
   * @version $Id: ConnectionFactoryAbstractImpl.java,v 1.1 2002/11/28 22:25:53 arminw Exp
$
   */
  public abstract class ConnectionFactoryAbstractImpl implements ConnectionFactory
  {
      private Logger log = LoggerFactory.getLogger(ConnectionFactoryAbstractImpl.class);
  
      /**
       * holds the datasource looked up from JNDI in a map, keyed
       * by the JNDI name.
       */
      private Map m_dsCache = new HashMap();
  
      /**
       * Implement this method.
       */
      public abstract Connection getConnectionFromPool(JdbcConnectionDescriptor jcd)
              throws LookupException;
  
      /**
       * Implement this method.
       */
      public abstract void returnConnectionToPool(JdbcConnectionDescriptor jcd, Connection
con)
              throws LookupException;
  
      public void releaseConnection(JdbcConnectionDescriptor jcd, Connection con)
      {
          if (con == null) return;
          if (jcd.getDatasourceName() != null)
          {
              try
              {
                  con.close();
              }
              catch (SQLException e)
              {
                  log.error("Closing connection failed", e);
              }
          }
          else
          {
              try
              {
                  returnConnectionToPool(jcd, con);
              }
              catch (LookupException e)
              {
                  log.error("Unexpected exception when return connection " + con +
                          " to pool using " + jcd, e);
              }
          }
      }
  
      public Connection lookupConnection(JdbcConnectionDescriptor jcd) throws LookupException
      {
          Connection conn;
          /*
          use JNDI datasourcelookup or ordinary jdbc DriverManager
          to obtain connection ?
          */
          if (jcd.getDatasourceName() != null)
          {
              if (log.isDebugEnabled())
                  log.debug("do datasource lookup, name: " + jcd.getDatasourceName() +
                          ", user: " + jcd.getUserName());
              conn = newConnectionFromDataSource(jcd);
          }
          else
          {
              conn = getConnectionFromPool(jcd);
              // check connection
              try
              {
                  if (conn == null || conn.isClosed())
                  {
                      log.error("Connection for JdbcConnectionDiscriptor ("
                              + jcd.getDatasourceName() != null ? "datasource: " + jcd.getDatasourceName()
:
                              "db-url: " + getDbURL(jcd) + ", user: " + jcd.getUserName()
+
                              ") was not sane, either closed or null");
                  }
              }
              catch (SQLException e)
              {
                  log.error("Error during sanity check of new DB Connection, either it was
closed", e);
                  throw new LookupException("Connection check failed", e);
              }
              // initialize connection
              // perform platform specific initializations:
              try
              {
                  PlatformFactory.getPlatformFor(jcd).initializeJdbcConnection(conn);
              }
              catch (PlatformException e)
              {
                  throw new LookupException("Platform dependent initialization of connection
failed", e);
              }
          }
          return conn;
      }
  
      /**
       * Override this method to do cleanup in your implenetation.
       * Do a <tt>super.releaseAllResources()</tt> in your method implementation
       * to free resources used by this class.
       */
      public synchronized void releaseAllResources()
      {
          this.m_dsCache.clear();
      }
  
      /**
       *
       * @param datasourceName The JNDI name where the datasource is bound
       * @param user
       * @param password
       * @return an instance of Connection from the named Datasource
       * @throws PersistenceBrokerException if we can't get a connection from the datasource
either due to a
       *          naming exception, a failed sanity check, or a SQLException.
       */
      protected Connection newConnectionFromDataSource(JdbcConnectionDescriptor jcd)
              throws LookupException
      {
          Connection retval = null;
          // use JNDI lookup
          DataSource ds = (DataSource) m_dsCache.get(jcd.getDatasourceName());
          try
          {
              if (ds == null)
              {
                  /**
                   * this synchronization block won't be a big deal as we only look up
                   * new datasources not found in the map.
                   */
                  synchronized (m_dsCache)
                  {
                      InitialContext ic = new InitialContext();
                      ds = (DataSource) ic.lookup(jcd.getDatasourceName());
                      /**
                       * cache the datasource lookup.
                       */
                      m_dsCache.put(jcd.getDatasourceName(), ds);
                  }
              }
              if (jcd.getUserName() == null)
              {
                  retval = ds.getConnection();
              }
              else
              {
                  retval = ds.getConnection(jcd.getUserName(), jcd.getPassWord());
              }
          }
          catch (SQLException sqlEx)
          {
              log.error("SQLException thrown while trying to get Connection from Datasource
(" +
                      jcd.getDatasourceName() + ")", sqlEx);
              throw new LookupException("SQLException thrown while trying to get Connection
from Datasource (" +
                      jcd.getDatasourceName() + ")", sqlEx);
          }
          catch (NamingException namingEx)
          {
              log.error("Naming Exception while looking up DataSource (" + jcd.getDatasourceName()
+ ")", namingEx);
              throw new LookupException("Naming Exception while looking up DataSource (" +
jcd.getDatasourceName() +
                      ")", namingEx);
          }
          return retval;
      }
  
      /**
       * Returns a new created connection
       *
       * @param jcd the connection descriptor
       * @param user
       * @param pass
       * @return an instance of Connection from the drivermanager
       */
      protected Connection newConnectionFromDriverManager(JdbcConnectionDescriptor jcd)
              throws LookupException
      {
          Connection retval = null;
          // use JDBC DriverManager
          String driver = jcd.getDriver();
          String url = getDbURL(jcd);
          try
          {
              // loads the driver - NB call to newInstance() added to force initialisation
              Class.forName(driver, true, Thread.currentThread().getContextClassLoader()).newInstance();
              if (jcd.getUserName() == null)
              {
                  retval = java.sql.DriverManager.getConnection(url);
              }
              else
              {
                  retval = java.sql.DriverManager.getConnection(url, jcd.getUserName(), jcd.getPassWord());
              }
          }
          catch (SQLException sqlEx)
          {
              log.error("Error getting Connection from DriverManager with url (" + url + ")
and driver (" + driver + ")", sqlEx);
              throw new LookupException("Error getting Connection from DriverManager with
url (" + url + ") and driver (" + driver + ")", sqlEx);
          }
          catch (ClassNotFoundException cnfEx)
          {
              log.error(cnfEx);
              throw new LookupException("A class was not found", cnfEx);
          }
          catch (Exception e)
          {
              log.error("Instantiation of jdbc driver failed", e);
              throw new LookupException("Instantiation of jdbc driver failed", e);
          }
          return retval;
      }
  
      private String getDbURL(JdbcConnectionDescriptor jcd)
      {
          return jcd.getProtocol() + ":" + jcd.getSubProtocol() + ":" + jcd.getDbAlias();
      }
  }
  
  
  

Mime
View raw message