You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@uima.apache.org by ea...@apache.org on 2008/07/11 20:24:44 UTC

svn commit: r676042 - in /incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima: aae/jmx/monitor/ adapter/jms/activemq/ adapter/jms/service/

Author: eae
Date: Fri Jul 11 11:24:42 2008
New Revision: 676042

URL: http://svn.apache.org/viewvc?rev=676042&view=rev
Log:
UIMA-1104 Commit JC core-06 & activemq-07 patches; add single line monitor for import to excel

Modified:
    incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/aae/jmx/monitor/JmxMonitor.java
    incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/activemq/BrokerDeployer.java
    incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/activemq/SpringContainerDeployer.java
    incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/service/UIMA_Service.java

Modified: incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/aae/jmx/monitor/JmxMonitor.java
URL: http://svn.apache.org/viewvc/incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/aae/jmx/monitor/JmxMonitor.java?rev=676042&r1=676041&r2=676042&view=diff
==============================================================================
--- incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/aae/jmx/monitor/JmxMonitor.java (original)
+++ incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/aae/jmx/monitor/JmxMonitor.java Fri Jul 11 11:24:42 2008
@@ -37,9 +37,15 @@
 import org.apache.uima.aae.jmx.ServiceInfoMBean;
 import org.apache.uima.aae.jmx.ServicePerformanceMBean;
 
