You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jetspeed-dev@portals.apache.org by at...@apache.org on 2005/08/24 09:27:54 UTC

svn commit: r239550 - in /portals/jetspeed-2/trunk: components/portal/src/test/org/apache/jetspeed/testhelpers/ components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ etc/db-o...

Author: ate
Date: Wed Aug 24 00:26:20 2005
New Revision: 239550

URL: http://svn.apache.org/viewcvs?rev=239550&view=rev
Log:
Resolving http://issues.apache.org/jira/browse/JS2-326:
Great patch provided by Michael Lipp, thank you!
This also removes the need to hard code the OJB platform in the runtime configuration.
I'll cleanout the no longer used org.apache.jetspeed.[test|production]database.ojb.platform
properties and the @platform@ filtering after this commit.

Added:
    portals/jetspeed-2/trunk/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/
    portals/jetspeed-2/trunk/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/
    portals/jetspeed-2/trunk/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionManagerImpl.java   (with props)
    portals/jetspeed-2/trunk/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionRepositoryEntry.java   (with props)
Modified:
    portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/testhelpers/SpringEngineHelper.java
    portals/jetspeed-2/trunk/etc/db-ojb/OJB.properties
    portals/jetspeed-2/trunk/etc/db-ojb/repository_database.xml
    portals/jetspeed-2/trunk/etc/db-ojb/test-repository-datasource-spring.xml
    portals/jetspeed-2/trunk/src/webapp/WEB-INF/assembly/boot/datasource.xml

Modified: portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/testhelpers/SpringEngineHelper.java
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/testhelpers/SpringEngineHelper.java?rev=239550&r1=239549&r2=239550&view=diff
==============================================================================
--- portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/testhelpers/SpringEngineHelper.java (original)
+++ portals/jetspeed-2/trunk/components/portal/src/test/org/apache/jetspeed/testhelpers/SpringEngineHelper.java Wed Aug 24 00:26:20 2005
@@ -46,7 +46,7 @@
         ServletConfigFactoryBean.setServletConfig(servletConfig);
         ApplicationContext bootCtx = (ApplicationContext) context.get(AbstractTestHelper.APP_CONTEXT);
         
-        SpringComponentManager scm = new SpringComponentManager(null, new String[] {"/WEB-INF/assembly/*.xml"}, servletContent, appRoot );
+        SpringComponentManager scm = new SpringComponentManager(new String[] {"../../etc/db-ojb/test-*.xml"}, new String[] {"/WEB-INF/assembly/*.xml"}, servletContent, appRoot );
        
         engine = new JetspeedEngine(config, appRoot, servletConfig, scm );
         engine.start();

