[jboss-svn-commits] JBL Code SVN: r17914 - in labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product: rosetta/src/org/jboss/internal/soa/esb/couriers and 13 other directories.

jboss-svn-commits at lists.jboss.org jboss-svn-commits at lists.jboss.org
Thu Jan 17 04:43:33 EST 2008


Author: kevin.conner at jboss.com
Date: 2008-01-17 04:43:33 -0500 (Thu, 17 Jan 2008)
New Revision: 17914

Added:
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/helpers/NamingContextException.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/helpers/NamingContextPool.java
Modified:
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/internal/soa/esb/command/JmsCommandQueue.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/internal/soa/esb/couriers/JmsCourier.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/internal/soa/esb/rosetta/pooling/JmsConnectionPool.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/actions/routing/JMSRouter.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/common/Configuration.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/common/Environment.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/helpers/NamingContext.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/lifecycle/LifecyclePriorities.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/lifecycle/LifecycleResourceManager.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/listeners/gateway/JmsGatewayListener.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/notification/NotifyJMS.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/notification/NotifyQueues.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/notification/NotifyTopics.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/common/tests/utils/DrainQueuesAndTopics.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/helpers/AppServerContextUnitTest.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/notification/NotifyQueuesUnitTest.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/notification/NotifyTopicsUnitTest.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/rosetta/pooling/JmsConnectionPoolingIntegrationTest.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/services/jbossesb/src/main/java/org/jboss/internal/soa/esb/persistence/format/jcr/JCRConnectionManager.java
   labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/services/smooks/src/main/java/org/jboss/soa/esb/actions/converters/SmooksInstanceManager.java
Log:
Moved NamingContext over to pooled version: JBESB-1484

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/internal/soa/esb/command/JmsCommandQueue.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/internal/soa/esb/command/JmsCommandQueue.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/internal/soa/esb/command/JmsCommandQueue.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -23,7 +23,8 @@
 import org.apache.log4j.Logger;
 import org.jboss.soa.esb.ConfigurationException;
 import org.jboss.soa.esb.helpers.ConfigTree;
-import org.jboss.soa.esb.helpers.NamingContext;
+import org.jboss.soa.esb.helpers.NamingContextException;
+import org.jboss.soa.esb.helpers.NamingContextPool;
 import org.jboss.soa.esb.util.Util;
 
 /**
@@ -121,7 +122,7 @@
 		return null;
 	}
 
-	private void initialiseJMS (ConfigTree p_oP) throws ConfigurationException, JMSException, NamingException
+	private void initialiseJMS (ConfigTree p_oP) throws ConfigurationException, JMSException, NamingException, NamingContextException
 	{
 		// Only check for JMS attributes if a queue JNDI name was specified
 		String sJndiName = p_oP.getAttribute(COMMAND_JNDI_NAME);
@@ -143,7 +144,9 @@
 			String sJndiPkgPrefix = obtainAtt(p_oP, COMMAND_JNDI_PKG_PREFIX,"");
             environment.put(Context.URL_PKG_PREFIXES, sJndiPkgPrefix);
 			oNewAtts.put(COMMAND_JNDI_PKG_PREFIX, sJndiPkgPrefix);
-			Context oJndiCtx = NamingContext.getServerContext(environment);
+			Context oJndiCtx = NamingContextPool.getNamingContext(environment);
+			try
+			{
 
 			String sFactClass = obtainAtt(p_oP, COMMAND_CONN_FACTORY,
 					"ConnectionFactory");
@@ -156,7 +159,7 @@
 			{
 				oFactCls = oJndiCtx.lookup(sFactClass);
 			} catch (NamingException ne) {
-                oJndiCtx = NamingContext.getFreshServerContext(environment);
+                oJndiCtx = NamingContextPool.replaceNamingContext(oJndiCtx, environment);
                 try {
                     oFactCls = oJndiCtx.lookup(sFactClass);
                 } catch (NamingException ex) {
@@ -210,7 +213,11 @@
 				m_oJmsSess = oSess;
 				m_oCmdSrc = oSess.createReceiver(oQ, sMsgSelector);
 			}
-            oJndiCtx.close();
+			}
+			finally
+			{
+			    NamingContextPool.releaseNamingContext(oJndiCtx) ;
+			}
 		}
 	}
 

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/internal/soa/esb/couriers/JmsCourier.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/internal/soa/esb/couriers/JmsCourier.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/internal/soa/esb/couriers/JmsCourier.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -52,7 +52,8 @@
 import org.jboss.soa.esb.couriers.CourierException;
 import org.jboss.soa.esb.couriers.CourierTimeoutException;
 import org.jboss.soa.esb.helpers.KeyValuePair;
-import org.jboss.soa.esb.helpers.NamingContext;
+import org.jboss.soa.esb.helpers.NamingContextException;
+import org.jboss.soa.esb.helpers.NamingContextPool;
 import org.jboss.soa.esb.listeners.gateway.DefaultESBPropertiesSetter;
 import org.jboss.soa.esb.listeners.gateway.ESBPropertiesSetter;
 import org.jboss.soa.esb.message.Message;
@@ -186,7 +187,11 @@
         }
 
         if (_messageProducer == null) {
-            createMessageProducer();
+            try {
+                createMessageProducer();
+            } catch (final NamingContextException nce) {
+                throw new CourierException("Unexpected exception attempting to access naming context pool", nce) ;
+            }
         }
 
         // Create the JMS message from the serialized ESB message...
@@ -228,7 +233,11 @@
         }
 
         if (_messageProducer == null) {
-            createMessageProducer();
+            try {
+                createMessageProducer();
+            } catch (final NamingContextException nce) {
+                throw new CourierException("Unexpected exception attempting to access naming context pool", nce) ;
+            }
         }
 
         while (null != _messageProducer) {
@@ -303,14 +312,14 @@
         }
     } // ________________________________
 
-    private void createMessageProducer() throws CourierException {
+    private void createMessageProducer() throws CourierException, NamingContextException {
         Context oJndiCtx = null;
 
         if (_messageProducer == null) {
             synchronized(this) {
                 if (_messageProducer == null) {
                     try {
-                        oJndiCtx = NamingContext.getServerContext(_epr.getJndiEnvironment());
+                        oJndiCtx = NamingContextPool.getNamingContext(_epr.getJndiEnvironment());
 
                         String sType = _epr.getDestinationType();
                         if (JMSEpr.QUEUE_TYPE.equals(sType)) {
@@ -321,7 +330,7 @@
                                         .getDestinationName());
                             } catch (NamingException ne) {
                                 try {
-                                    oJndiCtx = NamingContext.getFreshServerContext(_epr.getJndiEnvironment());
+                                    oJndiCtx = NamingContextPool.replaceNamingContext(oJndiCtx, _epr.getJndiEnvironment());
                                     queue = (javax.jms.Queue) oJndiCtx.lookup(_epr
                                             .getDestinationName());
                                 } catch (NamingException nex) {
@@ -355,6 +364,10 @@
                     }
                     catch (URISyntaxException ex) {
                         throw new CourierException(ex);
+                    } finally {
+                        if (oJndiCtx != null) {
+                            NamingContextPool.releaseNamingContext(oJndiCtx) ;
+                        }
                     }
                 }
             }
@@ -475,7 +488,7 @@
         esbPropertiesStrategy.setPropertiesFromJMSMessage(fromJMS, toESB);
     }
 
-    private void createMessageConsumer() throws CourierException, ConfigurationException, MalformedEPRException {
+    private void createMessageConsumer() throws CourierException, ConfigurationException, MalformedEPRException, NamingContextException {
         Context oJndiCtx = null;
 
         if (_messageConsumer == null) {
@@ -484,38 +497,39 @@
                     boolean success = false;
                     try {
                         Properties environment = _epr.getJndiEnvironment();
-                        oJndiCtx = NamingContext.getServerContext(environment);
-                        if (null == oJndiCtx)
-                            throw new ConfigurationException(
-                                    "Unable fo obtain jndi context");
-
-                        String sType = _epr.getDestinationType();
-                        if (JMSEpr.QUEUE_TYPE.equals(sType)) {
-                            QueueSession qSess = (QueueSession) getJmsSession(_epr.getAcknowledgeMode());
-                            javax.jms.Queue queue = null;
-                            try {
-                                queue = (javax.jms.Queue) oJndiCtx.lookup(_epr
-                                        .getDestinationName());
-                            } catch (NamingException ne) {
+                        oJndiCtx = NamingContextPool.getNamingContext(environment);
+                        try
+                        {
+                            String sType = _epr.getDestinationType();
+                            if (JMSEpr.QUEUE_TYPE.equals(sType)) {
+                                QueueSession qSess = (QueueSession) getJmsSession(_epr.getAcknowledgeMode());
+                                javax.jms.Queue queue = null;
                                 try {
-                                    oJndiCtx = NamingContext.getFreshServerContext(environment);
                                     queue = (javax.jms.Queue) oJndiCtx.lookup(_epr
                                             .getDestinationName());
-                                } catch (NamingException nex) {
-                                    //ActiveMQ
-                                    queue = qSess.createQueue(_epr.getDestinationName());
+                                } catch (NamingException ne) {
+                                    try {
+                                        oJndiCtx = NamingContextPool.replaceNamingContext(oJndiCtx, environment);
+                                        queue = (javax.jms.Queue) oJndiCtx.lookup(_epr
+                                                .getDestinationName());
+                                    } catch (NamingException nex) {
+                                        //ActiveMQ
+                                        queue = qSess.createQueue(_epr.getDestinationName());
+                                    }
                                 }
+                                _messageConsumer = qSess.createReceiver(queue, _epr.getMessageSelector());
+                            } else if (JMSEpr.TOPIC_TYPE.equals(sType)) {
+                                TopicSession tSess = (TopicSession) getJmsSession(_epr.getAcknowledgeMode());
+                                Topic topic = tSess.createTopic(_epr.getDestinationName());
+                                _messageConsumer = tSess.createConsumer(topic, _epr
+                                        .getMessageSelector());
+                            } else {
+                                throw new CourierException("Unknown destination type");
                             }
-                            _messageConsumer = qSess.createReceiver(queue, _epr.getMessageSelector());
-                        } else if (JMSEpr.TOPIC_TYPE.equals(sType)) {
-                            TopicSession tSess = (TopicSession) getJmsSession(_epr.getAcknowledgeMode());
-                            Topic topic = tSess.createTopic(_epr.getDestinationName());
-                            _messageConsumer = tSess.createConsumer(topic, _epr
-                                    .getMessageSelector());
-                        } else {
-                            throw new CourierException("Unknown destination type");
+                            success = true;
+                        } finally {
+                            NamingContextPool.releaseNamingContext(oJndiCtx) ;
                         }
-                        success = true;
                     }
                     catch (JMSException ex) {
                         _logger.debug("Error from JMS system.", ex);

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/internal/soa/esb/rosetta/pooling/JmsConnectionPool.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/internal/soa/esb/rosetta/pooling/JmsConnectionPool.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/internal/soa/esb/rosetta/pooling/JmsConnectionPool.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -44,7 +44,8 @@
 import org.jboss.soa.esb.addressing.eprs.JMSEpr;
 import org.jboss.soa.esb.common.Environment;
 import org.jboss.soa.esb.common.ModulePropertyManager;
-import org.jboss.soa.esb.helpers.NamingContext;
+import org.jboss.soa.esb.helpers.NamingContextException;
+import org.jboss.soa.esb.helpers.NamingContextPool;
 
 import com.arjuna.common.util.propertyservice.PropertyManager;
 
@@ -85,9 +86,6 @@
     /** Logger */
     private Logger logger = Logger.getLogger(this.getClass());
     