+/**
+ *	Collects metrics from UIMA-AS Service MBeans at defined intervals and
+ *	passes the metrics for formatting to the registered {@link JmxMonitorListener} 
+ *
+ */
 public class JmxMonitor implements Runnable {
 	private static final Class CLASS_NAME = JmxMonitor.class;
-
+	public static final String CheckpointFrequency = "jmx.monitor.frequency";
+	public static final String FormatterListener = "jmx.monitor.formatter";
 	private boolean running = false;
 	private MBeanServerConnection mbsc;
 	private ObjectName uimaServicePattern;
@@ -52,6 +58,14 @@
 	private int maxNameLength=0;
 	private boolean verbose = false;
 	
+	/**
+	 * Creates a connection to an MBean Server identified by <code>remoteServerURI</code>
+	 * 
+	 * @param remoteServerURI - URI to MBeanServer
+	 * @return - connection to MBeanServer
+	 * 
+	 * @throws Exception
+	 */
 	private MBeanServerConnection getServerConnection( String remoteServerURI) throws Exception
 	{
 		JMXServiceURL url = new JMXServiceURL(remoteServerURI);
@@ -60,6 +74,11 @@
 		return server;
 	}
 	
+	/**
+	 * Registers custom {@link JmxMonitorListener}
+	 * 
+	 * @param listener - listener to receive metrics for formatting
+	 */
 	public void addJmxMonitorListener( JmxMonitorListener listener)
 	{
 		listeners.add( listener );
@@ -68,7 +87,12 @@
 	{
 		echo("\nRemote JVM Info: \n\tJVM::"+runtime.getVmName()+"\n\tJVM Vendor::"+runtime.getVmVendor()+"\n\tJVM Version::"+runtime.getVmVersion()+"\n\n");
 	}
-	
+	/**
+	 * Passes metrics to all registered {@link JmxMonitorListener} objects
+	 * 
+	 * @param uptime - time when the metrics were collected
+	 * @param metrics - current metrics 
+	 */
 	public void notifyListeners( long uptime, ServiceMetrics[] metrics )
 	{
 		for( JmxMonitorListener listener: listeners)
@@ -108,12 +132,13 @@
 		mbsc = getServerConnection(remoteServerURI);
 		
 		ObjectName objName = new  ObjectName(ManagementFactory.RUNTIME_MXBEAN_NAME);
+		
+		//	Construct query string to fetch UIMA-AS MBean names from the JMX Server registry
 		uimaServicePattern = new ObjectName("org.apache.uima:type=ee.jms.services,*");
+		//	Construct query string to fetch Queue MBean names from the JMX Server registry
 		uimaServiceQueuePattern = new ObjectName("org.apache.activemq:BrokerName=localhost,Type=Queue,*");
-		//	Fetch UIMA AS MBeans from the JMX Server
+		//	Fetch UIMA AS MBean names from the JMX Server that match the name pattern
 		Set<ObjectName> names = new HashSet<ObjectName>(mbsc.queryNames(uimaServicePattern, null));
-		//	Fetch All queue MBeans from the JMX Server
-		//		names = new TreeSet<ObjectName>(mbsc.queryNames(uimaServicePattern, null));
 		String key = "";
 		if ( verbose )
 			System.out.println("\nFound UIMA AS Services Managed by JMX Server:"+remoteServerURI);
@@ -122,7 +147,7 @@
 			
 			//	Set up a key for matching Service Performance MBean names
 			String perfKey = "_Service Performance";
-			//	Check if the current name is for the Service Performance MBean
+			//	Check if the current name is the Service Performance MBean
 			if ( name.toString().endsWith(perfKey) )
 			{
 				if ( servicePerformanceNames == null )
@@ -143,18 +168,19 @@
 					maxNameLength = nameLen;
 				}
 				
-				//	Create Service Info proxy
+				//	Create a proxy object to the Service Info MBean
 				ServiceInfoMBean infoMBeanProxy = getServiceInfoMBean(names, key);
 				key = key.substring(key.indexOf(",name=")+",name=".length());
 				
-				
 				long depth = 0; 
 				//	Create a Map entry containing MBeans
 				StatEntry entry = new StatEntry(perfMBeanProxy, infoMBeanProxy);
+				
 				String location = "Collocated";
-				//	If a service is colocated in the same JVM fetch the service queue proxy 
+				//	If a service is co-located in the same JVM fetch the service queue proxy 
 				if ( infoMBeanProxy.getBrokerURL().startsWith("Embedded Broker"))
 				{
+					//	Create a proxy to the service queue MBean
 					QueueViewMBean queueProxy = getQueueMBean(mbsc, infoMBeanProxy.getInputQueueName());
 					if (queueProxy != null )
 					{
@@ -165,7 +191,8 @@
 				else
 				{
 					//	The MBean is for a remote service. Connect to this service Broker and create a proxy
-					//	to an input queue for the service.
+					//	to an input queue for the service. Assumption: the broker registers JMX server on 
+					//	port 1099.
 					location = "Remote";	
 					int spos = infoMBeanProxy.getBrokerURL().indexOf("//");
 					int endpos = infoMBeanProxy.getBrokerURL().lastIndexOf(":");
@@ -189,7 +216,6 @@
 				if ( verbose )
 					System.out.println("\nUIMA AS Service:"+key+"[>>> "+location+" <<<]\n\tService Broker:"+infoMBeanProxy.getBrokerURL()+"\n\tQueue Name:"+infoMBeanProxy.getInputQueueName());
 
-				//System.out.println("Info Bean:"+key+" Broker URL:"+infoMBeanProxy.getBrokerURL()+" Service Queue Name:"+infoMBeanProxy.getInputQueueName()+" Input Queue Depth:"+depth);
 				stats.put(name, entry);
 
 				/** jdk1.6 code
@@ -199,7 +225,13 @@
 			}
 		}
 	}
-	
+	/**
+	 * Returns a proxy object to an UIMA-AS Service Info MBean identified by a <code>key</code>
+	 * 
+	 * @param names - list of MBean names 
+	 * @param key - target name to find in the list of MBeans
+	 * @return - proxy to MBean identified by <code>key</code>
+	 */
 	private ServiceInfoMBean getServiceInfoMBean(Set<ObjectName> names, String key)
 	{
 		String target = key+"_Service Info";
@@ -227,18 +259,21 @@
 		return null;
 	}
 	
-	
+	/**
+	 * Retrieves metrics from UIMA-AS MBeans at defined interval. 
+	 * 
+	 */
 	public void run()
 	{
 		running = true;
 		boolean initial = true;
 		while( running )
 		{
-			
 			long uptime = System.nanoTime() - startTime;
 			
 			ServiceMetrics[] metrics = new ServiceMetrics[servicePerformanceNames.size()];
 			int index = 0;
+			//	iterate over all Performance MBeans to retrieve current metrics
 			for (ObjectName name : servicePerformanceNames) {
 				try
 				{
@@ -269,9 +304,8 @@
 					double deltaTimeInCMGetNext = 0;
 					if ( timeInCMGetNext > 0 )
 					{
-						deltaTimeInCMGetNext = timeInCMGetNext - entry.getLastWaitTimeOnCMGetNext();
+						deltaTimeInCMGetNext = timeInCMGetNext - entry.getWaitTimeOnCMGetNext();
 					}
-					
 					boolean isRemote = entry.getServiceInfoMBeanProxy().getBrokerURL().startsWith("tcp:");
 					boolean topLevel = entry.getServiceInfoMBeanProxy().isTopLevel();
 					
@@ -305,7 +339,8 @@
 					//	Save current metrics for the next delta
 					entry.setIdleTime(idleTime);
 					entry.incrementCASCount(processCount);
-					entry.setLastWaitTimeOnCMGetNext(timeInCMGetNext);
+					//entry.setWaitTimeOnCMGetNext(timeInCMGetNext);
+					entry.incrementWaitTimeOnCMGetNext(timeInCMGetNext);
 				}
 				catch( Exception e){e.printStackTrace();}
 			} // for
@@ -325,6 +360,18 @@
 			//	Notify listeners with current metrics collected from MBeans
 			notifyListeners(uptime, metrics);
 		}
+		
+		running = false;
+	}
+	
+	public boolean isRunning()
+	{
+		return running;
+	}
+	
+	public void doStop()
+	{
+		running = false;
 	}
 	/*
 	 * For simplicity, we declare "throws Exception". Real programs will usually
@@ -383,7 +430,7 @@
 		String name="";
 		
 		double lastIdleTime = 0;
-		double lastWaitTimeOnCMGetNext = 0;
+		double waitTimeOnCMGetNext = 0;
 		long casProcessedCount = 0;
 		double cpWaitTime;
 		double scpWaitTime;
@@ -434,14 +481,13 @@
 			return name;
 		}
 
-		public void setLastWaitTimeOnCMGetNext( double aLastWaitTimeOnCMGetNext)
+		public void incrementWaitTimeOnCMGetNext( double aWaitTimeOnCMGetNext )
 		{
-			lastWaitTimeOnCMGetNext = aLastWaitTimeOnCMGetNext;
+			waitTimeOnCMGetNext =+ aWaitTimeOnCMGetNext;
 		}
-		
-		public double getLastWaitTimeOnCMGetNext()
+		public double getWaitTimeOnCMGetNext()
 		{
-			return lastWaitTimeOnCMGetNext;
+			return waitTimeOnCMGetNext;
 		}
 		public double getTotalCPWaitTime()
 		{

Modified: incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/activemq/BrokerDeployer.java
URL: http://svn.apache.org/viewvc/incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/activemq/BrokerDeployer.java?rev=676042&r1=676041&r2=676042&view=diff
==============================================================================
--- incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/activemq/BrokerDeployer.java (original)
+++ incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/activemq/BrokerDeployer.java Fri Jul 11 11:24:42 2008
@@ -105,10 +105,10 @@
 			String connectorList = "";
 			service.setPersistent(false);
 			int startPort = BASE_JMX_PORT;
-			
 			if ( System.getProperties().containsKey("com.sun.management.jmxremote.port") )
 			{
 				startPort = Integer.parseInt(System.getProperty("com.sun.management.jmxremote.port"));
+				
 			}
 			while( startPort < MAX_PORT_THRESHOLD && !openPort(startPort))
 			{
@@ -118,6 +118,9 @@
 			{
 				service.setUseJmx(true);
 				service.getManagementContext().setConnectorPort(startPort);
+				
+				System.setProperty("com.sun.management.jmxremote.port", String.valueOf(startPort)); 
+
 				System.out.println("JMX Console connect URI:  service:jmx:rmi:///jndi/rmi://localhost:"+startPort+"/jmxrmi");
 				UIMAFramework.getLogger(CLASS_NAME).logrb(Level.CONFIG, CLASS_NAME.getName(),
 	                    "startInternalBroker", JmsConstants.JMS_LOG_RESOURCE_BUNDLE, "UIMAJMS_jmx_uri__CONFIG",

Modified: incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/activemq/SpringContainerDeployer.java
URL: http://svn.apache.org/viewvc/incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/activemq/SpringContainerDeployer.java?rev=676042&r1=676041&r2=676042&view=diff
==============================================================================
--- incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/activemq/SpringContainerDeployer.java (original)
+++ incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/activemq/SpringContainerDeployer.java Fri Jul 11 11:24:42 2008
@@ -24,8 +24,6 @@
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 
-import javax.jms.ConnectionFactory;
-
 import org.apache.activemq.ActiveMQConnectionFactory;
 import org.apache.activemq.command.ActiveMQQueue;
 import org.apache.uima.UIMAFramework;
@@ -51,7 +49,7 @@
 	private boolean serviceInitializationException;
 	private Object serviceMonitor = new Object();
 	private ConcurrentHashMap springContainerRegistry=null;
-	
+	private FileSystemXmlApplicationContext context = null;
 	public SpringContainerDeployer(){
 	}
 
@@ -285,8 +283,8 @@
 		    if (!springContextFile.startsWith("file:")) {
 		      springContextFile = "file:" + springContextFile;
 		    }
-			ApplicationContext ctx = new FileSystemXmlApplicationContext(springContextFile);
-			return initializeContainer(ctx);
+			context = new FileSystemXmlApplicationContext(springContextFile);
+			return initializeContainer(context);
 		} catch (ResourceInitializationException e) {
 			//e.printStackTrace();
 			throw e;
@@ -314,8 +312,8 @@
 			// synchronous ( one bean at a time), some beans run in a separate
 			// threads. The completion of container deployment doesnt
 			// necessarily mean that all beans have initialized completely.
-			ApplicationContext ctx = new FileSystemXmlApplicationContext(springContextFiles);
-			return initializeContainer(ctx);
+			context = new FileSystemXmlApplicationContext(springContextFiles);
+			return initializeContainer(context);
 		} catch (ResourceInitializationException e) {
 			e.printStackTrace();
 			throw e;
@@ -372,4 +370,18 @@
 	public void notifyOnTermination(String message) {
 	}
 
+	public FileSystemXmlApplicationContext getSpringContext()
+	{
+		return context;
+	}
+	
+	public boolean isInitialized()
+	{
+		return serviceInitializationCompleted;
+	}
+	
+	public boolean initializationFailed()
+	{
+		return serviceInitializationException;
+	}
 }

Modified: incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/service/UIMA_Service.java
URL: http://svn.apache.org/viewvc/incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/service/UIMA_Service.java?rev=676042&r1=676041&r2=676042&view=diff
==============================================================================
--- incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/service/UIMA_Service.java (original)
+++ incubator/uima/sandbox/branches/uima-as-post1st/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/service/UIMA_Service.java Fri Jul 11 11:24:42 2008
@@ -1,3 +1,4 @@
+
 /*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
@@ -22,180 +23,244 @@
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
-import java.net.BindException;
-import java.net.ServerSocket;
-
-import org.apache.activemq.broker.BrokerService;
-import org.apache.activemq.broker.TransportConnector;
+import java.io.InvalidClassException;
 import org.apache.uima.UIMAFramework;
-import org.apache.uima.aae.controller.AnalysisEngineController;
-import org.apache.uima.aae.controller.ControllerCallbackListener;
+import org.apache.uima.aae.jmx.monitor.BasicUimaJmxMonitorListener;
+import org.apache.uima.aae.jmx.monitor.JmxMonitor;
+import org.apache.uima.aae.jmx.monitor.JmxMonitorListener;
 import org.apache.uima.adapter.jms.JmsConstants;
 import org.apache.uima.adapter.jms.activemq.SpringContainerDeployer;
 import org.apache.uima.resource.ResourceInitializationException;
 import org.apache.uima.util.Level;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.support.AbstractApplicationContext;
+import org.springframework.context.ApplicationEvent;
+import org.springframework.context.ApplicationListener;
+import org.springframework.context.event.ContextClosedEvent;
 import org.springframework.context.support.FileSystemXmlApplicationContext;
 
-public class UIMA_Service implements ControllerCallbackListener
+public class UIMA_Service implements  ApplicationListener
 {
 	private static final Class CLASS_NAME = UIMA_Service.class;
 
-	private BrokerService service;
-	private TransportConnector connector;
-	private TransportConnector stompConnector;
-	private TransportConnector httpConnector;
-	private Object semaphore = new Object();
 	protected boolean serviceInitializationCompleted;
 	protected boolean serviceInitializationException;
 	protected Object serviceMonitor = new Object();
-
-	public void startInternalBroker() throws Exception
+	private JmxMonitor monitor = null;
+	private Thread monitorThread = null;
+	
+	/**
+	 * Parse command args, run dd2spring on the deployment descriptors to generate Spring context files.
+	 * 
+	 * @param args - command line arguments
+	 * @return - an array of Spring context files generated from provided deployment descriptors
+	 * @throws Exception
+	 */
+	public String[] initialize(String[] args) throws Exception
 	{
+		UIMAFramework.getLogger(CLASS_NAME).log(Level.INFO, "UIMA-AS version " + UIMAFramework.getVersionString());
+
+		String[] springConfigFileArray =
+		{};
+		String[] deployedDescriptors =
+		{};
+		String[] deploymentDescriptors =
+		{};
+		int nbrOfArgs = args.length;
 
-		service = new BrokerService();
-		String[] connectors = service.getNetworkConnectorURIs();
-		String brokerURI;
-		if (connectors != null)
+		deploymentDescriptors = getMultipleArg("-d", args);
+		if (deploymentDescriptors.length == 0)
 		{
-			for (int i = 0; i < connectors.length; i++)
-			{
-				System.out.println("ActiveMQ Broker Started With Connector:" + connectors[i]);
-			}
-			brokerURI = service.getMasterConnectorURI();
+		  // allow multiple args for one key
+			deploymentDescriptors = getMultipleArg2("-dd", args);
+		}
+		String saxonURL = getArg("-saxonURL", args);
+		String xslTransform = getArg("-xslt", args);
+		String uimaAsDebug = getArg("-uimaEeDebug", args);
+		
+		if (nbrOfArgs < 1 || (args[0].startsWith("-") && (deploymentDescriptors.length == 0 || saxonURL.equals("") || xslTransform.equals(""))))
+		{
+			printUsageMessage();
+			return null;
+		}
+
+		if (deploymentDescriptors.length == 0)
+		{
+			// array of context files passed in
+			springConfigFileArray = args;
+			deployedDescriptors = args;
 		}
 		else
 		{
-			String connectorList = "";
-			service.setPersistent(false);
-			service.setUseJmx(true);
-			brokerURI = generateInternalURI("tcp", 18810, true, false);
-			connector = service.addConnector(brokerURI);
-			System.out.println("Adding TCP Connector:" + connector.getConnectUri());
-			UIMAFramework.getLogger(CLASS_NAME).logrb(Level.CONFIG, CLASS_NAME.getName(), "JmsMessageContext", JmsConstants.JMS_LOG_RESOURCE_BUNDLE, "UIMAJMS_adding_connector__CONFIG", new Object[]
-			{ "Adding TCP Connector", connector.getConnectUri() });
+			// create a String array of spring context files
+			springConfigFileArray = new String[deploymentDescriptors.length];
+			deployedDescriptors = new String[deploymentDescriptors.length];
 
-			connectorList = connector.getName();
-			if (System.getProperty("StompSupport") != null)
-			{
-				String stompURI = generateInternalURI("stomp", 61613, false, false);
-				stompConnector = service.addConnector(stompURI);
-				System.out.println("Adding STOMP Connector:" + stompConnector.getConnectUri());
-				UIMAFramework.getLogger(CLASS_NAME).logrb(Level.CONFIG, CLASS_NAME.getName(), "JmsMessageContext", JmsConstants.JMS_LOG_RESOURCE_BUNDLE, "UIMAJMS_adding_connector__CONFIG", new Object[]
-				{ "Adding STOMP Connector", stompConnector.getConnectUri() });
-				connectorList += "," + stompConnector.getName();
-			}
-			if (System.getProperty("HTTP") != null)
+			Dd2spring aDd2Spring = new Dd2spring();
+			for (int dd = 0; dd < deploymentDescriptors.length; dd++)
 			{
-				String stringPort = System.getProperty("HTTP");
-				int p = Integer.parseInt(stringPort);
-				String httpURI = generateInternalURI("http", p, false, true);
-				httpConnector = service.addConnector(httpURI);
-				System.out.println("Adding HTTP Connector:" + httpConnector.getConnectUri());
-				UIMAFramework.getLogger(CLASS_NAME).logrb(Level.CONFIG, CLASS_NAME.getName(), "JmsMessageContext", JmsConstants.JMS_LOG_RESOURCE_BUNDLE, "UIMAJMS_adding_connector__CONFIG", new Object[]
-				{ "Adding HTTP Connector", httpConnector.getConnectUri() });
+				String deploymentDescriptor = deploymentDescriptors[dd];
+
+				File springConfigFile = aDd2Spring.convertDd2Spring(deploymentDescriptor, xslTransform, saxonURL, uimaAsDebug);
+
+				// if any are bad, fail
+				if (null == springConfigFile)
+				{
+					return null;
+				}
+				springConfigFileArray[dd] = springConfigFile.getAbsolutePath();
 
-				connectorList += "," + httpConnector.getName();
+				// get the descriptor to register with the engine controller
+				String deployDescriptor = "";
+				File afile = null;
+				FileInputStream fis = null;
+				try
+				{
+					afile = new File(deploymentDescriptor);
+					fis = new FileInputStream(afile);
+					byte[] bytes = new byte[(int) afile.length()];
+					fis.read(bytes);
+					deployDescriptor = new String(bytes);
+					deployedDescriptors[dd] = deployDescriptor;
+					// Log Deployment Descriptor
+					UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINEST, CLASS_NAME.getName(), "main", JmsConstants.JMS_LOG_RESOURCE_BUNDLE, "UIMAJMS_deploy_desc__FINEST", new Object[]
+					{ deployDescriptor });
+				}
+				catch (IOException e)
+				{
+					e.printStackTrace();
+				}
+				finally
+				{
+					if (fis != null)
+					{
+						try
+						{
+							fis.close();
+						}
+						catch (IOException e)
+						{
+						}
+					}
+				}
 			}
-			service.start();
-			System.setProperty("ActiveMQConnectors", connectorList);
-			System.out.println("Broker Service Started - URL:" + service.getVmConnectorURI());
-			UIMAFramework.getLogger(CLASS_NAME).logrb(Level.CONFIG, CLASS_NAME.getName(), "JmsMessageContext", JmsConstants.JMS_LOG_RESOURCE_BUNDLE, "UIMAJMS_broker_started__CONFIG", new Object[]
-			{ service.getVmConnectorURI() });
 		}
+		return springConfigFileArray;
+		
 
-		// Allow the connector time to start
-		synchronized (semaphore)
-		{
-			semaphore.wait(5000);
-		}
-		System.setProperty("jms.brokerUrl", brokerURI);
+		
 	}
-
 	/**
-	 * Generates a unique port for the Network Connector that will be plugged
-	 * into the internal Broker. This connector externalizes the internal broker
-	 * so that remote delegates can reply back to the Aggregate. This method
-	 * tests port 18810 for availability and it fails increments the port by one
-	 * until a port is valid.
+	 * Deploy Spring context files in a Spring Container.
 	 * 
-	 * @return - Broker URI with a unique port
+	 * @param springContextFiles - array of Spring context files
+	 * 
+	 * @throws Exception
 	 */
-
-	private String generateInternalURI(String aProtocol, int aDefaultPort, boolean cacheURL, boolean oneTry) throws Exception
+	public void deploy( String[] springContextFiles ) throws Exception
 	{
-		boolean success = false;
-		int openPort = aDefaultPort;
-		ServerSocket ssocket = null;
-
-		while (!success)
+		SpringContainerDeployer springDeployer =
+			new SpringContainerDeployer();
+		// now try to deploy the array of spring context files
+		springDeployer.deploy(springContextFiles);
+		//	Poll the deployer for the initialization status. Wait for either successful
+		//	initialization or failure.
+		while( !springDeployer.isInitialized() && !springDeployer.initializationFailed())
 		{
-			try
+			synchronized( springDeployer )
 			{
-				ssocket = new ServerSocket(openPort);
-				UIMAFramework.getLogger(CLASS_NAME).logrb(Level.CONFIG, CLASS_NAME.getName(), "generateInternalURI", JmsConstants.JMS_LOG_RESOURCE_BUNDLE, "UIMAJMS_port_available__CONFIG", new Object[]
-				{ openPort });
-
-				String uri = aProtocol + "://" + ssocket.getInetAddress().getLocalHost().getCanonicalHostName() + ":" + openPort;
-				success = true;
-				if (cacheURL)
-				{
-					System.setProperty("BrokerURI", uri);
-				}
-				return uri;
+				springDeployer.wait(100);
 			}
-			catch (BindException e)
+		}
+		//	Check if the deployer failed
+		if ( springDeployer.initializationFailed() )
+		{
+			throw new ResourceInitializationException();
+		}
+		//	Register this class to receive Spring container notifications. Specifically, looking
+		//	for an even signaling the container termination. This is done so that we can stop
+		//	the monitor thread
+		FileSystemXmlApplicationContext context = springDeployer.getSpringContext();
+		context.addApplicationListener(this);
+	}
+	/**
+	 * Creates an instance of a {@link JmxMonitor}, initializes it with the JMX Server URI and
+	 * checkpoint frequency, and finally starts the monitor.
+	 * 
+	 * @param samplingFrequency - how often the JmxMonitor should checkpoint to fetch service metrics
+	 * 
+	 * @throws Exception - error on monitor initialization or startup
+	 */
+	public void startMonitor(long samplingFrequency) throws Exception
+	{
+		monitor = new JmxMonitor();
+
+		//	Check if the monitor should run in the verbose mode. In this mode
+		//	the monitor dumps JMX Server URI, and a list of UIMA-AS services
+		//	found in that server. The default is to not show this info.
+		if ( System.getProperty("verbose") != null )
+		{
+			monitor.setVerbose();
+		}
+
+		//	Use the URI provided in the first arg to connect to the JMX server.
+		//	Also define sampling frequency. The monitor will collect the metrics
+		//	at this interval.
+		String jmxServerPort = null;
+		//	get the port of the JMX Server. This property can be set on the command line via -d
+		//	OR it is set automatically by the code that creates an internal JMX Server. The latter
+		//	is created in the {@link BaseAnalysisEngineController} constructor.
+		if ( ( jmxServerPort = System.getProperty("com.sun.management.jmxremote.port")) != null )
+		{
+			//	parameter is set, compose the URI
+			String jmxServerURI = "service:jmx:rmi:///jndi/rmi://localhost:"+jmxServerPort+"/jmxrmi";
+			//	Connect to the JMX Server, configure checkpoint frequency, create MBean proxies for 
+			//	UIMA-AS MBeans and service input queues
+			monitor.initialize(jmxServerURI, samplingFrequency);
+			// Create formatter listener
+			JmxMonitorListener listener = null;
+			String formatterListenerClass = null;
+			//	Check if a custom monitor formatter listener class is provided. The user provides this
+			//	formatter by adding a -Djmx.monitor.formatter=<class> parameter which specifies a class
+			//	that implements {@link JmxMonitorListener} interface
+			if ( (formatterListenerClass = System.getProperty(JmxMonitor.FormatterListener)) != null )
 			{
-				UIMAFramework.getLogger(CLASS_NAME).logrb(Level.CONFIG, CLASS_NAME.getName(), "generateInternalURI", JmsConstants.JMS_LOG_RESOURCE_BUNDLE, "UIMAJMS_port_not_available__CONFIG", new Object[]
-				{ openPort });
-				if (oneTry)
+				Object object = null;
+				try
 				{
-					System.out.println("Given port:" + openPort + " is not available for " + aProtocol);
-					throw e;
+					//	Instantiate the formatter listener class
+					Class formatterClass = Class.forName( formatterListenerClass );
+					object = formatterClass.newInstance();
 				}
-				openPort++;
-			}
-			catch (Exception e)
-			{
-				e.printStackTrace();
-				UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, CLASS_NAME.getName(), "generateInternalURI", JmsConstants.JMS_LOG_RESOURCE_BUNDLE, "UIMAJMS_exception__WARNING", new Object[]
-				{ JmsConstants.threadName(), e });
-				if (oneTry)
+				catch( ClassNotFoundException e)
 				{
+					System.out.println("Class Not Found:"+formatterListenerClass+". Provide a Formatter Class Which Implements:org.apache.uima.aae.jmx.monitor.JmxMonitorListener");
 					throw e;
 				}
-			}
-			finally
-			{
-				try
+				if ( object instanceof JmxMonitorListener )
 				{
-					if (ssocket != null)
-					{
-						ssocket.close();
-					}
+					listener = (JmxMonitorListener)object; 
 				}
-				catch (IOException ioe)
+				else
 				{
+					throw new InvalidClassException("Invalid Monitor Formatter Class:"+formatterListenerClass+".The Monitor Requires a Formatter Which Implements:org.apache.uima.aae.jmx.monitor.JmxMonitorListener");
 				}
 			}
+			else
+			{
+				//	The default formatter listener which logs to the UIMA log
+				listener = new BasicUimaJmxMonitorListener(monitor.getMaxServiceNameLength());
+			}
+			//	Plug in the monitor listener
+			monitor.addJmxMonitorListener(listener);
+			//	Create and start the monitor thread
+			monitorThread = new Thread(monitor);
+			
+			//	Start the monitor thread. It will run until the Spring container stops. When this happens
+			//	the UIMA_Service receives notication via a {@code onApplicationEvent()} callback. There
+			//	the monitor is stopped allowing the service to terminate.
+			monitorThread.start();
+			System.out.println(">>> Started JMX Monitor.\n\t>>> MBean Server Port:"+jmxServerPort+"\n\t>>> Monitor Checkpoint Frequency:"+samplingFrequency+"\n\t>>> Monitor Formatter Class:"+listener.getClass().getName());
 		}
-		return null;
-
-	}
-
-	public ApplicationContext initialize(String[] springXmlConfigFiles) throws ResourceInitializationException
-	{
-		try
-		{
-			ApplicationContext ctx = new FileSystemXmlApplicationContext(springXmlConfigFiles);
-			((AbstractApplicationContext) ctx).registerShutdownHook();
-			return ctx;
-		}
-		catch (Exception e)
-		{
-			throw new ResourceInitializationException(e);
-		}
+		
 	}
 
 	/**
@@ -288,50 +353,13 @@
 		System.out.println(" Arguments to the program are as follows : \n" + "-d path-to-UIMA-Deployment-Descriptor [-d path-to-UIMA-Deployment-Descriptor ...] \n" + "-saxon path-to-saxon.jar \n" + "-xslt path-to-dd2spring-xslt\n" + "   or\n"
 				+ "path to Spring XML Configuration File which is the output of running dd2spring\n");
 	}
-	protected void waitForServiceNotification() throws Exception {
-
-		while (!serviceInitializationCompleted) {
-			if (serviceInitializationException) {
-				throw new ResourceInitializationException();
-			}
-			UIMAFramework.getLogger(CLASS_NAME).logrb(Level.INFO, CLASS_NAME.getName(), "waitForServiceNotification", JmsConstants.JMS_LOG_RESOURCE_BUNDLE, "UIMAJMS_awaiting_container_init__INFO", new Object[] {});
-
-			synchronized (serviceMonitor) {
-				serviceMonitor.wait();
-			}
-			if (serviceInitializationException) {
-				throw new ResourceInitializationException();
-			}
-		}
-	}
-	public void notifyOnInitializationFailure(Exception e) {
-		notifyOnInitializationFailure( null, e);
-	}
-
-	public void notifyOnInitializationSuccess() {
-		notifyOnInitializationSuccess(null);
-	}
-	public void notifyOnInitializationSuccess(AnalysisEngineController aController) {
-		serviceInitializationCompleted = true;
-		synchronized (serviceMonitor) {
-			serviceMonitor.notifyAll();
-		}
-	}
-
-	public void notifyOnInitializationFailure(AnalysisEngineController aController, Exception e) {
-
-		// Initialization exception. Notify blocking thread and indicate a
-		// problem
-		serviceInitializationException = true;
-		UIMAFramework.getLogger(CLASS_NAME).logrb(Level.WARNING, CLASS_NAME.getName(), "notifyOnInitializationFailure", JmsConstants.JMS_LOG_RESOURCE_BUNDLE, "UIMAJMS_container_init_exception__WARNING", new Object[] {e});
-		synchronized (serviceMonitor) {
-			serviceMonitor.notifyAll();
+	public void onApplicationEvent(ApplicationEvent event) {
+		if ( event instanceof ContextClosedEvent && monitor != null && monitor.isRunning() )
+		{
+			System.out.println("Stopping Monitor");
+			//	Stop the monitor. The service has stopped
+			monitor.doStop();
 		}
-
-	}
-
-
-	public void notifyOnTermination(String message) {
 	}
 
 	/**
@@ -353,100 +381,31 @@
 	 */
 	public static void main(String[] args)
 	{
-		UIMAFramework.getLogger(CLASS_NAME).log(Level.INFO, "UIMA-AS version " + UIMAFramework.getVersionString());
-
-		String[] springConfigFileArray =
-		{};
-		String[] deployedDescriptors =
-		{};
-		String[] deploymentDescriptors =
-		{};
-		int nbrOfArgs = args.length;
-
-		deploymentDescriptors = getMultipleArg("-d", args);
-		if (deploymentDescriptors.length == 0)
-		{
-		  // allow multiple args for one key
-			deploymentDescriptors = getMultipleArg2("-dd", args);
-		}
-		String saxonURL = getArg("-saxonURL", args);
-		String xslTransform = getArg("-xslt", args);
-		String uimaAsDebug = getArg("-uimaEeDebug", args);
-		
-		if (nbrOfArgs < 1 || (args[0].startsWith("-") && (deploymentDescriptors.length == 0 || saxonURL.equals("") || xslTransform.equals(""))))
-		{
-			printUsageMessage();
-			return;
-		}
-
-		if (deploymentDescriptors.length == 0)
-		{
-			// array of context files passed in
-			springConfigFileArray = args;
-			deployedDescriptors = args;
-		}
-		else
+		try
 		{
-			// create a String array of spring context files
-			springConfigFileArray = new String[deploymentDescriptors.length];
-			deployedDescriptors = new String[deploymentDescriptors.length];
-
-			Dd2spring aDd2Spring = new Dd2spring();
-			for (int dd = 0; dd < deploymentDescriptors.length; dd++)
+			UIMA_Service service = new UIMA_Service();
+			//	parse command args and run dd2spring to generate spring context
+			//	files from deployment descriptors
+			String contextFiles[] = service.initialize(args);
+			//	If no context files generated there is nothing to do
+			if ( contextFiles == null )
 			{
-				String deploymentDescriptor = deploymentDescriptors[dd];
-
-				File springConfigFile = aDd2Spring.convertDd2Spring(deploymentDescriptor, xslTransform, saxonURL, uimaAsDebug);
-
-				// if any are bad, fail
-				if (null == springConfigFile)
-				{
-					return;
-				}
-				springConfigFileArray[dd] = springConfigFile.getAbsolutePath();
-
-				// get the descriptor to register with the engine controller
-				String deployDescriptor = "";
-				File afile = null;
-				FileInputStream fis = null;
-				try
-				{
-					afile = new File(deploymentDescriptor);
-					fis = new FileInputStream(afile);
-					byte[] bytes = new byte[(int) afile.length()];
-					fis.read(bytes);
-					deployDescriptor = new String(bytes);
-					deployedDescriptors[dd] = deployDescriptor;
-					// Log Deployment Descriptor
-					UIMAFramework.getLogger(CLASS_NAME).logrb(Level.FINEST, CLASS_NAME.getName(), "main", JmsConstants.JMS_LOG_RESOURCE_BUNDLE, "UIMAJMS_deploy_desc__FINEST", new Object[]
-					{ deployDescriptor });
-				}
-				catch (IOException e)
-				{
-					e.printStackTrace();
-				}
-				finally
-				{
-					if (fis != null)
-					{
-						try
-						{
-							fis.close();
-						}
-						catch (IOException e)
-						{
-						}
-					}
-				}
+				return;
+			}
+			//	Deploy components defined in Spring context files. This method blocks until
+			//	the container is fully initialized and all UIMA-AS components are succefully
+			//	deployed.
+			service.deploy( contextFiles );
+			//	Check if we should start an optional JMX-based monitor that will provide service metrics
+			//	The monitor is enabled by existence of -Djmx.monitor.frequency=<number> parameter. By default
+			//	the monitor is not enabled.
+			String monitorCheckpointFrequency;
+			if ( ( monitorCheckpointFrequency = System.getProperty(JmxMonitor.CheckpointFrequency)) != null)
+			{
+				//	Found monitor checkpoint frequency parameter, configure and start the monitor.
+				//	If the monitor fails to initialize the service is not effected. 
+				service.startMonitor(Long.parseLong(monitorCheckpointFrequency));
 			}
-		}
-
-		// now try to deploy the array of spring context files
-		SpringContainerDeployer springDeployer =
-			new SpringContainerDeployer();
-		try
-		{
-			springDeployer.deploy(springConfigFileArray);
 		}
 		catch( Exception e)
 		{