Added: portals/jetspeed-2/trunk/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionManagerImpl.java
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionManagerImpl.java?rev=239550&view=auto
==============================================================================
--- portals/jetspeed-2/trunk/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionManagerImpl.java (added)
+++ portals/jetspeed-2/trunk/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionManagerImpl.java Wed Aug 24 00:26:20 2005
@@ -0,0 +1,443 @@
+package org.apache.jetspeed.components.rdbms.ojb;
+
+/* Copyright 2003-2004 The Apache Software Foundation
+ *
+ * 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.
+ */
+
+import java.sql.Connection;
+import java.sql.SQLException;
+
+import org.apache.ojb.broker.OJBRuntimeException;
+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.accesslayer.ConnectionFactory;
+import org.apache.ojb.broker.accesslayer.ConnectionFactoryFactory;
+import org.apache.ojb.broker.accesslayer.ConnectionManagerIF;
+import org.apache.ojb.broker.accesslayer.LookupException;
+import org.apache.ojb.broker.accesslayer.OJBBatchUpdateException;
+import org.apache.ojb.broker.metadata.ConnectionPoolDescriptor;
+import org.apache.ojb.broker.metadata.JdbcConnectionDescriptor;
+import org.apache.ojb.broker.metadata.MetadataManager;
+import org.apache.ojb.broker.platforms.Platform;
+import org.apache.ojb.broker.platforms.PlatformFactory;
+import org.apache.ojb.broker.util.ClassHelper;
+import org.apache.ojb.broker.util.batch.BatchConnection;
+import org.apache.ojb.broker.util.logging.Logger;
+import org.apache.ojb.broker.util.logging.LoggerFactory;
+
+/**
+ * Manages Connection ressources. This class is a replacement for the default
+ * ConnectionManagerImpl that comes with OJB. It differs from this class only
+ * in its way to get a connection factory. The default OJB class always uses
+ * the class configured in OJB.properties. This implementation looks up the
+ * factory configured for the given JCD first and uses the default factory
+ * class only if no class is configured in the JCD.
+ *
+ * @see ConnectionManagerIF
+ * @author Thomas Mahler
+ * @version $Id$
+ */
+public class ConnectionManagerImpl implements ConnectionManagerIF
+{
+    // We cannot derive from OBJ's ConnectionManagerIF because member
+    // variables are private
+    
+    private Logger log = LoggerFactory.getLogger(ConnectionManagerImpl.class);
+
+    private PersistenceBroker broker = null;
+    private ConnectionFactory connectionFactory;
+    private JdbcConnectionDescriptor jcd;
+    private Platform platform;
+    private Connection con = null;
+    private PBKey pbKey;
+    private boolean originalAutoCommitState;
+    private boolean isInLocalTransaction;
+    private boolean batchMode;
+    private BatchConnection batchCon = null;
+
+    public ConnectionManagerImpl(PersistenceBroker broker)
+    {
+        this.broker = broker;
+        this.pbKey = broker.getPBKey();
+        this.jcd = MetadataManager.getInstance().connectionRepository().getDescriptor(pbKey);
+        ConnectionPoolDescriptor cpd = jcd.getConnectionPoolDescriptor();
+        if (cpd != null && cpd.getConnectionFactory() != null)
+        {
+            try
+            {
+                connectionFactory = (ConnectionFactory)
+                    ClassHelper.newInstance (cpd.getConnectionFactory(), true);
+            }
+            catch (InstantiationException e)
+            {
+                String err = "Can't instantiate class " + cpd.getConnectionFactory();
+                log.error(err, e);
+                throw (IllegalStateException)(new IllegalStateException(err)).initCause(e);
+            }
+            catch (IllegalAccessException e)
+            {
+                String err = "Can't instantiate class " + cpd.getConnectionFactory();
+                log.error(err, e);
+                throw (IllegalStateException)(new IllegalStateException(err)).initCause(e);
+            }
+        }
+        else 
+        {
+            this.connectionFactory = ConnectionFactoryFactory.getInstance().createConnectionFactory();
+        }
+        this.platform = PlatformFactory.getPlatformFor(jcd);
+        /*
+        by default batch mode is not enabled and after use of a PB
+        instance, before instance was returned to pool, batch mode
+        was set to false again (PB implementation close method)
+        Be carefully in modify this behaviour, changes could cause
+        unexpected behaviour
+        */
+        setBatchMode(false);
+    }
+
+    /**
+     * Returns the associated {@link org.apache.ojb.broker.metadata.JdbcConnectionDescriptor}
+     */
+    public JdbcConnectionDescriptor getConnectionDescriptor()
+    {
+        return jcd;
+    }
+
+    public Platform getSupportedPlatform()
+    {
+        return this.platform;
+    }
+
+    /**
+     * Returns the underlying connection, requested from
+     * {@link org.apache.ojb.broker.accesslayer.ConnectionFactory}.
+     * <p>
+     * PB#beginTransaction() opens a single jdbc connection via
+	 * PB#serviceConnectionManager().localBegin().
+	 * If you call PB#serviceConnectionManager().getConnection() later
+	 * it returns the already opened connection.
+	 * The PB instance will release the used connection during
+	 * PB#commitTransaction() or PB#abortTransaction() or PB#close().
+     * </p>
+     * <p>
+     * NOTE: Never call Connection.close() on the connection requested from the ConnectionManager.
+     * Cleanup of used connection is done by OJB itself. If you need to release a used connection
+     * call {@link #releaseConnection()}.
+     * </p>
+     */
+    public Connection getConnection() throws LookupException
+    {
+        /*
+        if the connection is not null and we are not in a local tx, we check
+        the connection state and release "dead" connections.
+        if connection is in local tx we do nothing, the dead connection will cause
+        an exception and PB instance have to handle rollback
+        */
+        if(con != null && !isInLocalTransaction() && !isAlive(con))
+        {
+            releaseConnection();
+        }
+        if (con == null)
+        {
+            con = this.connectionFactory.lookupConnection(jcd);
+            if (con == null) throw new PersistenceBrokerException("Cannot get connection for " + jcd);
+            if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE)
+            {
+                try
+                {
+                    this.originalAutoCommitState = con.getAutoCommit();
+                }
+                catch (SQLException e)
+                {
+                    throw new PersistenceBrokerException("Cannot request autoCommit state on the connection", e);
+                }
+            }
+            if (log.isDebugEnabled()) log.debug("Request new connection from ConnectionFactory: " + con);
+        }
+
+        if (isBatchMode())
+        {
+            if (batchCon == null)
+            {
+                batchCon = new BatchConnection(con, broker);
+            }
+            return batchCon;
+        }
+        else
+        {
+            return con;
+        }
+    }
+
+    /**
+     * Start transaction on the underlying connection.
+     */
+    public void localBegin()
+    {
+        if (this.isInLocalTransaction)
+        {
+            throw new TransactionInProgressException("Connection is already in transaction");
+        }
+        Connection connection = null;
+        try
+        {
+            connection = this.getConnection();
+        }
+        catch (LookupException e)
+        {
+            /**
+             * must throw to notify user that we couldn't start a connection
+             */
+            throw new PersistenceBrokerException("Can't lookup a connection", e);
+        }
+        if (log.isDebugEnabled()) log.debug("localBegin was called for con " + connection);
+        if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE)
+        {
+            if (log.isDebugEnabled()) log.debug("Try to change autoCommit state to 'false'");
+            platform.changeAutoCommitState(jcd, connection, false);
+        }
+        this.isInLocalTransaction = true;
+    }
+
+    /**
+     * Call commit on the underlying connection.
+     */
+    public void localCommit()
+    {
+        if (log.isDebugEnabled()) log.debug("commit was called");
+        if (!this.isInLocalTransaction)
+        {
+            throw new TransactionNotInProgressException("Not in transaction, call begin() before commit()");
+        }
+        try
+        {
+            if (batchCon != null)
+            {
+                batchCon.commit();
+            }
+            else if (con != null)
+            {
+                con.commit();
+            }
+        }
+        catch (SQLException e)
+        {
+            log.error("Commit on underlying connection failed, try to rollback connection", e);
+            this.localRollback();
+            throw new TransactionAbortedException("Commit on connection failed", e);
+        }
+        finally
+        {
+            this.isInLocalTransaction = false;
+            restoreAutoCommitState();
+            this.releaseConnection();
+        }
+    }
+
+    /**
+     * Call rollback on the underlying connection.
+     */
+    public void localRollback()
+    {
+        log.info("Rollback was called, do rollback on current connection " + con);
+        if (!this.isInLocalTransaction)
+        {
+            throw new PersistenceBrokerException("Not in transaction, cannot abort");
+        }
+        try
+        {
+            //truncate the local transaction
+            this.isInLocalTransaction = false;
+            if (batchCon != null)
+            {
+                batchCon.rollback();
+            }
+            else if (con != null && !con.isClosed())
+            {
+                con.rollback();
+            }
+        }
+        catch (SQLException e)
+        {
+            log.error("Rollback on the underlying connection failed", e);
+        }
+        finally
+        {
+            try
+            {
+            	restoreAutoCommitState();
+		    }
+            catch(OJBRuntimeException ignore)
+            {
+			    // Ignore or log exception
+		    }
+            releaseConnection();
+        }
+    }
+
+    /**
+     * Reset autoCommit state.
+     */
+    protected void restoreAutoCommitState()
+    {
+        try
+        {
+            if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE
+                    && originalAutoCommitState == true && con != null && !con.isClosed())
+            {
+                platform.changeAutoCommitState(jcd, con, true);
+            }
+        }
+        catch (SQLException e)
+        {
+            // should never be reached
+            throw new OJBRuntimeException("Restore of connection autocommit state failed", e);
+        }
+    }
+
+    /**
+     * Check if underlying connection was alive.
+     */
+    public boolean isAlive(Connection conn)
+    {
+        try
+        {
+            return con != null ? !con.isClosed() : false;
+        }
+        catch (SQLException e)
+        {
+            log.error("IsAlive check failed, running connection was invalid!!", e);
+            return false;
+        }
+    }
+
+    public boolean isInLocalTransaction()
+    {
+        return this.isInLocalTransaction;
+    }
+
+    /**
+     * Release connection to the {@link org.apache.ojb.broker.accesslayer.ConnectionFactory}, make
+     * sure that you call the method in either case, it's the only way to free the connection.
+     */
+    public void releaseConnection()
+    {
+        if (this.con == null)
+        {
+            return;
+        }
+        if(isInLocalTransaction())
+        {
+            log.error("Release connection: connection is in local transaction, missing 'localCommit' or" +
+                    " 'localRollback' call - try to rollback the connection");
+            localRollback();
+        }
+        else
+        {
+            this.connectionFactory.releaseConnection(this.jcd, this.con);
+            this.con = null;
+            this.batchCon = null;
+        }
+    }
+
+    /**
+     * Returns the underlying used {@link org.apache.ojb.broker.accesslayer.ConnectionFactory}
+     * implementation.
+     */
+    public ConnectionFactory getUnderlyingConnectionFactory()
+    {
+        return connectionFactory;
+    }
+
+    /**
+     * Sets the batch mode on or off - this
+     * switch only works if you set attribute <code>batch-mode</code>
+     * in <code>jdbc-connection-descriptor</code> true and your database
+     * support batch mode.
+     *
+     * @param mode the batch mode
+     */
+    public void setBatchMode(boolean mode)
+    {
+        /*
+        arminw:
+        if batch mode was set 'false' in repository,
+        never enable it.
+        There are many users having weird problems
+        when batch mode was enabled behind the scenes
+        */
+        batchMode = mode && jcd.getBatchMode();
+    }
+
+    /**
+     * @return the batch mode.
+     */
+    public boolean isBatchMode()
+    {
+        return batchMode && platform.supportsBatchOperations();
+    }
+
+    /**
+     * Execute batch (if the batch mode where used).
+     */
+    public void executeBatch() throws OJBBatchUpdateException
+    {
+        if (batchCon != null)
+        {
+            try
+            {
+                batchCon.executeBatch();
+            }
+            catch (Throwable th)
+            {
+                throw new OJBBatchUpdateException(th);
+            }
+        }
+    }
+
+    /**
+     * Execute batch if the number of statements in it
+     * exceeded the limit (if the batch mode where used).
+     */
+    public void executeBatchIfNecessary() throws OJBBatchUpdateException
+    {
+        if (batchCon != null)
+        {
+            try
+            {
+                batchCon.executeBatchIfNecessary();
+            }
+            catch (Throwable th)
+            {
+                throw new OJBBatchUpdateException(th);
+            }
+        }
+    }
+
+    /**
+     * Clear batch (if the batch mode where used).
+     */
+    public void clearBatch()
+    {
+        if (batchCon != null)
+        {
+            batchCon.clearBatch();
+        }
+    }
+}

