db-ojb-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From arm...@apache.org
Subject cvs commit: db-ojb/src/test/org/apache/ojb/broker ConnectionFactoryTest.java
Date Mon, 05 May 2003 23:46:43 GMT
arminw      2003/05/05 16:46:42

  Modified:    src/java/org/apache/ojb/broker/accesslayer
                        ConnectionFactoryAbstractImpl.java
                        ConnectionFactoryDBCPImpl.java
  Added:       src/test/org/apache/ojb/broker ConnectionFactoryTest.java
  Log:
  refactoring ConnectionFactory implementation
  using DBCP, add simple test case
  
  Revision  Changes    Path
  1.4       +2 -2      db-ojb/src/java/org/apache/ojb/broker/accesslayer/ConnectionFactoryAbstractImpl.java
  
  Index: ConnectionFactoryAbstractImpl.java
  ===================================================================
  RCS file: /home/cvs/db-ojb/src/java/org/apache/ojb/broker/accesslayer/ConnectionFactoryAbstractImpl.java,v
  retrieving revision 1.3
  retrieving revision 1.4
  diff -u -r1.3 -r1.4
  --- ConnectionFactoryAbstractImpl.java	9 Jan 2003 16:57:21 -0000	1.3
  +++ ConnectionFactoryAbstractImpl.java	5 May 2003 23:46:42 -0000	1.4
  @@ -260,7 +260,7 @@
           return retval;
       }
   
  -    private String getDbURL(JdbcConnectionDescriptor jcd)
  +    protected String getDbURL(JdbcConnectionDescriptor jcd)
       {
           return jcd.getProtocol() + ":" + jcd.getSubProtocol() + ":" + jcd.getDbAlias();
       }
  
  
  
  1.5       +25 -62    db-ojb/src/java/org/apache/ojb/broker/accesslayer/ConnectionFactoryDBCPImpl.java
  
  Index: ConnectionFactoryDBCPImpl.java
  ===================================================================
  RCS file: /home/cvs/db-ojb/src/java/org/apache/ojb/broker/accesslayer/ConnectionFactoryDBCPImpl.java,v
  retrieving revision 1.4
  retrieving revision 1.5
  diff -u -r1.4 -r1.5
  --- ConnectionFactoryDBCPImpl.java	15 Jan 2003 10:43:28 -0000	1.4
  +++ ConnectionFactoryDBCPImpl.java	5 May 2003 23:46:42 -0000	1.5
  @@ -9,13 +9,10 @@
   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.platforms.PlatformException;
  -import org.apache.ojb.broker.platforms.PlatformFactory;
   import org.apache.ojb.broker.util.ClassHelper;
   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;
  @@ -24,29 +21,31 @@
   
   /**
    * ConnectionFactory implementation using jakarta-DBCP
  - * based on a part of Dirk Verbeek's OJB redesign-proposal (Thanks).
  + * to pool driver based connections.
  + *
  + * (based on a proposal of Dirk Verbeek - Thanks).
    *
    * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>
    * @version $Id$
    */
  -public class ConnectionFactoryDBCPImpl implements ConnectionFactory
  +public class ConnectionFactoryDBCPImpl extends ConnectionFactoryAbstractImpl
   {
       private Logger log = LoggerFactory.getLogger(ConnectionFactoryDBCPImpl.class);
   
  -    private Map ds_map = new HashMap();
  +    private Map poolMap = new HashMap();
       /* @todo make objectPool configurable at runtime */
       private ObjectPool connectionPool;
   
  -    public Connection lookupConnection(JdbcConnectionDescriptor jcd) throws LookupException
  +    public Connection getConnectionFromPool(JdbcConnectionDescriptor jcd) throws LookupException
       {
  -        DataSource ds = (DataSource) ds_map.get(jcd.getPBKey());
  -        if (ds == null)
  +        DataSource ds = (DataSource) poolMap.get(jcd.getPBKey());
  +        if (ds == null) // found no pool for PBKey
           {
               try
               {
  -                ds = jcd.getDatasourceName() != null ? setupDataSource(jcd.getDatasourceName())
:
  -                        setupDriver(jcd);
  -                ds_map.put(jcd.getPBKey(), ds);
  +                // setup new pool
  +                ds = setupPool(jcd);
  +                poolMap.put(jcd.getPBKey(), ds);
               }
               catch (Exception e)
               {
  @@ -57,65 +56,36 @@
           try
           {
               Connection con = ds.getConnection();
  -            /* TODO:
  -            We initialize connection on every lookup, better solution
  -            will be doing initialize once when collection was created
  -            */
  -            initializeJdbcConnection(con, jcd);
               return con;
           }
           catch (SQLException e)
           {
  -            throw new LookupException("Can't get connection from DataSource", e);
  +            throw new LookupException("Can't get connection from DBCP-DataSource", e);
           }
       }
   
  -    protected void initializeJdbcConnection(Connection con, JdbcConnectionDescriptor jcd)
  +    public void returnConnectionToPool(JdbcConnectionDescriptor jcd, Connection con)
               throws LookupException
       {
  -        // initialize connection
  -        // perform platform specific initializations:
  -        try
  -        {
  -            PlatformFactory.getPlatformFor(jcd).initializeJdbcConnection(jcd, con);
  -        }
  -        catch (PlatformException e)
  -        {
  -            throw new LookupException("Platform dependent initialization of connection
failed", e);
  -        }
  -    }
  -
  -    public void releaseConnection(JdbcConnectionDescriptor jcd, Connection con)
  -    {
           try
           {
  +            // we using datasources, thus close return connection to pool
               con.close();
           }
           catch (SQLException e)
           {
  -            //ignore
  +            log.warn("Connection close failed", e);
           }
       }
   
  -    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
  +    /**
  +     * Override this method to setup your own pool
  +     */
  +    protected DataSource setupPool(JdbcConnectionDescriptor jcd) throws Exception
       {
           log.info("Create new DBCP connection pool:" + jcd);
           try
           {
  -            // Class.forName(jcd.getDriver(), true, Thread.currentThread().getContextClassLoader()).newInstance();
               ClassHelper.newInstance(jcd.getDriver());
           }
           catch (Exception e)
  @@ -125,17 +95,15 @@
   
           // 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,
  @@ -143,12 +111,13 @@
           org.apache.commons.dbcp.ConnectionFactory connectionFactory =
                   new DriverManagerConnectionFactory(getDbURL(jcd), jcd.getUserName(), jcd.getPassWord());
   
  -
           KeyedObjectPoolFactory statementPoolFactory = new GenericKeyedObjectPoolFactory(null);
  -
  +        // set the validation query
           String validationQuery = jcd.getConnectionPoolDescriptor().getValidationQuery();
           boolean defaultReadOnly = false;
  -        boolean defaultAutoCommit = true;
  +        // set autocommit mode
  +        boolean defaultAutoCommit = (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_FALSE)
?
  +                false : true;
   
           // Abandoned configuration
           AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig();
  @@ -174,10 +143,4 @@
           PoolingDataSource dataSource = new PoolingDataSource(connectionPool);
           return dataSource;
       }
  -
  -    private String getDbURL(JdbcConnectionDescriptor jcd)
  -    {
  -        return jcd.getProtocol() + ":" + jcd.getSubProtocol() + ":" + jcd.getDbAlias();
  -    }
  -
   }
  
  
  
  1.1                  db-ojb/src/test/org/apache/ojb/broker/ConnectionFactoryTest.java
  
  Index: ConnectionFactoryTest.java
  ===================================================================
  package org.apache.ojb.broker;
  
  import junit.framework.TestCase;
  import org.apache.commons.lang.SerializationUtils;
  import org.apache.ojb.broker.accesslayer.ConnectionFactory;
  import org.apache.ojb.broker.accesslayer.ConnectionFactoryDBCPImpl;
  import org.apache.ojb.broker.accesslayer.ConnectionFactoryFactory;
  import org.apache.ojb.broker.accesslayer.ConnectionFactoryPooledImpl;
  import org.apache.ojb.broker.metadata.JdbcConnectionDescriptor;
  import org.apache.ojb.broker.metadata.MetadataManager;
  
  import java.sql.Connection;
  
  /**
   * ConnectionFactory implementation related tests.
   *
   * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>
   * @version $Id: ConnectionFactoryTest.java,v 1.1 2003/05/05 23:46:42 arminw Exp $
   */
  public class ConnectionFactoryTest extends TestCase
  {
      PersistenceBroker broker;
  
      public ConnectionFactoryTest()
      {
      }
  
      public ConnectionFactoryTest(String s)
      {
          super(s);
      }
  
      public static void main(String[] args)
      {
          String[] arr = {ConnectionFactoryTest.class.getName()};
          junit.textui.TestRunner.main(arr);
      }
  
      /**
       * Simple test to check base functionality of the
       * ConnectionFactory implementation
       */
      public void testConnectionFactoryPooledImpl() throws Exception
      {
          checkFactory(ConnectionFactoryPooledImpl.class);
      }
  
      /**
       * Simple test to check base functionality of the
       * ConnectionFactory implementation
       */
      public void testConnectionFactoryDBCPImpl() throws Exception
      {
          checkFactory(ConnectionFactoryDBCPImpl.class);
      }
  
      private void checkFactory(Class factory) throws Exception
      {
          Class oldFac = null;
          ConnectionFactoryFactory fac = null;
          try
          {
              fac = ConnectionFactoryFactory.getInstance();
              oldFac = fac.getClassToServe();
              fac.setClassToServe(factory);
              ConnectionFactory conFac = (ConnectionFactory) fac.createNewInstance();
  
              MetadataManager mm = MetadataManager.getInstance();
              JdbcConnectionDescriptor jcd = (JdbcConnectionDescriptor) SerializationUtils.clone(
                      broker.serviceConnectionManager().getConnectionDescriptor());
              jcd.setJcdAlias(factory.getName() + "_test_1");
              jcd.setUseAutoCommit(2);
  
              mm.connectionRepository().addDescriptor(jcd);
              Connection con = conFac.lookupConnection(jcd);
              Connection con2 = conFac.lookupConnection(jcd);
              Connection con3 = conFac.lookupConnection(jcd);
              assertFalse("Expect autocommit state false", con.getAutoCommit());
              con.close();
              con2.close();
              con3.close();
  
  
              conFac = (ConnectionFactory) fac.createNewInstance();
  
              jcd = (JdbcConnectionDescriptor) SerializationUtils.clone(
                      broker.serviceConnectionManager().getConnectionDescriptor());
              jcd.setJcdAlias(factory.getName() + "_test_2");
              jcd.setUseAutoCommit(1);
  
              mm.connectionRepository().addDescriptor(jcd);
              con = conFac.lookupConnection(jcd);
              assertTrue("Expect autocommit state true", con.getAutoCommit());
          }
          finally
          {
              if (oldFac != null) fac.setClassToServe(oldFac);
          }
      }
  
  
      /**
       * Insert the method's description here.
       * Creation date: (06.12.2000 21:58:53)
       */
      public void setUp() throws PBFactoryException
      {
          broker = PersistenceBrokerFactory.defaultPersistenceBroker();
      }
  
      /**
       * Insert the method's description here.
       * Creation date: (06.12.2000 21:59:14)
       */
      public void tearDown()
      {
          try
          {
              broker.close();
          }
          catch (PersistenceBrokerException e)
          {
          }
      }
  }
  
  
  

Mime
View raw message