-    /** Context, which is cached until we encounter a naming exception, or the pool is rebuild */
-    private Context jndiContext;
-    
     /**
      * Contructor of the pool.
      * 
@@ -122,7 +120,7 @@
      * @throws ConnectionException
      */
     private  synchronized void addAnotherSession(Map<String, String> poolKey, final int acknowledgeMode)
-    throws NamingException, JMSException, ConnectionException
+    throws NamingException, JMSException, ConnectionException, NamingContextException
     {
         String destinationType = poolKey.get(JMSEpr.DESTINATION_TYPE_TAG);
         
@@ -131,36 +129,40 @@
             JmsConnectionPoolContainer.addToPool(poolKey, this);
             logger.debug("Creating a JMS Connection for poolKey : " + poolKey);
             Properties jndiEnvironment = JmsConnectionPoolContainer.getJndiEnvironment(poolKey);
-            jndiContext = NamingContext.getServerContext(jndiEnvironment);
-            String connectionFactoryString = poolKey.get(JMSEpr.CONNECTION_FACTORY_TAG);
-            Object factoryConnection=null;
+            Context jndiContext = NamingContextPool.getNamingContext(jndiEnvironment);
             try {
-                factoryConnection = jndiContext.lookup(connectionFactoryString);
-            } catch (NamingException ne) {
-                logger.info("Received NamingException, refreshing context.");
-                jndiContext = NamingContext.getFreshServerContext(JmsConnectionPoolContainer.getJndiEnvironment(poolKey));
-                factoryConnection = jndiContext.lookup(connectionFactoryString);
+                String connectionFactoryString = poolKey.get(JMSEpr.CONNECTION_FACTORY_TAG);
+                Object factoryConnection=null;
+                try {
+                    factoryConnection = jndiContext.lookup(connectionFactoryString);
+                } catch (NamingException ne) {
+                    logger.info("Received NamingException, refreshing context.");
+                    jndiContext = NamingContextPool.replaceNamingContext(jndiContext, JmsConnectionPoolContainer.getJndiEnvironment(poolKey));
+                    factoryConnection = jndiContext.lookup(connectionFactoryString);
+                }
+                final String username = poolKey.get( JMSEpr.JMS_SECURITY_PRINCIPAL_TAG );
+                final String password = poolKey.get( JMSEpr.JMS_SECURITY_CREDENTIAL_TAG );
+                boolean useJMSSecurity = (username != null && password != null);
+                logger.debug( "JMS Security principal [" + username + "] using JMS Security : " + useJMSSecurity );
+                
+                if (JMSEpr.QUEUE_TYPE.equals(destinationType)) {
+                    QueueConnectionFactory factory = (QueueConnectionFactory) factoryConnection;
+                    jmsConnection = useJMSSecurity ? factory.createQueueConnection(username,password): factory.createQueueConnection();
+                } else {
+                    TopicConnectionFactory factory = (TopicConnectionFactory) factoryConnection;
+                    jmsConnection = useJMSSecurity ? factory.createTopicConnection(username,password): factory.createTopicConnection();
+                }
+                
+                jmsConnection.setExceptionListener(new ExceptionListener() {
+                    public void onException(JMSException arg0)
+                    {
+                        removeSessionPool() ;
+                    }
+                }) ;
+                jmsConnection.start();
+            } finally {
+                NamingContextPool.releaseNamingContext(jndiContext) ;
             }
-            final String username = poolKey.get( JMSEpr.JMS_SECURITY_PRINCIPAL_TAG );
-            final String password = poolKey.get( JMSEpr.JMS_SECURITY_CREDENTIAL_TAG );
-            boolean useJMSSecurity = (username != null && password != null);
-            logger.debug( "JMS Security principal [" + username + "] using JMS Security : " + useJMSSecurity );
-            
-            if (JMSEpr.QUEUE_TYPE.equals(destinationType)) {
-                QueueConnectionFactory factory = (QueueConnectionFactory) factoryConnection;
-                jmsConnection = useJMSSecurity ? factory.createQueueConnection(username,password): factory.createQueueConnection();
-            } else {
-                TopicConnectionFactory factory = (TopicConnectionFactory) factoryConnection;
-                jmsConnection = useJMSSecurity ? factory.createTopicConnection(username,password): factory.createTopicConnection();
-            }
-            
-            jmsConnection.setExceptionListener(new ExceptionListener() {
-                public void onException(JMSException arg0)
-                {
-                    removeSessionPool() ;
-                }
-            }) ;
-            jmsConnection.start();
         }
         final boolean transacted = Boolean.valueOf(poolKey.get(JMSEpr.TRANSACTED_TAG));
         