Propchange: portals/jetspeed-2/trunk/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionManagerImpl.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: portals/jetspeed-2/trunk/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionRepositoryEntry.java
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionRepositoryEntry.java?rev=239550&view=auto
==============================================================================
--- portals/jetspeed-2/trunk/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionRepositoryEntry.java (added)
+++ portals/jetspeed-2/trunk/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionRepositoryEntry.java Wed Aug 24 00:26:20 2005
@@ -0,0 +1,417 @@
+/*
+ * Copyright 2000-2004 The Apache Software Foundation.
+ * 
+ * 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 org.apache.jetspeed.components.rdbms.ojb;
+
+import java.io.PrintWriter;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.HashMap;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.sql.DataSource;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ojb.broker.PBKey;
+import org.apache.ojb.broker.accesslayer.ConnectionFactoryDBCPImpl;
+import org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl;
+import org.apache.ojb.broker.accesslayer.LookupException;
+import org.apache.ojb.broker.metadata.ConnectionPoolDescriptor;
+import org.apache.ojb.broker.metadata.ConnectionRepository;
+import org.apache.ojb.broker.metadata.JdbcConnectionDescriptor;
+import org.apache.ojb.broker.metadata.JdbcMetadataUtils;
+import org.apache.ojb.broker.metadata.MetadataManager;
+import org.apache.ojb.broker.util.ClassHelper;
+import org.springframework.beans.factory.BeanNameAware;
+import org.springframework.beans.factory.InitializingBean;
+
+/**
+ * A JavaBean that configures an entry in OJB's ConnectionRepository
+ * according to its properties. If a JCD alias is not specified, it defaults
+ * to the bean's name in the Spring configuration. If the JDBC connection
+ * descriptor already exists (e.g. because it has been defined in OJB's
+ * configuration) the properties are merged into the existing descriptor
+ * (see note about "platform" below), else the JDBC connection descriptor
+ * is created.<P>
+ * 
+ * If a JNDI name is set, the bean automatically configures a JDBC connection 
+ * descriptor with a connection factory of type 
+ * <code>ConnectionFactoryManagedImpl</code>, else it uses 
+ * <code>ConectionFactoryDBCPImpl</code>. This may be overridden my setting 
+ * the connection factory property explicitly.<P>
+ * 
+ * Properties "driverClassName", "url", "username" and "password" are used
+ * only if no JNDI name is set, i.e. if the connection factory uses the
+ * driver to create data sources.<P>
+ * 
+ * The bean derives the RDBMS platform setting from the configured 
+ * data source or database driver using OJB's <code>JdbcMetadataUtils</code>
+ * class. At least until OJB 1.0.3, however, this class does not properly 
+ * distinguish the platforms "Oracle" and "Oracle9i"; it always assigns 
+ * "Oracle". In case of "Oracle", this bean therefore opens a connection,
+ * obtains the version information from the database server and adjusts the
+ * platform accordingly. This behaviour may be overridden by setting the 
+ * <code>platform</code> property of the bean explicitly. Note that the
+ * attribute "platform" of an already existing JCD is ignored. An already
+ * existing JCD stems most likely from a configuration file "repository.xml".
+ * As the DTD for "repository.xml" ("repository.dtd") defines a default
+ * value for attribute "platform" ("Hsqldb"), it is in general impossible 
+ * to find out whether the platform attribute of an existing JCD has been set 
+ * explicitly or has simply assumed its default value.      
+ *
+ * @author Michael Lipp
+ * @version $Id$
+ */
+public class ConnectionRepositoryEntry 
+    implements BeanNameAware, InitializingBean
+{
+    private static final Log log = LogFactory.getLog(ConnectionRepositoryEntry.class);
+    
+    // general properties
+    private String jcdAlias = null;
+    private String platform = null;
+    private String connectionFactoryClass = null;
+    // properties for obtaining data source from JNDI
+    private String jndiName = null;
+    // properties for creating independant data source 
+    private String driverClassName = null;
+    private String url = null;
+    private String username = null;
+    private String password = null;
+
+    /**
+     * @see org.springframework.beans.factory.BeanNameAware#setBeanName(java.lang.String)
+     */
+    public void setBeanName(String beanName) {
+        // Use the bean's name as fallback if a JCD alias is not set
+        // explicitly
+        if (jcdAlias == null) {
+            jcdAlias = beanName;
+        }
+    }
+    
+    /**
+     * @return Returns the jcdAlias.
+     */
+    public String getJcdAlias() {
+        return jcdAlias;
+    }
+    
+    /**
+     * @param jcdAlias The jcdAlias to set.
+     */
+    public void setJcdAlias(String jcdAlias) {
+        this.jcdAlias = jcdAlias;
+    }
+
+    /**
+     * @return Returns the jndiName.
+     */
+    public String getJndiName() {
+        return jndiName;
+    }
+
+    /**
+     * @param jndiName The jndiName to set.
+     */
+    public void setJndiName(String jndiName) {
+        this.jndiName = jndiName;
+    }
+
+    /**
+     * @return Returns the driverClassName.
+     */
+    public String getDriverClassName() {
+        return driverClassName;
+    }
+
+    /**
+     * @param driverClassName The driverClassName to set.
+     */
+    public void setDriverClassName(String driverClassName) {
+        this.driverClassName = driverClassName;
+    }
+
+    /**
+     * @return Returns the password.
+     */
+    public String getPassword() {
+        return password;
+    }
+
+    /**
+     * @param password The password to set.
+     */
+    public void setPassword(String password) {
+        this.password = password;
+    }
+
+    /**
+     * @return Returns the url.
+     */
+    public String getUrl() {
+        return url;
+    }
+
+    /**
+     * @param url The url to set.
+     */
+    public void setUrl(String url) {
+        this.url = url;
+    }
+
+    /**
+     * @return Returns the username.
+     */
+    public String getUsername() {
+        return username;
+    }
+
+    /**
+     * @param username The username to set.
+     */
+    public void setUsername(String username) {
+        this.username = username;
+    }
+    
+    /**
+     * @return Returns the platform.
+     */
+    public String getPlatform() {
+        return platform;
+    }
+
+    /**
+     * Set the platform attribute of the JCD. Setting this property overrides
+     * the value derived from the data source or database driver. 
+     * @param platform The platform to set.
+     */
+    public void setPlatform(String platform) {
+        this.platform = platform;
+    }
+
+    public void afterPropertiesSet () throws Exception 
+    {
+        // Try to find JCD
+        ConnectionRepository cr = MetadataManager.getInstance().connectionRepository();
+        JdbcConnectionDescriptor jcd = cr.getDescriptor(new PBKey(jcdAlias));
+        if (jcd == null)
+        {
+            jcd = new JdbcConnectionDescriptor();
+            jcd.setJcdAlias(jcdAlias);
+            cr.addDescriptor(jcd);
+        }
+        if (platform != null && platform.length() == 0) {
+            platform = null;
+        }
+        DataSource ds = null;
+        JdbcMetadataUtils jdbcMetadataUtils = new JdbcMetadataUtils ();
+        if (jndiName != null) {
+            // using "preconfigured" data source
+            if (connectionFactoryClass == null) {
+                connectionFactoryClass = ConnectionFactoryManagedImpl.class.getName ();
+            }
+            Context initialContext = new InitialContext();
+            ds = (DataSource) initialContext.lookup(jndiName);
+            jcd.setDatasourceName(jndiName);
+        } else {
+            // have to get data source ourselves
+            if (connectionFactoryClass == null) {
+                connectionFactoryClass = ConnectionFactoryDBCPImpl.class.getName ();
+            }
+            jcd.setDriver(driverClassName);
+            HashMap conData = jdbcMetadataUtils.parseConnectionUrl(url);
+            jcd.setDbms(platform);
+            jcd.setProtocol((String)conData.get(JdbcMetadataUtils.PROPERTY_PROTOCOL));
+            jcd.setSubProtocol((String)conData.get(JdbcMetadataUtils.PROPERTY_SUBPROTOCOL));
+            jcd.setDbAlias((String)conData.get(JdbcMetadataUtils.PROPERTY_DBALIAS));
+            jcd.setUserName(username);
+            jcd.setPassWord(password);
+            // Wrapping the connection factory in a DataSource introduces a bit 
+            // of redundancy (url is parsed again and platform determined again).
+            // But although JdbcMetadataUtils exposes the methods used in 
+            // fillJCDFromDataSource as public (and these do not require a DataSource)
+            // the method itself does more than is made available by the exposed methods.
+            ds = new MinimalDataSource (jcd);
+        }
+        ConnectionPoolDescriptor cpd = jcd.getConnectionPoolDescriptor();
+        if (cpd == null)
+        {
+            cpd = new ConnectionPoolDescriptor();
+            jcd.setConnectionPoolDescriptor(cpd);
+        }
+        Class conFacCls = ClassHelper.getClass(connectionFactoryClass);
+        cpd.setConnectionFactory(conFacCls);
+
+        jdbcMetadataUtils.fillJCDFromDataSource(jcd, ds, null, null);
+        
+        if (platform == null && jcd.getDbms().equals (JdbcMetadataUtils.PLATFORM_ORACLE)) {
+            // Postprocess to find Oracle version.
+            updateOraclePlatform (jcd, ds);
+        }
+        // if platform has explicitly been set, the value takes precedence
+        if (platform != null) {
+            if (!platform.equals(jcd.getDbms())) {
+                log.warn ("Automatically derived RDBMS platform \"" + jcd.getDbms()
+                          + "\" differs from explicitly set platform \"" + platform + "\""); 
+            }
+            jcd.setDbms(platform);
+        } else {
+            platform = jcd.getDbms();
+        }
+    }
+
+    /**
+     * @param jcd
+     * @throws LookupException
+     * @throws IllegalAccessException
+     * @throws InstantiationException
+     * throws SQLException
+     */
+    private void updateOraclePlatform(JdbcConnectionDescriptor jcd, DataSource ds)
+    	throws LookupException, IllegalAccessException, InstantiationException, SQLException {
+        Connection con = null;
+        try 
+        {
+            con = ds.getConnection();
+            DatabaseMetaData metaData = con.getMetaData();
+            int rdbmsVersion = 0;
+            try 
+            {
+                // getDatabaseMajorVersion exists since 1.4, so it may
+                // not be defined for the driver used.
+                rdbmsVersion = metaData.getDatabaseMajorVersion();
+            } catch (Throwable t) {
+                String dbVersion = metaData.getDatabaseProductVersion();
+                String relKey = "Release";
+                String major = dbVersion;
+                int startPos = dbVersion.indexOf(relKey);
+                if (startPos < 0)
+                {
+                    log.warn ("Cannot determine Oracle version, no \"Release\" in procuct version: \"" + dbVersion + "\"");
+                    return;
+                }
+                startPos += relKey.length();
+                int dotPos = dbVersion.indexOf('.', startPos);
+                if (dotPos > 0) {
+                    major = dbVersion.substring(startPos, dotPos).trim();
+                }
+                try
+                {
+                    rdbmsVersion = Integer.parseInt(major);
+                }
+                catch (NumberFormatException e)
+                {
+                    log.warn ("Cannot determine Oracle version, product version \"" + dbVersion + "\" not layed out as \"... Release N.M.....\"");
+                    return;
+                }
+                if (log.isDebugEnabled())
+                {
+                    log.debug ("Extracted Oracle major version " + rdbmsVersion + " from product version \"" + dbVersion + "\"");
+                }
+            }
+            if (rdbmsVersion >= 9) {
+                jcd.setDbms(JdbcMetadataUtils.PLATFORM_ORACLE9I);
+            }
+        }
+        finally
+        {
+            if (con != null) {
+                con.close ();
+            }
+        }
+    }
+
+    /**
+     * a minimal DataSource implementation that satisfies the requirements
+     * of JdbcMetadataUtil.
+     */
+    private class MinimalDataSource implements DataSource {
+
+        private JdbcConnectionDescriptor jcd = null;
+        
+        /**
+         * Create a new instance using the given JCD.
+         */
+        public MinimalDataSource (JdbcConnectionDescriptor jcd)
+        {
+            this.jcd = jcd;
+        }
+        
+        /* (non-Javadoc)
+         * @see javax.sql.DataSource#getConnection()
+         */
+        public Connection getConnection() throws SQLException {
+            // Use JDBC DriverManager as we may not rely on JCD to be sufficiently
+            // initialized to use any of the ConnectionFactories.
+            try {
+                // loads the driver - NB call to newInstance() added to force initialisation
+                ClassHelper.getClass(jcd.getDriver(), true);
+                String url = jcd.getProtocol() + ":" + jcd.getSubProtocol() + ":" + jcd.getDbAlias();
+                if (jcd.getUserName() == null)
+                {
+                    return DriverManager.getConnection(url);
+                }
+                else
+                {
+                    return DriverManager.getConnection(url, jcd.getUserName(), jcd.getPassWord());
+                }
+            }
+            catch (ClassNotFoundException e)
+            {
+                throw (IllegalStateException)
+                    (new IllegalStateException (e.getMessage ())).initCause (e);
+            }
+        }
+        
+        /**
+         * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String)
+         */
+        public Connection getConnection(String username, String password)
+                throws SQLException {
+            return getConnection ();
+        }
+
+        /**
+         * @see javax.sql.DataSource#getLoginTimeout()
+         */
+        public int getLoginTimeout() throws SQLException {
+            return 0;
+        }
+
+        /**
+         * @see javax.sql.DataSource#getLogWriter()
+         */
+        public PrintWriter getLogWriter() throws SQLException {
+            return null;
+        }
+
+        /**
+         * @see javax.sql.DataSource#setLoginTimeout(int)
+         */
+        public void setLoginTimeout(int seconds) throws SQLException {
+        }
+
+        /**
+         * @see javax.sql.DataSource#setLogWriter(java.io.PrintWriter)
+         */
+        public void setLogWriter(PrintWriter out) throws SQLException {
+        }
+    }
+}

Propchange: portals/jetspeed-2/trunk/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionRepositoryEntry.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: portals/jetspeed-2/trunk/etc/db-ojb/OJB.properties
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/etc/db-ojb/OJB.properties?rev=239550&r1=239549&r2=239550&view=diff
==============================================================================
--- portals/jetspeed-2/trunk/etc/db-ojb/OJB.properties (original)
+++ portals/jetspeed-2/trunk/etc/db-ojb/OJB.properties Wed Aug 24 00:26:20 2005
@@ -131,12 +131,16 @@
 # this default connection factory entry in each JDBCConnectionDescriptor.
 #
 
-#ConnectionFactoryClass=org.apache.ojb.broker.accesslayer.ConnectionFactoryPooledImpl
-# Use Spring managed-connections instead
-ConnectionFactoryClass=org.springframework.orm.ojb.support.LocalDataSourceConnectionFactory
+# Note that due to using org.apache.jetspeed.components.rdbms.ojb.ConnectionManagerImpl as
+# ConnectionManager (see below) this connection factory class will be used
+# as a fallback only, i.e. if no special connection factory has been defined
+# in the JDBC connection descriptor.
 
+#ConnectionFactoryClass=org.apache.ojb.broker.accesslayer.ConnectionFactoryPooledImpl
 #ConnectionFactoryClass=org.apache.ojb.broker.accesslayer.ConnectionFactoryNotPooledImpl