@@ -205,7 +207,12 @@
                 inUseSessions.add(session);
                 return session ;
             } else if (inUseSessions.size()<MAX_SESSIONS) {
-                addAnotherSession(poolKey,acknowledgeMode);
+                try {
+                    addAnotherSession(poolKey,acknowledgeMode);
+                } catch (final NamingContextException nce) {
+                    throw new ConnectionException("Unexpected exception accessing Naming Context", nce) ;
+                }
+                
                 continue ;
             } else {
                 if (emitExpiry)

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/actions/routing/JMSRouter.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/actions/routing/JMSRouter.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/actions/routing/JMSRouter.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -50,7 +50,8 @@
 import org.jboss.soa.esb.common.Configuration;
 import org.jboss.soa.esb.helpers.ConfigTree;
 import org.jboss.soa.esb.helpers.KeyValuePair;
-import org.jboss.soa.esb.helpers.NamingContext;
+import org.jboss.soa.esb.helpers.NamingContextException;
+import org.jboss.soa.esb.helpers.NamingContextPool;
 import org.jboss.soa.esb.notification.jms.DefaultJMSPropertiesSetter;
 import org.jboss.soa.esb.notification.jms.JMSPropertiesSetter;
 import org.jboss.soa.esb.util.Util;
@@ -329,38 +330,41 @@
         
         // TODO: Modify to support topic destinations too
 
-        private JMSSendQueueSetup(String queueName) throws NamingException, JMSException, ConnectionException  {
+        private JMSSendQueueSetup(String queueName) throws NamingException, JMSException, ConnectionException, NamingContextException  {
             environment = new Properties();
             environment.setProperty(Context.PROVIDER_URL, Configuration.getJndiServerURL());
             environment.setProperty(Context.INITIAL_CONTEXT_FACTORY, Configuration.getJndiServerContextFactory());
             environment.setProperty(Context.URL_PKG_PREFIXES, Configuration.getJndiServerPkgPrefix());
-            Context oCtx = NamingContext.getServerContext(environment);
-            pool = JmsConnectionPoolContainer.getPool(environment, "ConnectionFactory", JMSEpr.QUEUE_TYPE);
-            
-            this.queueName = queueName;
-            
-            jmsSession = pool.getQueueSession();
-            boolean clean = true ;
+            Context oCtx = NamingContextPool.getNamingContext(environment);
             try {
+                pool = JmsConnectionPoolContainer.getPool(environment, "ConnectionFactory", JMSEpr.QUEUE_TYPE);
+                
+                this.queueName = queueName;
+                
+                jmsSession = pool.getQueueSession();
+                boolean clean = true ;
                 try {
-                	jmsQueue = (Queue) oCtx.lookup(queueName);
-                } catch (NamingException ne) {
                     try {
-                        oCtx = NamingContext.getFreshServerContext(environment);
-                        jmsQueue = (Queue) oCtx.lookup(queueName);
-                    } catch (NamingException nex) {
-                        //ActiveMQ
-                        jmsQueue = jmsSession.createQueue(queueName);
+                    	jmsQueue = (Queue) oCtx.lookup(queueName);
+                    } catch (NamingException ne) {
+                        try {
+                            oCtx = NamingContextPool.replaceNamingContext(oCtx, environment);
+                            jmsQueue = (Queue) oCtx.lookup(queueName);
+                        } catch (NamingException nex) {
+                            //ActiveMQ
+                            jmsQueue = jmsSession.createQueue(queueName);
+                        }
                     }
+                    jmsProducer = jmsSession.createSender(jmsQueue);
+                    clean = false ;
+                } finally {
+                    if (clean) {
+                        pool.closeSession(jmsSession) ;
+                    }
                 }
-                jmsProducer = jmsSession.createSender(jmsQueue);
-                clean = false ;
             } finally {
-                if (clean) {
-                    pool.closeSession(jmsSession) ;
-                }
+                NamingContextPool.releaseNamingContext(oCtx) ;
             }
-            
         }
         
         public void setDeliveryMode(final int deliveryMode ) throws JMSException

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/common/Configuration.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/common/Configuration.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/common/Configuration.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -26,12 +26,14 @@
 
 import javax.jms.ConnectionFactory;
 import javax.naming.Context;
+import javax.naming.InitialContext;
 import javax.naming.NamingException;
 
 import org.apache.log4j.Logger;
 import org.jboss.soa.esb.ConfigurationException;
 import org.jboss.soa.esb.helpers.KeyValuePair;
-import org.jboss.soa.esb.helpers.NamingContext;
+import org.jboss.soa.esb.helpers.NamingContextException;
+import org.jboss.soa.esb.helpers.NamingContextPool;
 
 public class Configuration
 {
@@ -340,43 +342,48 @@
 	 * <p/>
 	 * The module/section parameters are:
 	 * <ol>
-	 * 	<li><b>{@link Context#PROVIDER_URL}</b>: Value defaults to "{@link NamingContext#JBOSS_PROVIDER_URL}".</li>
-	 * 	<li><b>{@link Context#INITIAL_CONTEXT_FACTORY}</b>: Value defaults to "{@link NamingContext#JBOSS_INITIAL_CONTEXT_FACTORY}".</li>
-	 * 	<li><b>{@link Context#URL_PKG_PREFIXES}</b>: Value defaults to "{@link NamingContext#JBOSS_URL_PKG_PREFIX}".</li>
+	 * 	<li><b>{@link Context#PROVIDER_URL}</b>: Value defaults to "{@link Environment#JBOSS_PROVIDER_URL}".</li>
+	 * 	<li><b>{@link Context#INITIAL_CONTEXT_FACTORY}</b>: Value defaults to "{@link Environment#JBOSS_INITIAL_CONTEXT_FACTORY}".</li>
+	 * 	<li><b>{@link Context#URL_PKG_PREFIXES}</b>: Value defaults to "{@link Environment#JBOSS_URL_PKG_PREFIX}".</li>
 	 * </ol>
 	 * 
 	 * @param contextModuleName Conficuration module/section name.
 	 * @return The context instance.
 	 * @throws ConfigurationException Unable to connect to context.
+	 * 
+	 * @deprecated {@link org.jboss.soa.esb.helpers.NamingContextPool}
 	 */
 	public static Context getNamingContext(String contextModuleName) throws ConfigurationException {
-		String providerUrl = ModulePropertyManager.getPropertyManager(contextModuleName).getProperty(Context.PROVIDER_URL, NamingContext.JBOSS_PROVIDER_URL);
-		String initialContextFactory = ModulePropertyManager.getPropertyManager(contextModuleName).getProperty(Context.INITIAL_CONTEXT_FACTORY, NamingContext.JBOSS_INITIAL_CONTEXT_FACTORY);
-		String urlPackagePrefix = ModulePropertyManager.getPropertyManager(contextModuleName).getProperty(Context.URL_PKG_PREFIXES, NamingContext.JBOSS_URL_PKG_PREFIX);
-		Properties environment = new Properties();
-        environment.setProperty(Context.PROVIDER_URL, providerUrl);
-        environment.setProperty(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
-        environment.setProperty(Context.URL_PKG_PREFIXES, urlPackagePrefix);
+	    final Properties environment = getProperties(contextModuleName) ;
 		
-        Context context = NamingContext.getServerContext(environment);
-		if(context == null) {
-			// Would be nice if NamingContext.getServerContext threw an exception with
-			// details attached.
-			throw new ConfigurationException("Failed to JNDI context [" + contextModuleName + "].");
-		}
-		
-		return context;
+        try {
+            return new InitialContext(environment) ;
+        } catch (final NamingException ne) {
+            throw new ConfigurationException("Failed to create JNDI context [" + contextModuleName + "].");
+        }
 	}
 	
+	private static Properties getProperties(final String contextModuleName)
+	{
+            final String providerUrl = ModulePropertyManager.getPropertyManager(contextModuleName).getProperty(Context.PROVIDER_URL, Environment.JBOSS_PROVIDER_URL);
+            final String initialContextFactory = ModulePropertyManager.getPropertyManager(contextModuleName).getProperty(Context.INITIAL_CONTEXT_FACTORY, Environment.JBOSS_INITIAL_CONTEXT_FACTORY);
+            final String urlPackagePrefix = ModulePropertyManager.getPropertyManager(contextModuleName).getProperty(Context.URL_PKG_PREFIXES, Environment.JBOSS_URL_PKG_PREFIX);
+            final Properties environment = new Properties();
+            environment.setProperty(Context.PROVIDER_URL, providerUrl);
+            environment.setProperty(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
+            environment.setProperty(Context.URL_PKG_PREFIXES, urlPackagePrefix);
+            return environment ;
+	}
+	
 	/**
 	 * Lookup the JMS Connection Factory based on the connection details outlined
 	 * in the named configuration module/section.
 	 * <p/>
 	 * The module/section parameters are:
 	 * <ol>
-	 * 	<li><b>{@link Context#PROVIDER_URL}</b>: Value defaults to "{@link NamingContext#JBOSS_PROVIDER_URL}".</li>
-	 * 	<li><b>{@link Context#INITIAL_CONTEXT_FACTORY}</b>: Value defaults to "{@link NamingContext#JBOSS_INITIAL_CONTEXT_FACTORY}".</li>
-	 * 	<li><b>{@link Context#URL_PKG_PREFIXES}</b>: Value defaults to "{@link NamingContext#JBOSS_URL_PKG_PREFIX}".</li>
+	 * 	<li><b>{@link Context#PROVIDER_URL}</b>: Value defaults to "{@link Environment#JBOSS_PROVIDER_URL}".</li>
+	 * 	<li><b>{@link Context#INITIAL_CONTEXT_FACTORY}</b>: Value defaults to "{@link Environment#JBOSS_INITIAL_CONTEXT_FACTORY}".</li>
+	 * 	<li><b>{@link Context#URL_PKG_PREFIXES}</b>: Value defaults to "{@link Environment#JBOSS_URL_PKG_PREFIX}".</li>
 	 * 	<li><b>javax.jms.ConnectionFactory</b>: Value defaults to "".</li>
 	 * </ol>
 	 * 
@@ -386,26 +393,26 @@
 	 * lookup the context, or the ConnectionFactory lookup failed.
 	 */
 	public static ConnectionFactory getJmsConnectionFactory(String jmsConnectionFactoryModuleName) throws ConfigurationException {
-		Context context = getNamingContext(jmsConnectionFactoryModuleName);
-		String connectionFactoryRuntime = ModulePropertyManager.getPropertyManager(jmsConnectionFactoryModuleName).getProperty(ConnectionFactory.class.getName(), "ConnectionFactory");
-		ConnectionFactory factory = null;
-		
-		try {
-			factory = (ConnectionFactory) context.lookup(connectionFactoryRuntime);
-		} catch (NamingException e) {
-			throw new ConfigurationException("JNDI lookup of JMS Connection Factory [" + connectionFactoryRuntime + "] failed.", e);
-		} catch (ClassCastException e) {
-			throw new ConfigurationException("JNDI lookup of JMS Connection Factory failed.  Class [" + connectionFactoryRuntime + "] is not an instance of [" + ConnectionFactory.class.getName() + "].", e);
-		} finally {
-            if (context!=null) {
-                try {
-                    context.close();
-                } catch (NamingException ne) {
-                    _logger.error(ne.getMessage(), ne);
-                }
-            }   
+	        final Properties environment = getProperties(jmsConnectionFactoryModuleName) ;
+	        try {
+	            Context context = NamingContextPool.getNamingContext(environment);
+	            try {
+                        String connectionFactoryRuntime = ModulePropertyManager.getPropertyManager(jmsConnectionFactoryModuleName).getProperty(ConnectionFactory.class.getName(), "ConnectionFactory");
+                        ConnectionFactory factory = null;
+                        
+                        try {
+                                factory = (ConnectionFactory) context.lookup(connectionFactoryRuntime);
+                        } catch (NamingException e) {
+                                throw new ConfigurationException("JNDI lookup of JMS Connection Factory [" + connectionFactoryRuntime + "] failed.", e);
+                        } catch (ClassCastException e) {
+                                throw new ConfigurationException("JNDI lookup of JMS Connection Factory failed.  Class [" + connectionFactoryRuntime + "] is not an instance of [" + ConnectionFactory.class.getName() + "].", e);
+                        }
+                        return factory;
+	            } finally {
+	                NamingContextPool.releaseNamingContext(context) ;
+	            }
+	        } catch (final NamingContextException nce) {
+	            throw new ConfigurationException("Unexpected exception while accessing naming context pool", nce) ;
+	        }
         }
-		
-		return factory;
-	}
-}
\ No newline at end of file
+}

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/common/Environment.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/common/Environment.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/common/Environment.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -192,4 +192,30 @@
 	
 	public static final String MESSAGE_TRACE = "org.jboss.soa.esb.messagetrace"; // on or off
 	public static final String PER_MESSAGE_TRACE = "org.jboss.soa.esb.permessagetrace"; // on or off
+	
+	// Configuration options for the Naming Context pooling.
+	/**
+	 * The maximum pool size.
+	 */
+	public static final String NAMING_CONTEXT_POOL_SIZE = "org.jboss.soa.esb.namingcontext.poolsize" ;
+	/**
+	 * The maximum sleep period when waiting for a naming context, specified in seconds.
+	 */
+        public static final String NAMING_CONTEXT_SLEEP_PERIOD = "org.jboss.soa.esb.namingcontext.sleepperiod" ;
+        /**
+         * The maximum number of retries when creating a naming context.
+         */
+        public static final String NAMING_CONTEXT_RETRY_COUNT = "org.jboss.soa.esb.namingcontext.retrycount" ;
+        /**
+         * The JBoss JNDI provider URL. 
+         */
+        public static final String JBOSS_PROVIDER_URL = "localhost";
+        /**
+         * The JBoss JNDI initial context factory. 
+         */
+        public static final String JBOSS_INITIAL_CONTEXT_FACTORY = "org.jnp.interfaces.NamingContextFactory";
+        /**
+         * The JBoss JNDI URL package prefix. 
+         */
+        public static final String JBOSS_URL_PKG_PREFIX = ""; //"org.jboss.naming:org.jnp.interfaces"
 }

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/helpers/NamingContext.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/helpers/NamingContext.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/helpers/NamingContext.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -33,6 +33,7 @@
 /**
  * Obtains JNDI naming context.
  * 
+ * @deprecated {@link org.jboss.soa.esb.helpers.NamingContextPool}
  */
 public class NamingContext 
 {

Added: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/helpers/NamingContextException.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/helpers/NamingContextException.java	                        (rev 0)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/helpers/NamingContextException.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -0,0 +1,69 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2006, JBoss Inc., and individual contributors as indicated
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.soa.esb.helpers;
+
+/**
+ * Exception used for Naming Connection Pool errors.
+ */
+public class NamingContextException extends Exception
+{
+    /**
+     * The serial version UID for this exception.
+     */
+    private static final long serialVersionUID = 8246625119667566368L;
+
+    /**
+     * Create a naming context exception.
+     */
+    public NamingContextException()
+    {
+        super() ;
+    }
+
+    /**
+     * Create a naming context exception with the specified message.
+     * @param message The message associated with the exception.
+     */
+    public NamingContextException(final String message)
+    {
+        super(message) ;
+    }
+
+    /**
+     * Create a naming context exception with the specified cause.
+     * @param cause The cause associated with the exception.
+     */
+    public NamingContextException(final Throwable cause)
+    {
+        super(cause) ;
+    }
+
+    /**
+     * Create a naming context exception with the specified message and cause.
+     * @param message The message associated with the exception.
+     * @param cause The cause associated with the exception.
+     */
+    public NamingContextException(final String message, final Throwable cause)
+    {
+        super(message, cause) ;
+    }
+}


Property changes on: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/helpers/NamingContextException.java
___________________________________________________________________
Name: svn:keywords
   + Rev Date
Name: svn:eol-style
   + native

Added: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/helpers/NamingContextPool.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/helpers/NamingContextPool.java	                        (rev 0)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/helpers/NamingContextPool.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -0,0 +1,522 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2006, JBoss Inc., and individual contributors as indicated
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.soa.esb.helpers;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.TreeMap;
+import java.util.Map.Entry;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NameNotFoundException;
+import javax.naming.NamingException;
+
+import org.apache.log4j.Logger;
+import org.jboss.soa.esb.common.Environment;
+import org.jboss.soa.esb.common.ModulePropertyManager;
+import org.jboss.soa.esb.lifecycle.LifecyclePriorities;
+import org.jboss.soa.esb.lifecycle.LifecycleResource;
+import org.jboss.soa.esb.lifecycle.LifecycleResourceException;
+import org.jboss.soa.esb.lifecycle.LifecycleResourceFactory;
+
+import com.arjuna.common.util.propertyservice.PropertyManager;
+
+/**
+ * Pool for Naming Contexts.
+ * 
+ * @author <a href="mailto:kevin.conner at jboss.com">Kevin Conner</a>
+ */
+public class NamingContextPool
+{
+    /**
+     * Logger for this class
+     */
+    private static final Logger LOGGER = Logger.getLogger(NamingContextPool.class);
+    /**
+     * Default maximum pool size.
+     */
+    private static final int DEFAULT_POOL_SIZE = 20 ;
+    /**
+     * Default sleep period.
+     */
+    private static final int DEFAULT_SLEEP_PERIOD = 30 ;
+    /**
+     * Default retry count for creating Naming Contexts.
+     */
+    private static final int DEFAULT_RETRY_COUNT = 10 ;
+    /**
+     * Default key for environments.
+     */
+    private static final String DEFAULT_KEY = "<empty key>" ;
+    /**
+     * Maximum pool size.
+     */
+    private static final int POOL_SIZE ;
+    /**
+     * Sleep period.
+     */
+    private static final int SLEEP_PERIOD ;
+    /**
+     * Retry count for creating Naming Contexts.
+     */
+    private static final int RETRY_COUNT ;
+
+    /**
+     * The lifecycle resource factory.
+     */
+    private static final LifecycleResourceFactory<NamingContextPool> lifecycleNamingContextPoolFactory =
+        new NamingContextPoolFactory();
+
+    /**
+     * The lifecycle Naming Context pools.
+     */
+    private static final LifecycleResource<NamingContextPool> lifecycleNamingContextPoolResource =
+        new LifecycleResource<NamingContextPool>(lifecycleNamingContextPoolFactory,
+            LifecyclePriorities.NAMING_CONTEXT_POOL_PRIORITY);
+    
+    /**
+     * The free contexts.
+     */
+    private final Map<String, List<Context>> freeContexts = new HashMap<String, List<Context>>() ;
+    /**
+     * The free contexts in insertion order.
+     */
+    private final Map<Context, String> freeContextOrder = new LinkedHashMap<Context, String>() ;
+    /**
+     * The in use contexts.
+     */
+    private final Map<Context, String> inUseContexts = new HashMap<Context, String>() ;
+    /**
+     * The count of created contexts.
+     */
+    private int numContexts ;
+    /**
+     * True if the pool has been destroyed.
+     */
+    private boolean destroyed ;
+    
+    /**
+     * Private constructor.
+     */
+    private NamingContextPool()
+    {
+    }
+    
+    /**
+     * Get a Naming Context from the pool.
+     * @param env The JNDI environment parameters for the Naming Context.
+     * @return The Naming Context.
+     * @throws NamingContextException for errors obtaining a Naming Context.
+     */
+    Context getContext(final Properties env)
+        throws NamingContextException
+    {
+        final long end = System.currentTimeMillis() + (SLEEP_PERIOD * 1000) ;
+        final String key = getKey(env) ;
+        boolean emitExpiry = LOGGER.isDebugEnabled() ;
+        synchronized(this)
+        {
+            while(true)
+            {
+                if (destroyed)
+                {
+                    throw new NamingContextException("Naming Context Pool has been previosuly destroyed") ;
+                }
+                final Context context = getContext(env, key) ;
+                if (context != null)
+                {
+                    return context ;
+                }
+                if (emitExpiry)
+                {
+                    LOGGER.debug("The Naming Context pool was exhausted, waiting for one to be released.") ;
+                    emitExpiry = false ;
+                }
+                final long now = System.currentTimeMillis() ;
+                final long delay = (end - now) ;
+                if (delay <= 0)
+                {
+                    throw new NamingContextException("Could not obtain a Naming Context from the pool after " + SLEEP_PERIOD + "s.") ;
+                }
+                else
+                {
+                    try
+                    {
+                        wait(delay) ;
+                    }
+                    catch (final InterruptedException ie) {} // ignore
+                }
+            }
+        }
+    }
+    
+    /**
+     * Release the Naming Context back into the pool.
+     * @param context The Naming Context.
+     * @throws NamingContextException for errors releasing the Naming Context.
+     */
+    synchronized void releaseContext(final Context context)
+        throws NamingContextException
+    {
+        if (destroyed)
+        {
+            throw new NamingContextException("Naming Context Pool has been previosuly destroyed") ;
+        }
+        final String key = inUseContexts.remove(context) ;
+        if (key == null)
+        {
+            throw new NamingContextException("Cannot release a context which is not in use.") ;
+        }
+        
+        freeContextOrder.put(context, key) ;
+        final List<Context> contexts = freeContexts.get(key) ;
+        if (contexts != null)
+        {
+            contexts.add(context) ;
+        }
+        else
+        {
+            final List<Context> newContexts = new ArrayList<Context>() ;
+            newContexts.add(context) ;
+            freeContexts.put(key, newContexts) ;
+        }
+        
+        notifyAll() ;
+    }
+    
+    /**
+     * Replace the specified Naming Context.
+     * @param context The Naming Context to replace.
+     * @param env The JNDI environment parameters for the Naming Context.
+     * @return The new Naming Context
+     * @throws NamingContextException for errors releasing the Naming Context.
+     */
+    synchronized Context replaceContext(final Context context, final Properties env)
+        throws NamingContextException
+    {
+        if (destroyed)
+        {
+            throw new NamingContextException("Naming Context Pool has been previosuly destroyed") ;
+        }
+        final String key = inUseContexts.remove(context) ;
+        if (key == null)
+        {
+            throw new NamingContextException("Cannot release a context which is not in use.") ;
+        }
+        
+        numContexts-- ;
+        closeContext(context) ;
+        return createContext(env, key) ;
+    }
+
+    /**
+     * Closes all Contexts, and removes them from the contextCache.
+     */
+    synchronized void closeAllContexts()
+    {
+        closeAllContexts(freeContextOrder.keySet().iterator()) ;
+        if (inUseContexts.size() > 0)
+        {
+            LOGGER.warn("Forcing closure of in-use Naming Contexts") ;
+            closeAllContexts(inUseContexts.keySet().iterator()) ;
+        }
+        inUseContexts.clear() ;
+        freeContextOrder.clear() ;
+        freeContexts.clear() ;
+        destroyed = true ;
+    }
+    
+    /**
+     * Get a Naming Context from the pool.
+     * @param env The JNDI environment parameters for the Naming Context.
+     * @param key The key of the context to locate.
+     * @return The Naming Context.
+     * @throws NamingContextException for errors obtaining a Naming Context.
+     */
+    private Context getContext(final Properties env, final String key)
+        throws NamingContextException
+    {
+        final Context context = getFreeContext(key) ;
+        if (context != null)
+        {
+            return context ;
+        }
+        if (numContexts == POOL_SIZE)
+        {
+            if (freeContextOrder.size() == 0)
+            {
+                return null ;
+            }
+            final Iterator<Entry<Context, String>> freeContextIter = freeContextOrder.entrySet().iterator() ;
+            final Entry<Context, String> freeContextEntry = freeContextIter.next() ;
+            final Context freeContext = freeContextEntry.getKey() ;
+            final String freeContextKey = freeContextEntry.getValue() ;
+            if (LOGGER.isDebugEnabled())
+            {
+                LOGGER.debug("Ejecting Naming Context from pool, key: " + freeContextKey) ;
+            }
+            
+            freeContextOrder.remove(freeContext) ;
+            final List<Context> contexts = freeContexts.get(key) ;
+            contexts.remove(freeContext) ;
+            if (contexts.size() == 0)
+            {
+                freeContexts.remove(key) ;
+            }
+            
+            numContexts-- ;
+            closeContext(freeContext) ;
+        }
+        return createContext(env, key) ;
+    }
+    
+    /**
+     * Get a free Naming Context from the available list
+     * @param key The key of the context to return.
+     * @return The Naming Context or null if none present
+     */
+    private Context getFreeContext(final String key)
+    {
+        final List<Context> contexts = freeContexts.get(key) ;
+        if (contexts != null)
+        {
+            final int size = contexts.size() ;
+            if (size > 0)
+            {
+                final Context context = contexts.remove(size-1) ;
+                freeContextOrder.remove(context) ;
+                inUseContexts.put(context, key) ;
+                return context ;
+            }
+        }
+        return null ;
+    }
+    
+    /**
+     * Create the context with the specified environment and key.
+     * @param env The JNDI environment parameters for the Naming Context.
+     * @param key The key of the context to locate.
+     * @return The Naming Context.
+     * @throws NamingContextException for errors obtaining a Naming Context.
+     */
+    private Context createContext(final Properties env, final String key)
+        throws NamingContextException
+    {
+        NamingException cachedException = null ;
+        
+        for(int count = 0 ; count < RETRY_COUNT ; count++)
+        {
+            final Context context ;
+            try
+            {
+                context = new InitialContext(env) ;
+                
+                try
+                {
+                    context.list("__dummy2@#$%") ;
+                }
+                catch (final NameNotFoundException nfne) {} // Expected
+            }
+            catch (final NamingException ne)
+            {
+                cachedException = ne ;
+                continue ;
+            }
+            
+            inUseContexts.put(context, key) ;
+            numContexts++ ;
+            return context ;
+        }
+        
+        throw new NamingContextException("Failed to create Naming Context", cachedException) ;
+    }
+    
+    /**
+     * Close all the specified contexts.
+     * @param contextIter The iterator of Naming Contexts.
+     */
+    private void closeAllContexts(Iterator<Context> contextIter)
+    {
+        while(contextIter.hasNext())
+        {
+            closeContext(contextIter.next()) ;
+        }
+    }
+    
+    /**
+     * Close the specified Naming Context.
+     * @param context The Naming Context to close.
+     */
+    private void closeContext(final Context context)
+    {
+        try
+        {
+            context.close() ;
+        }
+        catch (final NamingException ne) {} // ignore
+    }
+    
+    static
+    {
+        final PropertyManager prop = ModulePropertyManager.getPropertyManager(ModulePropertyManager.CORE_MODULE);
+        POOL_SIZE = getIntProperty(prop, Environment.NAMING_CONTEXT_POOL_SIZE, DEFAULT_POOL_SIZE);
+        SLEEP_PERIOD = getIntProperty(prop, Environment.NAMING_CONTEXT_SLEEP_PERIOD, DEFAULT_SLEEP_PERIOD);
+        RETRY_COUNT = getIntProperty(prop, Environment.NAMING_CONTEXT_RETRY_COUNT, DEFAULT_RETRY_COUNT);
+    }
+    
+    /**
+     * Get a Naming Context from the pool.
+     * @param properties The properties of the JNDI environment.
+     * @return the pooled Naming Context.
+     */
+    public static Context getNamingContext(final Properties properties)
+        throws NamingContextException
+    {
+        return getPool().getContext(properties) ;
+    }
+    
+    /**
+     * Release the Naming Context back into the pool.
+     * @param context The Naming Context to release.
+     */
+    public static void releaseNamingContext(final Context context)
+        throws NamingContextException
+    {
+        getPool().releaseContext(context) ;
+    }
+    
+    /**
+     * Close the Naming Context and remove from the pool.
+     * @param context The Naming Context to close.
+     * @param env The JNDI environment parameters for the Naming Context.
+     */
+    public static Context replaceNamingContext(final Context context, final Properties env)
+        throws NamingContextException
+    {
+        return getPool().replaceContext(context, env) ;
+    }
+    
+    /**
+     * Get the Naming Context pool.
+     * @return The Naming Context pool.
+     * @throws NamingContextException For errors retrieving the Naming Context pool.
+     */
+    private static NamingContextPool getPool()
+        throws NamingContextException
+    {
+        try
+        {
+            return lifecycleNamingContextPoolResource.getLifecycleResource() ;
+        }
+        catch (final LifecycleResourceException lre)
+        {
+            throw new NamingContextException("Unexpected lifecycle resource exception", lre) ;
+        }
+    }
+    
+    /**
+     * Takes properties and serializes this into a long string which is the key
+     * into the contextCache.
+     * 
+     * @param properties -
+     *                property Bag.
+     * @return key into the contextCache.
+     */
+    private static String getKey(Properties properties)
+    {
+        if ((properties == null) || (properties.size() == 0))
+        {
+            return DEFAULT_KEY ;
+        }
+        
+        final TreeMap<String, String> orderedProperties = new TreeMap<String, String>() ;
+        final Iterator<Entry<Object, Object>> entryIter = properties.entrySet().iterator() ;
+        while(entryIter.hasNext())
+        {
+            final Entry<Object, Object> entry = entryIter.next() ;
+            orderedProperties.put(entry.getKey().toString(), entry.getValue().toString()) ;
+        }
+        return orderedProperties.toString() ;
+    }
+    
+    /**
+     * Get the integer value of the specified property.
+     * @param prop The property manager.
+     * @param name The property name.
+     * @param defaultValue The default value.
+     * @return The integer value of the property or the default value.
+     */
+    private static int getIntProperty(final PropertyManager prop, final String name, final int defaultValue)
+    {
+        final String value = prop.getProperty(name) ;
+        if (value != null)
+        {
+            try
+            {
+                return Integer.parseInt(value) ;
+            }
+            catch (final NumberFormatException nfe)
+            {
+                LOGGER.warn("Could not parse value for property: " + name + ", value: " + value) ;
+            }
+        }
+        return defaultValue ;
+    }
+    
+    /**
+     * The factory for creating and destroying lifecycle resources.
+     */
+    private static class NamingContextPoolFactory implements LifecycleResourceFactory<NamingContextPool>
+    {
+        /**
+         * Create a resource object which will be associated with the specified lifecycle identity.
+         * @param lifecycleIdentity The associated lifecycle identity.
+         * @return The lifecycle resource
+         * @throws LifecycleResourceException for errors during construction.
+         */
+        public NamingContextPool createLifecycleResource(final String lifecycleIdentity)
+            throws LifecycleResourceException
+        {
+            return new NamingContextPool() ;
+        }
+        
+        /**
+         * Destroy a resource object which is associated with the specified lifecycle identity.
+         * @param resource The lifecycle resource.
+         * @param lifecycleIdentity The associated lifecycle identity.
+         * @return The lifecycle resource.
+         * @throws LifecycleResourceException for errors during destroy.
+         */
+        public void destroyLifecycleResource(final NamingContextPool resource,
+            final String lifecycleIdentity)
+            throws LifecycleResourceException
+        {
+            resource.closeAllContexts() ;
+        }
+    }
+}


Property changes on: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/helpers/NamingContextPool.java
___________________________________________________________________
Name: svn:keywords
   + Rev Date
Name: svn:eol-style
   + native

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/lifecycle/LifecyclePriorities.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/lifecycle/LifecyclePriorities.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/lifecycle/LifecyclePriorities.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -45,4 +45,9 @@
      * The JMS connection pool priority.
      */
     public static final int JMS_CONNECTION_POOL_PRIORITY = 200000 ;
+    
+    /**
+     * The Naming Context pool priority.
+     */
+    public static final int NAMING_CONTEXT_POOL_PRIORITY = 400000 ;
 }

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/lifecycle/LifecycleResourceManager.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/lifecycle/LifecycleResourceManager.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/lifecycle/LifecycleResourceManager.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -283,7 +283,7 @@
         {
             resourceLock.unlock() ;
         }
-        // Not touching this yet, needs reworking
+        // NamingContext has been replaced by NamingContextPool and is now deprecated
         NamingContext.closeAllContexts() ;
     }
     

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/listeners/gateway/JmsGatewayListener.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/listeners/gateway/JmsGatewayListener.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/listeners/gateway/JmsGatewayListener.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -39,7 +39,6 @@
 import javax.jms.Session;
 import javax.jms.Topic;
 import javax.jms.TopicSession;
-import javax.jms.XASession;
 import javax.naming.Context;
 import javax.naming.NamingException;
 
@@ -57,7 +56,8 @@
 import org.jboss.soa.esb.couriers.CourierUtil;
 import org.jboss.soa.esb.filter.FilterManager;
 import org.jboss.soa.esb.helpers.ConfigTree;
-import org.jboss.soa.esb.helpers.NamingContext;
+import org.jboss.soa.esb.helpers.NamingContextException;
+import org.jboss.soa.esb.helpers.NamingContextPool;
 import org.jboss.soa.esb.listeners.ListenerTagNames;
 import org.jboss.soa.esb.listeners.ListenerUtil;
 import org.jboss.soa.esb.listeners.RegistryUtil;
@@ -119,6 +119,10 @@
             throw new ManagedLifecycleException(
                     "Unexpected configuration exception from prepareMessageReceiver",
                     ce);
+        } catch (final NamingContextException nce) {
+            throw new ManagedLifecycleException(
+                    "Unexpected naming context exception from prepareMessageReceiver",
+                    nce);
         }
 
         if (_serviceName != null) {
@@ -351,7 +355,7 @@
     } // ________________________________
 
     private void prepareMessageReceiver() throws ConfigurationException,
-            JMSException, ConnectionException {
+            JMSException, ConnectionException, NamingContextException {
         jmsSession = null;
         jmsDestination = null;
 
@@ -375,67 +379,65 @@
                 environment.setProperty(name, _config.getAttribute(name));
             }
         }
-        Context oJndiCtx = NamingContext.getServerContext(environment);
-
-        if (null == oJndiCtx)
-            throw new ConfigurationException("Unable fo obtain jndi context <"
-                    + sJndiURL + "," + sJndiContextFactory + ","
-                    + sJndiPkgPrefix + ">");
-
-        String sFactClass = ListenerUtil.getValue(_config,
-                JMSEpr.CONNECTION_FACTORY_TAG, "ConnectionFactory");
-        if (null == _config.getAttribute(JMSEpr.CONNECTION_FACTORY_TAG))
-            _logger.debug("No value specified for "
-                    + JMSEpr.CONNECTION_FACTORY_TAG + " attribute"
-                    + " -  Using default of: '" + sFactClass + "'");
-        _serviceCategory = _config
-                .getAttribute(ListenerTagNames.SERVICE_CATEGORY_NAME_TAG);
-        _serviceName = _config.getAttribute(ListenerTagNames.SERVICE_NAME_TAG);
-
-        String destType = _config.getAttribute(JMSEpr.DESTINATION_TYPE_TAG);
-        boolean persistent = Boolean.valueOf( _config.getAttribute(JMSEpr.PERSISTENT_TAG));
-        boolean transacted = Boolean.valueOf( _config.getAttribute(JMSEpr.TRANSACTED_TAG));
-        
-        String acknowledgeMode = _config.getAttribute(JMSEpr.ACKNOWLEDGE_MODE_TAG);
-        
-        final String username =  _config.getAttribute( JMSEpr.JMS_SECURITY_PRINCIPAL_TAG );
-        final String password =  _config.getAttribute( JMSEpr.JMS_SECURITY_CREDENTIAL_TAG );
-        if ( username != null && password != null )
-        {
-	        environment.put( JMSEpr.JMS_SECURITY_PRINCIPAL_TAG, username );
-	        environment.put( JMSEpr.JMS_SECURITY_CREDENTIAL_TAG, password );
-        }
-        _logger.debug( "JMSGateway isTransacted = " + transacted );
-        
-        _myEpr = (null == _serviceName) ? null : new JMSEpr(JMSEpr.ONE_ONE_PROTOCOL, destType,
-            jmsDestinationName, sFactClass, environment, _messageSelector, persistent, acknowledgeMode,
-            username, password, transacted );
-        jmsConnectionPool = JmsConnectionPoolContainer.getPool(environment, sFactClass, destType,username, password, transacted);
-        	
+        Context oJndiCtx = NamingContextPool.getNamingContext(environment);
         try {
-            jmsSession = _myEpr != null ? jmsConnectionPool.getSession(((JMSEpr)_myEpr).getAcknowledgeMode()):
-            	jmsConnectionPool.getSession(Session.AUTO_ACKNOWLEDGE);
-        		
-        }
-        catch (NamingException ne) {
-            throw new ConfigurationException("Failed to obtain queue session from pool", ne);
-        }
-
-        try {
-            jmsDestination = (Destination) oJndiCtx.lookup(jmsDestinationName);
-        }
-        catch (NamingException nex) {
+            String sFactClass = ListenerUtil.getValue(_config,
+                    JMSEpr.CONNECTION_FACTORY_TAG, "ConnectionFactory");
+            if (null == _config.getAttribute(JMSEpr.CONNECTION_FACTORY_TAG))
+                _logger.debug("No value specified for "
+                        + JMSEpr.CONNECTION_FACTORY_TAG + " attribute"
+                        + " -  Using default of: '" + sFactClass + "'");
+            _serviceCategory = _config
+                    .getAttribute(ListenerTagNames.SERVICE_CATEGORY_NAME_TAG);
+            _serviceName = _config.getAttribute(ListenerTagNames.SERVICE_NAME_TAG);
+    
+            String destType = _config.getAttribute(JMSEpr.DESTINATION_TYPE_TAG);
+            boolean persistent = Boolean.valueOf( _config.getAttribute(JMSEpr.PERSISTENT_TAG));
+            boolean transacted = Boolean.valueOf( _config.getAttribute(JMSEpr.TRANSACTED_TAG));
+            
+            String acknowledgeMode = _config.getAttribute(JMSEpr.ACKNOWLEDGE_MODE_TAG);
+            
+            final String username =  _config.getAttribute( JMSEpr.JMS_SECURITY_PRINCIPAL_TAG );
+            final String password =  _config.getAttribute( JMSEpr.JMS_SECURITY_CREDENTIAL_TAG );
+            if ( username != null && password != null )
+            {
+    	        environment.put( JMSEpr.JMS_SECURITY_PRINCIPAL_TAG, username );
+    	        environment.put( JMSEpr.JMS_SECURITY_CREDENTIAL_TAG, password );
+            }
+            _logger.debug( "JMSGateway isTransacted = " + transacted );
+            
+            _myEpr = (null == _serviceName) ? null : new JMSEpr(JMSEpr.ONE_ONE_PROTOCOL, destType,
+                jmsDestinationName, sFactClass, environment, _messageSelector, persistent, acknowledgeMode,
+                username, password, transacted );
+            jmsConnectionPool = JmsConnectionPoolContainer.getPool(environment, sFactClass, destType,username, password, transacted);
+            	
             try {
-                oJndiCtx = NamingContext.getServerContext(environment);
+                jmsSession = _myEpr != null ? jmsConnectionPool.getSession(((JMSEpr)_myEpr).getAcknowledgeMode()):
+                	jmsConnectionPool.getSession(Session.AUTO_ACKNOWLEDGE);
+            		
+            }
+            catch (NamingException ne) {
+                throw new ConfigurationException("Failed to obtain queue session from pool", ne);
+            }
+    
+            try {
                 jmsDestination = (Destination) oJndiCtx.lookup(jmsDestinationName);
             }
-            catch (NamingException ne) {
-                if(jmsSession instanceof QueueSession) {
-                    jmsDestination = jmsSession.createQueue(jmsDestinationName);
-                } else {
-                    jmsDestination = jmsSession.createTopic(jmsDestinationName);
+            catch (NamingException nex) {
+                try {
+                    oJndiCtx = NamingContextPool.replaceNamingContext(oJndiCtx, environment);
+                    jmsDestination = (Destination) oJndiCtx.lookup(jmsDestinationName);
                 }
+                catch (NamingException ne) {
+                    if(jmsSession instanceof QueueSession) {
+                        jmsDestination = jmsSession.createQueue(jmsDestinationName);
+                    } else {
+                        jmsDestination = jmsSession.createTopic(jmsDestinationName);
+                    }
+                }
             }
+        } finally {
+            NamingContextPool.releaseNamingContext(oJndiCtx) ;
         }
 
         if(jmsSession instanceof QueueSession && jmsDestination instanceof Queue) {

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/notification/NotifyJMS.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/notification/NotifyJMS.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/notification/NotifyJMS.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -157,13 +157,6 @@
 	 */
 	public static final String TIME_TO_LIVE_ATTR = "time-to-live";
 	
-	/**
-	 * This object holds the JNDI naming context that will be used to obtain a
-	 * JMS destination (javax.jms.Destination) to send/publish the notification
-	 * at sendNotification() time
-	 */
-	protected Context[] contexts;
-
 	private Properties m_oProps = new Properties();
 
 	/**
@@ -231,25 +224,6 @@
     } // __________________________________
 
 	/**
-	 * Performs an orderly release of all JMS resources utilized - Well behaved
-	 * developers should always call this method before unreferencing this
-	 * object
-	 */
-	public void release ()
-	{
-        for (int i=0; i<connectionPools.length; i++) {
-        	connectionPools[i].closeSession(sessions[i]);
-            if (contexts[i]!=null) {
-                try {
-                    contexts[i].close();
-                } catch (NamingException ne) {
-                    log.error(ne.getMessage(), ne);
-                }
-            }
-        }
-	}
-
-	/**
 	 * Send a JMS message using p_o to fill in the message content and the list
 	 * of message properties that will be added to the JMS message header fields
 	 * 
@@ -330,8 +304,6 @@
 	 */
 	protected void sendToAll (final Message p_oMsg) throws JMSException
 	{
-		try 
-		{
             final StringBuilder jmsExceptions = new StringBuilder();
 			for (int i1 = 0; i1 < producers.length; i1++)
 			{
@@ -348,11 +320,6 @@
 			}
 			if ( jmsExceptions.length() > 0 )
 				throw new JMSException( jmsExceptions.toString() );
-		}
-		finally
-		{
-			release();
-		}
 	}
 	
 	/**
@@ -371,7 +338,6 @@
 		final int nrQueuesOrTopics = configTrees.length;
 		producers = new MessageProducer[nrQueuesOrTopics];
         connectionPools = new JmsConnectionPool[nrQueuesOrTopics];
-        contexts = new Context[nrQueuesOrTopics];
         sessions = new Session[nrQueuesOrTopics];
         deliveryModes = new int[nrQueuesOrTopics];
         priorities = new int[nrQueuesOrTopics];

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/notification/NotifyQueues.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/notification/NotifyQueues.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/notification/NotifyQueues.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -40,7 +40,8 @@
 import org.jboss.soa.esb.ConfigurationException;
 import org.jboss.soa.esb.addressing.eprs.JMSEpr;
 import org.jboss.soa.esb.helpers.ConfigTree;
-import org.jboss.soa.esb.helpers.NamingContext;
+import org.jboss.soa.esb.helpers.NamingContextException;
+import org.jboss.soa.esb.helpers.NamingContextPool;
 
 /**
  * This class that implements abstract methods defined in it's superclass
@@ -105,31 +106,40 @@
 		
 		QueueSession queueSession = (QueueSession) session;
 		
-        Context context = NamingContext.getServerContext(environment);
-        Queue queue=null;
-        try 
-        {
-            queue = (Queue) context.lookup(destinationName);
-        } 
-        catch (NamingException ne) 
-        {
-        	if ( context != null ) context.close();
-            context = NamingContext.getFreshServerContext(environment);
-            try 
+	try
+	{
+            Context context = NamingContextPool.getNamingContext(environment);
+            try
             {
-                queue = (Queue) context.lookup(destinationName);
-            } 
-            catch (NamingException nex) 
+                Queue queue=null;
+                try 
+                {
+                    queue = (Queue) context.lookup(destinationName);
+                } 
+                catch (NamingException ne) 
+                {
+                    context = NamingContextPool.replaceNamingContext(context, environment);
+                    try 
+                    {
+                        queue = (Queue) context.lookup(destinationName);
+                    } 
+                    catch (NamingException nex) 
+                    {
+                        //ActiveMQ
+                        queueSession.createTopic(destinationName);
+                    }
+                }
+    		return queueSession.createSender(queue);
+            }
+            finally
             {
-                //ActiveMQ
-                queueSession.createTopic(destinationName);
+                NamingContextPool.releaseNamingContext(context) ;
             }
-        }
-        finally
-        {
-        	if ( context != null ) context.close();
-        }
-		return queueSession.createSender(queue);
 	}
+	catch (final NamingContextException nce)
+	{
+	    throw new ConnectionException("Unexpected exception while accessing Naming Context pool", nce) ;
+	}
+	}
 
 }

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/notification/NotifyTopics.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/notification/NotifyTopics.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/src/org/jboss/soa/esb/notification/NotifyTopics.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -39,7 +39,8 @@
 import org.jboss.soa.esb.ConfigurationException;
 import org.jboss.soa.esb.addressing.eprs.JMSEpr;
 import org.jboss.soa.esb.helpers.ConfigTree;
-import org.jboss.soa.esb.helpers.NamingContext;
+import org.jboss.soa.esb.helpers.NamingContextException;
+import org.jboss.soa.esb.helpers.NamingContextPool;
 /**
  * 
  * KS: It is silly we open and close the jms connection with eash request.
@@ -83,31 +84,40 @@
 		
 		TopicSession topicSession = (TopicSession) session;
 		
-        Context context = NamingContext.getServerContext(environment);
-        Topic topic=null;
-        try 
-        {
-            topic = (Topic) context.lookup(destinationName);
-        } 
-        catch (NamingException ne) 
-        {
-        	if ( context != null ) context.close();
-            context = NamingContext.getFreshServerContext(environment);
-            try 
+	try
+	{
+            Context context = NamingContextPool.getNamingContext(environment);
+            try
             {
-                topic = (Topic) context.lookup(destinationName);
-            } 
-            catch (NamingException nex) 
+                Topic topic=null;
+                try 
+                {
+                    topic = (Topic) context.lookup(destinationName);
+                } 
+                catch (NamingException ne) 
+                {
+                    context = NamingContextPool.replaceNamingContext(context, environment);
+                    try 
+                    {
+                        topic = (Topic) context.lookup(destinationName);
+                    } 
+                    catch (NamingException nex) 
+                    {
+                        //ActiveMQ
+                        topicSession.createTopic(destinationName);
+                    }
+                }
+    		return topicSession.createPublisher(topic);
+            }
+            finally
             {
-                //ActiveMQ
-                topicSession.createTopic(destinationName);
+                NamingContextPool.releaseNamingContext(context) ;
             }
-        }
-        finally
-        {
-        	if ( context != null ) context.close();
-        }
-		return topicSession.createPublisher(topic);
 	}
+	catch (final NamingContextException nce)
+	{
+	    throw new ConnectionException("Unexpected exception while accessing naming context pool", nce) ;
+	}
+	}
 	
 } // ____________________________________________________________________________

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/common/tests/utils/DrainQueuesAndTopics.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/common/tests/utils/DrainQueuesAndTopics.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/common/tests/utils/DrainQueuesAndTopics.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -38,7 +38,8 @@
 import javax.naming.Context;
 
 import org.apache.log4j.Logger;
-import org.jboss.soa.esb.helpers.NamingContext;
+import org.jboss.soa.esb.common.Environment;
+import org.jboss.soa.esb.helpers.NamingContextPool;
 
 public class DrainQueuesAndTopics
 {
@@ -88,11 +89,11 @@
   QueueReceiver getQueue(String p_sJndi) throws Exception
   {
       Properties environment = new Properties();
-      environment.setProperty(Context.PROVIDER_URL, NamingContext.JBOSS_PROVIDER_URL);
-      environment.setProperty(Context.INITIAL_CONTEXT_FACTORY, NamingContext.JBOSS_INITIAL_CONTEXT_FACTORY);
-      environment.setProperty(Context.URL_PKG_PREFIXES, NamingContext.JBOSS_URL_PKG_PREFIX);
-      Context oCtx = NamingContext.getServerContext(environment);
-      
+      environment.setProperty(Context.PROVIDER_URL, Environment.JBOSS_PROVIDER_URL);
+      environment.setProperty(Context.INITIAL_CONTEXT_FACTORY, Environment.JBOSS_INITIAL_CONTEXT_FACTORY);
+      environment.setProperty(Context.URL_PKG_PREFIXES, Environment.JBOSS_URL_PKG_PREFIX);
+      final Context oCtx = NamingContextPool.getNamingContext(environment);
+      try {
 	QueueConnection oQconn = null;
 	QueueSession 	oQsess = null;
 	QueueConnectionFactory qcf = (QueueConnectionFactory) oCtx
@@ -103,19 +104,22 @@
 			,QueueSession.AUTO_ACKNOWLEDGE);
     Queue oQueue
     	= (Queue) oCtx.lookup(p_sJndi);
-    oCtx.close();
     QueueReceiver oRcv = oQsess.createReceiver(oQueue);
     oQconn.start();
     return oRcv;
+      } finally {
+          NamingContextPool.releaseNamingContext(oCtx) ;
+      }
   } //__________________________________
 
   TopicSubscriber getTopic(String p_sJndi) throws Exception
   {
       Properties environment = new Properties();
-      environment.setProperty(Context.PROVIDER_URL, NamingContext.JBOSS_PROVIDER_URL);
-      environment.setProperty(Context.INITIAL_CONTEXT_FACTORY, NamingContext.JBOSS_INITIAL_CONTEXT_FACTORY);
-      environment.setProperty(Context.URL_PKG_PREFIXES, NamingContext.JBOSS_URL_PKG_PREFIX);
-      Context oCtx = NamingContext.getServerContext(environment);
+      environment.setProperty(Context.PROVIDER_URL, Environment.JBOSS_PROVIDER_URL);
+      environment.setProperty(Context.INITIAL_CONTEXT_FACTORY, Environment.JBOSS_INITIAL_CONTEXT_FACTORY);
+      environment.setProperty(Context.URL_PKG_PREFIXES, Environment.JBOSS_URL_PKG_PREFIX);
+      final Context oCtx = NamingContextPool.getNamingContext(environment);
+      try {
 	TopicConnection oTconn = null;
 	TopicSession 	oTsess = null;
 	TopicConnectionFactory qcf = (TopicConnectionFactory) oCtx
@@ -125,9 +129,11 @@
 	oTsess = oTconn.createTopicSession(false
 			,QueueSession.AUTO_ACKNOWLEDGE);
     Topic oT = (Topic) oCtx.lookup(p_sJndi);
-    oCtx.close();
     TopicSubscriber oRcv = oTsess.createSubscriber(oT);
     oTconn.start();
     return oRcv;
+      } finally {
+          NamingContextPool.releaseNamingContext(oCtx) ;
+      }
   } //__________________________________ 
 } //____________________________________________________________________________

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/helpers/AppServerContextUnitTest.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/helpers/AppServerContextUnitTest.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/helpers/AppServerContextUnitTest.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -30,6 +30,7 @@
 import junit.framework.TestCase;
 
 import org.apache.log4j.Logger;
+import org.jboss.soa.esb.common.Environment;
 
 /**
  * AppServerContex unit tests.
@@ -40,19 +41,21 @@
 	private Logger log = Logger.getLogger( AppServerContextUnitTest.class );
 	final String initialContextFactory = MockInitialContextFactory.class.getName() ;
         
-	public void test_AppServerContext() throws NamingException {
+	public void test_AppServerContext() throws NamingException, NamingContextException {
         Properties environment = new Properties();
         environment.setProperty(Context.PROVIDER_URL, "http://localhost:1234");
         environment.setProperty(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
-        environment.setProperty(Context.URL_PKG_PREFIXES, NamingContext.JBOSS_URL_PKG_PREFIX);
-        Context ctx = NamingContext.getServerContext(environment);
+        environment.setProperty(Context.URL_PKG_PREFIXES, Environment.JBOSS_URL_PKG_PREFIX);
+        Context ctx = NamingContextPool.getNamingContext(environment);
+        try {
 		
 		
 		Hashtable props = ctx.getEnvironment();
 		log.debug(props);
 		assertEquals(initialContextFactory, props.get(Context.INITIAL_CONTEXT_FACTORY));
 		assertEquals("http://localhost:1234", props.get(Context.PROVIDER_URL));
-		
-        ctx.close();
+        } finally {
+            NamingContextPool.releaseNamingContext(ctx) ;
+        }
 	}
 }

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/notification/NotifyQueuesUnitTest.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/notification/NotifyQueuesUnitTest.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/notification/NotifyQueuesUnitTest.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -25,46 +25,29 @@
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
-import java.io.Serializable;
 import java.lang.reflect.InvocationHandler;
 import java.lang.reflect.Method;
 import java.lang.reflect.Proxy;
 import java.nio.ByteBuffer;
 
-import javax.jms.BytesMessage;
 import javax.jms.DeliveryMode;
-import javax.jms.Destination;
 import javax.jms.ExceptionListener;
 import javax.jms.JMSException;
-import javax.jms.MapMessage;
 import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
 import javax.jms.ObjectMessage;
-import javax.jms.Queue;
-import javax.jms.QueueBrowser;
 import javax.jms.QueueConnection;
-import javax.jms.QueueSender;
-import javax.jms.Session;
-import javax.jms.StreamMessage;
-import javax.jms.TemporaryQueue;
-import javax.jms.TemporaryTopic;
 import javax.jms.TextMessage;
-import javax.jms.Topic;
-import javax.jms.TopicSubscriber;
 import javax.naming.Context;
-import javax.naming.InitialContext;
 import javax.naming.NamingException;
 
 import junit.framework.JUnit4TestAdapter;
 
 import org.apache.log4j.Logger;
 import org.jboss.internal.soa.esb.rosetta.pooling.ConnectionException;
-import org.jboss.internal.soa.esb.rosetta.pooling.JmsConnectionPool;
 import org.jboss.soa.esb.ConfigurationException;
 import org.jboss.soa.esb.helpers.ConfigTree;
-import org.jboss.soa.esb.message.body.content.BytesBody;
+import org.jboss.soa.esb.helpers.NamingContextException;
+import org.jboss.soa.esb.helpers.NamingContextPool;
 import org.jboss.soa.esb.message.format.MessageFactory;
 import org.jboss.soa.esb.message.format.MessageType;
 import org.junit.After;
@@ -72,7 +55,6 @@
 import org.junit.Test;
 import org.mockejb.jms.MockQueue;
 import org.mockejb.jms.MockTopic;
-import org.mockejb.jms.ObjectMessageImpl;
 import org.mockejb.jms.QueueConnectionFactoryImpl;
 import org.mockejb.jndi.MockContextFactory;
 
@@ -94,10 +76,16 @@
 	@Before
 	public void setUp() {
         try {
-    		MockContextFactory.setAsInitial();		
-    		Context ctx = new InitialContext();
-    		ctx.rebind(NotifyQueues.CONNECTION_FACTORY, new MockQueueConnectionFactory());
-    		ctx.close();
+    		MockContextFactory.setAsInitial();
+                final Context ctx = NamingContextPool.getNamingContext(null);
+                try
+                {
+                    ctx.rebind(NotifyQueues.CONNECTION_FACTORY, new MockQueueConnectionFactory());
+                }
+                finally
+                {
+                    NamingContextPool.releaseNamingContext(ctx) ;
+                }
     		rootEl = new ConfigTree("rootEl");
     
     		addMessagePropertyConfigs(rootEl);
@@ -115,9 +103,6 @@
 	
 	@After
 	public void tearDown() throws Exception {
-        if(notifyQueues != null) {
-            notifyQueues.release();
-        }
         MockContextFactory.revertSetAsInitial();
 	}
 	
@@ -172,12 +157,6 @@
 		assertEquals( 600l, notifyQueues.timeToLives[0] );
 	}
 	
-	@Test
-	public void release() 
-	{
-		notifyQueues.release();
-	}
-	
 	private void checkQueueTextMessage(MockQueue mockQueue, int messageIdx, String expectedText) throws JMSException {
 		assertTrue(mockQueue.getMessages().size() > messageIdx);		
 		Message message = mockQueue.getMessageAt(0);
@@ -220,22 +199,34 @@
 		queueEl.setAttribute(NotifyJMS.ATT_DEST_NAME, queueName);
 	}
 
-	private MockQueue createAndBindQueue(String queueName) throws NamingException {
+	private MockQueue createAndBindQueue(String queueName) throws NamingException, NamingContextException {
 		MockQueue mockQueue = new MockQueue(queueName);
 				
-		Context ctx = new InitialContext();
-		ctx.rebind(queueName, mockQueue);
-		ctx.close();
+                final Context ctx = NamingContextPool.getNamingContext(null);
+                try
+                {
+                    ctx.rebind(queueName, mockQueue);
+                }
+                finally
+                {
+                    NamingContextPool.releaseNamingContext(ctx) ;
+                }
 		return mockQueue;
 	}
 
 	@SuppressWarnings("unused")
-	private MockTopic createAndBindTopic(String topicName) throws NamingException {
+	private MockTopic createAndBindTopic(String topicName) throws NamingException, NamingContextException {
 		MockTopic mockTopic = new MockTopic(topicName);
 		
-		Context ctx = new InitialContext();
-		ctx.rebind(topicName, mockTopic);
-		ctx.close();
+		final Context ctx = NamingContextPool.getNamingContext(null);
+		try
+		{
+		    ctx.rebind(topicName, mockTopic);
+		}
+		finally
+		{
+		    NamingContextPool.releaseNamingContext(ctx) ;
+		}
 		return mockTopic;
 	}
         

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/notification/NotifyTopicsUnitTest.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/notification/NotifyTopicsUnitTest.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/notification/NotifyTopicsUnitTest.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -34,7 +34,6 @@
 import javax.jms.TextMessage;
 import javax.jms.TopicConnection;
 import javax.naming.Context;
-import javax.naming.InitialContext;
 import javax.naming.NamingException;
 
 import junit.framework.TestCase;
@@ -42,7 +41,8 @@
 import org.jboss.internal.soa.esb.rosetta.pooling.ConnectionException;
 import org.jboss.soa.esb.ConfigurationException;
 import org.jboss.soa.esb.helpers.ConfigTree;
-import org.jboss.soa.esb.message.body.content.BytesBody;
+import org.jboss.soa.esb.helpers.NamingContextException;
+import org.jboss.soa.esb.helpers.NamingContextPool;
 import org.jboss.soa.esb.message.format.MessageFactory;
 import org.jboss.soa.esb.message.format.MessageType;
 import org.mockejb.jms.MockTopic;
@@ -60,10 +60,16 @@
 	private NotifyTopics notifyTopics;
 	
 	protected void setUp() throws Exception {
-		MockContextFactory.setAsInitial();		
-		Context ctx = new InitialContext();
-		ctx.rebind(NotifyTopics.CONNECTION_FACTORY, new MockTopicConnectionFactory());
-		ctx.close();
+		MockContextFactory.setAsInitial();
+                final Context ctx = NamingContextPool.getNamingContext(null);
+                try
+                {
+                    ctx.rebind(NotifyTopics.CONNECTION_FACTORY, new MockTopicConnectionFactory());
+                }
+                finally
+                {
+                    NamingContextPool.releaseNamingContext(ctx) ;
+                }
 		ConfigTree rootEl = new ConfigTree("rootEl");
 
 		addMessagePropertyConfigs(rootEl);
@@ -76,7 +82,6 @@
 	}
 
 	protected void tearDown() throws Exception {
-		notifyTopics.release();
 		MockContextFactory.revertSetAsInitial();		
 	}
 
@@ -162,12 +167,18 @@
 		topicEl.setAttribute(NotifyJMS.ATT_DEST_NAME, topicName);
 	}
 
-	private MockTopic createAndBindTopic(String topicName) throws NamingException {
+	private MockTopic createAndBindTopic(String topicName) throws NamingException, NamingContextException {
 		MockTopic mockTopic = new MockTopic(topicName);
 		
-		Context ctx = new InitialContext();
-		ctx.rebind(topicName, mockTopic);
-		ctx.close();
+		final Context ctx = NamingContextPool.getNamingContext(null) ;
+		try
+		{
+		    ctx.rebind(topicName, mockTopic);
+		}
+		finally
+		{
+		    NamingContextPool.releaseNamingContext(ctx) ;
+		}
 		return mockTopic;
 	}
         

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/rosetta/pooling/JmsConnectionPoolingIntegrationTest.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/rosetta/pooling/JmsConnectionPoolingIntegrationTest.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/rosetta/tests/src/org/jboss/soa/esb/rosetta/pooling/JmsConnectionPoolingIntegrationTest.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -33,10 +33,8 @@
 import org.jboss.internal.soa.esb.rosetta.pooling.JmsConnectionPool;
 import org.jboss.internal.soa.esb.rosetta.pooling.JmsConnectionPoolContainer;
 import org.jboss.soa.esb.addressing.eprs.JMSEpr;
-import org.jboss.soa.esb.helpers.NamingContext;
-import org.jboss.soa.esb.lifecycle.LifecycleResourceManager;
+import org.jboss.soa.esb.common.Environment;
 import org.junit.Before;
-import org.junit.Ignore;
 import org.junit.Test;
 
 /**
@@ -194,9 +192,9 @@
     public Properties getEnvironment()
     {
     	  Properties environment = new Properties();
-          environment.setProperty(Context.PROVIDER_URL, NamingContext.JBOSS_PROVIDER_URL);
-          environment.setProperty(Context.INITIAL_CONTEXT_FACTORY, NamingContext.JBOSS_INITIAL_CONTEXT_FACTORY);
-          environment.setProperty(Context.URL_PKG_PREFIXES, NamingContext.JBOSS_URL_PKG_PREFIX);
+          environment.setProperty(Context.PROVIDER_URL, Environment.JBOSS_PROVIDER_URL);
+          environment.setProperty(Context.INITIAL_CONTEXT_FACTORY, Environment.JBOSS_INITIAL_CONTEXT_FACTORY);
+          environment.setProperty(Context.URL_PKG_PREFIXES, Environment.JBOSS_URL_PKG_PREFIX);
           return environment;
     }
     

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/services/jbossesb/src/main/java/org/jboss/internal/soa/esb/persistence/format/jcr/JCRConnectionManager.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/services/jbossesb/src/main/java/org/jboss/internal/soa/esb/persistence/format/jcr/JCRConnectionManager.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/services/jbossesb/src/main/java/org/jboss/internal/soa/esb/persistence/format/jcr/JCRConnectionManager.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -39,7 +39,8 @@
 import org.apache.jackrabbit.core.TransientRepository;
 import org.apache.jackrabbit.core.config.RepositoryConfig;
 import org.jboss.soa.esb.common.Configuration;
-import org.jboss.soa.esb.helpers.NamingContext;
+import org.jboss.soa.esb.helpers.NamingContextException;
+import org.jboss.soa.esb.helpers.NamingContextPool;
 import org.jboss.system.server.ServerConfig;
 import org.jboss.system.server.ServerConfigLocator;
 
@@ -109,12 +110,18 @@
 						Configuration.getJndiServerContextFactory());
 				environment.setProperty(Context.URL_PKG_PREFIXES,
 						Configuration.getJndiServerPkgPrefix());
-				Context context = NamingContext.getServerContext(environment);
 				try {
-					repository = (Repository) context.lookup(Configuration.getJcrStoreJNDIPath());
-				} catch (NamingException e) {
-					throw new RepositoryException(e);
-				}
+        				Context context = NamingContextPool.getNamingContext(environment);
+        				try {
+        					repository = (Repository) context.lookup(Configuration.getJcrStoreJNDIPath());
+        				} catch (NamingException e) {
+        					throw new RepositoryException(e);
+        				} finally {
+        				    NamingContextPool.releaseNamingContext(context) ;
+        				}
+                                } catch (NamingContextException nce) {
+                                    throw new RepositoryException(nce);
+                                }
 			}
 			// If no JNDI path is specified, init the repository with default
 			// settings based on the respository.xml in the conf directory.

Modified: labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/services/smooks/src/main/java/org/jboss/soa/esb/actions/converters/SmooksInstanceManager.java
===================================================================
--- labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/services/smooks/src/main/java/org/jboss/soa/esb/actions/converters/SmooksInstanceManager.java	2008-01-17 06:19:55 UTC (rev 17913)
+++ labs/jbossesb/branches/JBESB_4_2_1_GA_CP/product/services/smooks/src/main/java/org/jboss/soa/esb/actions/converters/SmooksInstanceManager.java	2008-01-17 09:43:33 UTC (rev 17914)
@@ -21,12 +21,10 @@
 
 import org.jboss.soa.esb.ConfigurationException;
 import org.jboss.soa.esb.util.ClassUtil;
-import org.jboss.soa.esb.helpers.NamingContext;
 import org.jboss.internal.soa.esb.assertion.AssertArgument;
 import org.apache.log4j.Logger;
 import org.milyn.Smooks;
 import org.milyn.SmooksException;
-import org.milyn.resource.URIResourceLocator;
 import org.xml.sax.SAXException;
 
 import javax.jms.*;




More information about the jboss-svn-commits mailing list