-#ConnectionFactoryClass=org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl
+ConnectionFactoryClass=org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl
+
+#ConnectionFactoryClass=org.springframework.orm.ojb.support.LocalDataSourceConnectionFactory
 #ConnectionFactoryClass=org.apache.ojb.broker.accesslayer.ConnectionFactoryDBCPImpl
 #
 #
@@ -144,7 +148,14 @@
 # ConnectionManager
 #----------------------------------------------------------------------------------------
 # The ConnectionManagerClass entry defines the ConnectionManager implemementation to be used
-ConnectionManagerClass=org.apache.ojb.broker.accesslayer.ConnectionManagerImpl
+#
+# It is recommended to use the improved connection manager provided by Jetspeed.
+# Instead of always using the ConnectionFactoryClass specified above, it uses the 
+# specific class configured for a JDBC connection descriptor (and the class specified
+# above as a fallback only).
+
+#ConnectionManagerClass=org.apache.ojb.broker.accesslayer.ConnectionManagerImpl
+ConnectionManagerClass=org.apache.jetspeed.components.rdbms.ojb.ConnectionManagerImpl
 #
 #
 #----------------------------------------------------------------------------------------
@@ -459,4 +470,4 @@
 #----------------------------------------------------------------------------------------
 #----------------------------------------------------------------------------------------
 # End of OJB.properties file
-#----------------------------------------------------------------------------------------
\ No newline at end of file
+#----------------------------------------------------------------------------------------

Modified: portals/jetspeed-2/trunk/etc/db-ojb/repository_database.xml
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/etc/db-ojb/repository_database.xml?rev=239550&r1=239549&r2=239550&view=diff
==============================================================================
--- portals/jetspeed-2/trunk/etc/db-ojb/repository_database.xml (original)
+++ portals/jetspeed-2/trunk/etc/db-ojb/repository_database.xml Wed Aug 24 00:26:20 2005
@@ -32,14 +32,15 @@
 -->
 
 <!-- 
-	There is no need to specify any DB or JNDI info as the org.springframework.orm.ojb.support.LocalDataSourceConnectionFactory
-	defined in OJB.properties will be using a matching Datasource that is defined in Spring.
+	This is just a partial definition. The properties given will be merged 
+	with additional properties by a ConnectionRepositoryEntry JavaBean
+	instantiated in datasource.xml. This bean handles configuration of the
+	jndi name of this connection descriptor and all properties that can
+	dynamically be derived from the data source.
 	-->
     <jdbc-connection-descriptor
         jcd-alias="JetspeedDS"
-        platform="@PLATFORM@"
         default-connection="true"
-        jdbc-level="2.0"
         batch-mode="false"
      >
         <sequence-manager className="org.apache.ojb.broker.util.sequence.SequenceManagerHighLowImpl">

Modified: portals/jetspeed-2/trunk/etc/db-ojb/test-repository-datasource-spring.xml
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/etc/db-ojb/test-repository-datasource-spring.xml?rev=239550&r1=239549&r2=239550&view=diff
==============================================================================
--- portals/jetspeed-2/trunk/etc/db-ojb/test-repository-datasource-spring.xml (original)
+++ portals/jetspeed-2/trunk/etc/db-ojb/test-repository-datasource-spring.xml Wed Aug 24 00:26:20 2005
@@ -3,7 +3,7 @@
 <beans>		
 
   <!-- datasource bean -->
-  <bean id="JetspeedDS" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
+  <bean id="JetspeedDS" class="org.apache.jetspeed.components.rdbms.ojb.ConnectionRepositoryEntry">
     <property name="driverClassName">
       <value>${org.apache.jetspeed.database.driver}</value>
     </property>
@@ -16,11 +16,8 @@
     <property name="password">
       <value>${org.apache.jetspeed.database.password}</value>
     </property>
-  </bean>      
+  </bean>     
      
-  <!-- OJB configurer -->
-  <bean id="ojbConfigurer" class="org.springframework.orm.ojb.support.LocalOjbConfigurer"/>    	
-
   <!-- properties configurer used to pick up system properties -->
   <bean id="propertiesConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"/>
 

Modified: portals/jetspeed-2/trunk/src/webapp/WEB-INF/assembly/boot/datasource.xml
URL: http://svn.apache.org/viewcvs/portals/jetspeed-2/trunk/src/webapp/WEB-INF/assembly/boot/datasource.xml?rev=239550&r1=239549&r2=239550&view=diff
==============================================================================
--- portals/jetspeed-2/trunk/src/webapp/WEB-INF/assembly/boot/datasource.xml (original)
+++ portals/jetspeed-2/trunk/src/webapp/WEB-INF/assembly/boot/datasource.xml Wed Aug 24 00:26:20 2005
@@ -2,36 +2,43 @@
 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
 <beans>		
   <!-- 
-	  Creates a JNDI-based datasource bean name JetspeedDS.
-	  The  jdbc-connection-descriptor jcd-alias property must
-	  be set to match this.  The jdbc-connection-descriptor can
-	  be located under /etc/db-ojb/repository_database.xml in the
-	  source tree.  The LocalOjbConfigurer defined below is responsible 
-	  for matching Spring-managed datasources with there proper 
-	  bean definition.
-	  
-	  Another requirement for this to work is to have the 
-	  ConnectionFactoryClass=org.springframework.orm.ojb.support.LocalDataSourceConnectionFactory 
-      This property is located in /etc/db-ojb/OJB.properties in the source tree.	 
-	  
-	  FYI: The two OJB configuration files mentioned above are currently already setup this way 
-	  in the default Jetspeed implementation.  
-	  
-	  However, if you need to locate/modify these files in a running instance of jetspeed,
-	  they will be located under /WEB-INF/classes.
-	 -->
-  <bean id="JetspeedDS" class="org.springframework.jndi.JndiObjectFactoryBean">
+      Creates a JNDI-based datasource bean name "JetspeedDS". The information
+      provided here is merged with the basic configuration for the 
+      jdbc-connection-descriptor with the matching jcd-alias property
+      ("JetspeedDS") located under /etc/db-ojb/repository_database.xml in the
+      source tree.
+
+      Another requirement for this to work is to have the 
+      ConnectionFactoryClass=org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl
+      or to have
+      ConnectionManagerClass=org.apache.jetspeed.components.rdbms.ojb.ConnectionManagerImpl.
+      (either will do, both are recommended, see comments in configuration file).
+      These properties are located in /etc/db-ojb/OJB.properties in the source tree.
+          
+      FYI: The two OJB configuration files mentioned above are currently already setup this way 
+      in the default Jetspeed implementation.  
+          
+      However, if you need to locate/modify these files in a running instance of jetspeed,
+      they will be located under /WEB-INF/classes.
+     -->
+  <bean id="JetspeedDS" class="org.apache.jetspeed.components.rdbms.ojb.ConnectionRepositoryEntry">
     <property name="jndiName">
       <value>java:comp/env/jdbc/jetspeed</value>
     </property>
   </bean>     
   
   <!-- If would like use a commons DBCP Pooled datasource as opposed to the default 
-	   JNDI one above you can uncomment the configuration below and fill in 
-	   the datasource information as it relates to your environment.
-	-->
+       JNDI one above you can uncomment the configuration below and fill in 
+       the datasource information as it relates to your environment.
+
+       A requirement for this to work is to have the 
+       ConnectionFactoryClass=org.apache.ojb.broker.accesslayer.ConnectionFactoryDBCPImpl
+       or to have
+       ConnectionManagerClass=org.apache.jetspeed.components.rdbms.ojb.ConnectionManagerImpl
+       This property is located in /etc/db-ojb/OJB.properties in the source tree.
+    -->
 	<!--
-    <bean id="JetspeedDS" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
+    <bean id="JetspeedDS" class="org.apache.jetspeed.components.rdbms.ojb.ConnectionRepositoryEntry">
     <property name="driverClassName">
       <value>{my.drivers.class.name}</value>
     </property>
@@ -47,9 +54,4 @@
    </bean>      
    -->
   
-  <!-- OJB Locale Configurer 
-	 - see: http://www.springframework.org/docs/reference/orm.html#d0e7571
-	-->
-	
-  <bean id="ojbConfigurer" class="org.springframework.orm.ojb.support.LocalOjbConfigurer"/>    	
-</beans>
\ No newline at end of file
+</beans>



---------------------------------------------------------------------
To unsubscribe, e-mail: jetspeed-dev-unsubscribe@portals.apache.org
For additional commands, e-mail: jetspeed-dev-help@portals.apache.org