uima-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From cwik...@apache.org
Subject svn commit: r810549 - in /incubator/uima/uima-as/trunk/uimaj-as-activemq/src/main/java/org/apache/uima: adapter/jms/service/UIMA_Service.java examples/as/RunRemoteAsyncAE.java
Date Wed, 02 Sep 2009 15:17:15 GMT
Author: cwiklik
Date: Wed Sep  2 15:17:14 2009
New Revision: 810549

URL: http://svn.apache.org/viewvc?rev=810549&view=rev
Log:
UIMA-1541 Reformatted to conform to UIMA formatting guidelines. No other changes included.

Modified:
    incubator/uima/uima-as/trunk/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/service/UIMA_Service.java
    incubator/uima/uima-as/trunk/uimaj-as-activemq/src/main/java/org/apache/uima/examples/as/RunRemoteAsyncAE.java

Modified: incubator/uima/uima-as/trunk/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/service/UIMA_Service.java
URL: http://svn.apache.org/viewvc/incubator/uima/uima-as/trunk/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/service/UIMA_Service.java?rev=810549&r1=810548&r2=810549&view=diff
==============================================================================
--- incubator/uima/uima-as/trunk/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/service/UIMA_Service.java (original)
+++ incubator/uima/uima-as/trunk/uimaj-as-activemq/src/main/java/org/apache/uima/adapter/jms/service/UIMA_Service.java Wed Sep  2 15:17:14 2009
@@ -1,4 +1,3 @@
-
 /*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
@@ -40,418 +39,389 @@
 import org.springframework.context.event.ContextClosedEvent;
 import org.springframework.context.support.FileSystemXmlApplicationContext;
 
-public class UIMA_Service implements  ApplicationListener
-{
-	private static final Class CLASS_NAME = UIMA_Service.class;
-
-	protected boolean serviceInitializationCompleted;
-	protected boolean serviceInitializationException;
-	protected Object serviceMonitor = new Object();
-	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[] 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 null;
-		}
-    String brokerURL = getArg("-brokerURL",args);
-    // Check if broker URL is specified on the command line. If it is not, use the default 
+public class UIMA_Service implements ApplicationListener {
+  private static final Class CLASS_NAME = UIMA_Service.class;
+
+  protected boolean serviceInitializationCompleted;
+
+  protected boolean serviceInitializationException;
+
+  protected Object serviceMonitor = new Object();
+
+  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[] 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 null;
+    }
+    String brokerURL = getArg("-brokerURL", args);
+    // Check if broker URL is specified on the command line. If it is not, use the default
     // localhost:61616. In either case, set the System property defaultBrokerURL. It will be used
-    //  by Spring Framework to substitute a place holder in Spring xml.
-    if ( brokerURL != "") {
+    // by Spring Framework to substitute a place holder in Spring xml.
+    if (brokerURL != "") {
       System.setProperty("defaultBrokerURL", brokerURL);
     } else {
       System.setProperty("defaultBrokerURL", "tcp://localhost:61616");
     }
-    System.out.println(">>> Setting defaultBrokerURL to:"+System.getProperty("defaultBrokerURL"));
-    
-    if ( System.getProperty(JmsConstants.SessionTimeoutOverride) != null ) {
-      System.out.println(">>> Setting Inactivity Timeout To: "+System.getProperty(JmsConstants.SessionTimeoutOverride));
-    }
-    if (deploymentDescriptors.length == 0)
-		{
-			// array of context files passed in
-			springConfigFileArray = args;
-		}
-		else
-		{
-			// create a String array of spring context files
-			springConfigFileArray = new String[deploymentDescriptors.length];
-
-			Dd2spring aDd2Spring = new Dd2spring();
-			for (int dd = 0; dd < deploymentDescriptors.length; dd++)
-			{
-				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();
-
-				// 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);
-					// 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 springConfigFileArray;
-		
-
-		
-	}
-	/**
-	 * Deploy Spring context files in a Spring Container.
-	 * 
-	 * @param springContextFiles - array of Spring context files
-	 * 
-	 * @throws Exception
-	 */
-	public SpringContainerDeployer deploy( String[] springContextFiles ) throws Exception
-	{
-		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())
-		{
-			synchronized( springDeployer )
-			{
-				springDeployer.wait(100);
-			}
-		}
-		//	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);
-		return springDeployer;
-	}
-	/**
-	 * 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 )
-			{
-				Object object = null;
-				try
-				{
-					//	Instantiate the formatter listener class
-					Class formatterClass = Class.forName( formatterListenerClass );
-					object = formatterClass.newInstance();
-				}
-				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;
-				}
-				if ( object instanceof JmxMonitorListener )
-				{
-					listener = (JmxMonitorListener)object; 
-				}
-				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());
-		}
-		
-	}
-
-	/**
-	 * scan args for a particular arg, return the following token or the empty
-	 * string if not found
-	 * 
-	 * @param id
-	 *            the arg to search for
-	 * @param args
-	 *            the array of strings
-	 * @return the following token, or a 0 length string if not found
-	 */
-	private static String getArg(String id, String[] args)
-	{
-		for (int i = 0; i < args.length; i++)
-		{
-			if (id.equals(args[i]))
-				return (i + 1 < args.length) ? args[i + 1] : "";
-		}
-		return "";
-	}
-
-	/**
-	 * scan args for a particular arg, return the following token(s) or the
-	 * empty string if not found
-	 * 
-	 * @param id
-	 *            the arg to search for
-	 * @param args
-	 *            the array of strings
-	 * @return the following token, or a 0 length string array if not found
-	 */
-	private static String[] getMultipleArg(String id, String[] args)
-	{
-		String[] retr =
-		{};
-		for (int i = 0; i < args.length; i++)
-		{
-			if (id.equals(args[i]))
-			{
-				String[] temp = new String[retr.length + 1];
-				for (int s = 0; s < retr.length; s++)
-				{
-					temp[s] = retr[s];
-				}
-				retr = temp;
-				retr[retr.length - 1] = (i + 1 < args.length) ? args[i + 1] : null;
-			}
-		}
-		return retr;
-	}
+    System.out.println(">>> Setting defaultBrokerURL to:" + System.getProperty("defaultBrokerURL"));
+
+    if (System.getProperty(JmsConstants.SessionTimeoutOverride) != null) {
+      System.out.println(">>> Setting Inactivity Timeout To: "
+              + System.getProperty(JmsConstants.SessionTimeoutOverride));
+    }
+    if (deploymentDescriptors.length == 0) {
+      // array of context files passed in
+      springConfigFileArray = args;
+    } else {
+      // create a String array of spring context files
+      springConfigFileArray = new String[deploymentDescriptors.length];
+
+      Dd2spring aDd2Spring = new Dd2spring();
+      for (int dd = 0; dd < deploymentDescriptors.length; dd++) {
+        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();
+
+        // 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);
+          // 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 springConfigFileArray;
+
+  }
+
+  /**
+   * Deploy Spring context files in a Spring Container.
+   * 
+   * @param springContextFiles
+   *          - array of Spring context files
+   * 
+   * @throws Exception
+   */
+  public SpringContainerDeployer deploy(String[] springContextFiles) throws Exception {
+    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()) {
+      synchronized (springDeployer) {
+        springDeployer.wait(100);
+      }
+    }
+    // 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);
+    return springDeployer;
+  }
 
   /**
-   * scan args for a particular arg, return the following token(s) or the empty
-   * string if not found
+   * 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) {
+        Object object = null;
+        try {
+          // Instantiate the formatter listener class
+          Class formatterClass = Class.forName(formatterListenerClass);
+          object = formatterClass.newInstance();
+        } 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;
+        }
+        if (object instanceof JmxMonitorListener) {
+          listener = (JmxMonitorListener) object;
+        } 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());
+    }
+
+  }
+
+  /**
+   * scan args for a particular arg, return the following token or the empty string if not found
    * 
    * @param id
-   *            the arg to search for
+   *          the arg to search for
    * @param args
-   *            the array of strings
+   *          the array of strings
+   * @return the following token, or a 0 length string if not found
+   */
+  private static String getArg(String id, String[] args) {
+    for (int i = 0; i < args.length; i++) {
+      if (id.equals(args[i]))
+        return (i + 1 < args.length) ? args[i + 1] : "";
+    }
+    return "";
+  }
+
+  /**
+   * scan args for a particular arg, return the following token(s) or the empty string if not found
+   * 
+   * @param id
+   *          the arg to search for
+   * @param args
+   *          the array of strings
    * @return the following token, or a 0 length string array if not found
    */
-  private static String[] getMultipleArg2(String id, String[] args)
-  {
+  private static String[] getMultipleArg(String id, String[] args) {
     String[] retr = {};
     for (int i = 0; i < args.length; i++) {
       if (id.equals(args[i])) {
-        int j=0;
-        while ( (i+1+j < args.length) && !args[i+1+j].startsWith("-") ) {
+        String[] temp = new String[retr.length + 1];
+        for (int s = 0; s < retr.length; s++) {
+          temp[s] = retr[s];
+        }
+        retr = temp;
+        retr[retr.length - 1] = (i + 1 < args.length) ? args[i + 1] : null;
+      }
+    }
+    return retr;
+  }
+
+  /**
+   * scan args for a particular arg, return the following token(s) or the empty string if not found
+   * 
+   * @param id
+   *          the arg to search for
+   * @param args
+   *          the array of strings
+   * @return the following token, or a 0 length string array if not found
+   */
+  private static String[] getMultipleArg2(String id, String[] args) {
+    String[] retr = {};
+    for (int i = 0; i < args.length; i++) {
+      if (id.equals(args[i])) {
+        int j = 0;
+        while ((i + 1 + j < args.length) && !args[i + 1 + j].startsWith("-")) {
           String[] temp = new String[retr.length + 1];
-          for (int s=0; s<retr.length; s++) {
+          for (int s = 0; s < retr.length; s++) {
             temp[s] = retr[s];
-            }
-          retr = temp;
-          retr[retr.length-1] = args[i + 1 + j++];
           }
-        return retr;
+          retr = temp;
+          retr[retr.length - 1] = args[i + 1 + j++];
         }
+        return retr;
       }
+    }
     return retr;
+  }
+
+  protected void finalize() {
+    System.err.println(this + " finalized");
+  }
+
+  private static void printUsageMessage() {
+    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"
+                    + "-defaultBrokerURL the default broker URL to use for the service and all its delegates");
+  }
+
+  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();
     }
-  
-	protected void finalize()
-	{
-	     System.err.println(this + " finalized");
-	}	
-
-	private static void printUsageMessage()
-	{
-		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"+
-				"-defaultBrokerURL the default broker URL to use for the service and all its delegates");
-	}
-	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();
-		}
-	}
-
-	/**
-	 * The main routine for starting the deployment of a UIMA-AS instance. The
-	 * args are either: 1 or more "paths" to Spring XML descriptors representing
-	 * the information needed or some number of parameters, preceeded by a "-"
-	 * sign. If the first arg doesn't start with a "-" it is presumed to be the
-	 * first format.
-	 * 
-	 * For the 2nd style, the arguments are: -saxonURL a-URL-to-the-saxon-jar
-	 * usually starting with "file:", -xslt path-to-the-dd2spring.xsl file, -d
-	 * path-to-UIMA-deployment-descriptor [-d path-to-another-dd ...] these
-	 * arguments may be in any order)
-   * 
-   * For the 3rd style, like #2 but with multiple dd-files following a single -dd
-   * Useful for calling from scripts.
-	 * 
-	 * @param args
-	 */
-	public static void main(String[] args)
-	{
-		try
-		{
-			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 )
-			{
-				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.
-			SpringContainerDeployer serviceDeployer = service.deploy( contextFiles );
-			
-			if ( serviceDeployer == null ) {
-			  System.out.println(">>> Failed to Deploy UIMA Service. Check Logs for Details");
-			  System.exit(1);
-			}
-			//	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));
-			}
-      AnalysisEngineController topLevelControllor = 
-        serviceDeployer.getTopLevelController();
-      if ( topLevelControllor != null ) {
+  }
+
+  /**
+   * The main routine for starting the deployment of a UIMA-AS instance. The args are either: 1 or
+   * more "paths" to Spring XML descriptors representing the information needed or some number of
+   * parameters, preceeded by a "-" sign. If the first arg doesn't start with a "-" it is presumed
+   * to be the first format.
+   * 
+   * For the 2nd style, the arguments are: -saxonURL a-URL-to-the-saxon-jar usually starting with
+   * "file:", -xslt path-to-the-dd2spring.xsl file, -d path-to-UIMA-deployment-descriptor [-d
+   * path-to-another-dd ...] these arguments may be in any order)
+   * 
+   * For the 3rd style, like #2 but with multiple dd-files following a single -dd Useful for calling
+   * from scripts.
+   * 
+   * @param args
+   */
+  public static void main(String[] args) {
+    try {
+      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) {
+        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.
+      SpringContainerDeployer serviceDeployer = service.deploy(contextFiles);
+
+      if (serviceDeployer == null) {
+        System.out.println(">>> Failed to Deploy UIMA Service. Check Logs for Details");
+        System.exit(1);
+      }
+      // 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));
+      }
+      AnalysisEngineController topLevelControllor = serviceDeployer.getTopLevelController();
+      if (topLevelControllor != null) {
         System.out.println("Enter 'q' to quiesce and stop the service or 's' to stop it now:");
-      //  Loop forever or until the service is stopped  
-      while(!topLevelControllor.isStopped()) {
-          if ( System.in.available() > 0 ) {
+        // Loop forever or until the service is stopped
+        while (!topLevelControllor.isStopped()) {
+          if (System.in.available() > 0) {
             int c = System.in.read();
-            if ( c == 's') {
+            if (c == 's') {
               serviceDeployer.undeploy(SpringContainerDeployer.STOP_NOW);
-            } else if ( c == 'q') {
+            } else if (c == 'q') {
               serviceDeployer.undeploy(SpringContainerDeployer.QUIESCE_AND_STOP);
-            } else if ( Character.isLetter(c) || Character.isDigit(c)) {
-              System.out.println("Enter 'q' to quiesce and stop the service or 's' to stop it now:");
+            } else if (Character.isLetter(c) || Character.isDigit(c)) {
+              System.out
+                      .println("Enter 'q' to quiesce and stop the service or 's' to stop it now:");
             }
-          } 
-          //  This is a polling loop. Sleep for 1 sec
+          }
+          // This is a polling loop. Sleep for 1 sec
           try {
-            Thread.sleep(1000); 
-          } catch( InterruptedException ex) {
+            Thread.sleep(1000);
+          } catch (InterruptedException ex) {
           }
-        }  // while
+        } // while
       }
-		}
-		catch( Exception e)
-		{
-			e.printStackTrace();
-		}
-	}
+    } catch (Exception e) {
+      e.printStackTrace();
+    }
+  }
 
 }

Modified: incubator/uima/uima-as/trunk/uimaj-as-activemq/src/main/java/org/apache/uima/examples/as/RunRemoteAsyncAE.java
URL: http://svn.apache.org/viewvc/incubator/uima/uima-as/trunk/uimaj-as-activemq/src/main/java/org/apache/uima/examples/as/RunRemoteAsyncAE.java?rev=810549&r1=810548&r2=810549&view=diff
==============================================================================
--- incubator/uima/uima-as/trunk/uimaj-as-activemq/src/main/java/org/apache/uima/examples/as/RunRemoteAsyncAE.java (original)
+++ incubator/uima/uima-as/trunk/uimaj-as-activemq/src/main/java/org/apache/uima/examples/as/RunRemoteAsyncAE.java Wed Sep  2 15:17:14 2009
@@ -48,32 +48,31 @@
 /**
  * Example application that calls a Remote Asynchronous Analysis Engine on a collection.
  * <p>
- * Arguments: brokerUrl endpoint [options] 
- *     [-t Timeout] [-i]
+ * Arguments: brokerUrl endpoint [options] [-t Timeout] [-i]
  * <p>
  * This connects to a remote AE at specified brokerUrl and endpoint (which must match what is in the
  * service's deployment descriptor. The following optional arguments are accepted:
  * <ul>
- * <li>-d Specifies a deployment descriptor. The specified service will be deployed before processing
- * begin, and the service will be undeployed after processing completes. 
- * Multiple -d entries can be given.</li>
+ * <li>-d Specifies a deployment descriptor. The specified service will be deployed before
+ * processing begin, and the service will be undeployed after processing completes. Multiple -d
+ * entries can be given.</li>
  * <li>-c Specifies a CollectionReader descriptor. The client will read CASes from the
  * CollectionReader and send them to the service for processing. If this option is ommitted, one
  * empty CAS will be sent to the service (useful for services containing a CAS Multiplier acting as
  * a collection reader).</li>
- * <li>-p  Specifies CAS pool size, which determines the maximum number of requests that can be outstanding.</li>
- * <li>-f  Specifies the initial FS heap size in bytes of each CAS in the pool.</li>
- * <li>-o Specifies an Output Directory. All CASes received by the client's CallbackListener will
- * be serialized to XMI in the specified OutputDir. If ommitted, no XMI files will be output.</li>
- * <li>-t Specifies a timeout period in seconds.  If a CAS does not return within this time period it
- * is considered an error.  By default there is no timeout, so the client will wait forever.</li>
- * <li>-i Causes the client to ignore errors returned from the service.  If not specified, the client
+ * <li>-p Specifies CAS pool size, which determines the maximum number of requests that can be
+ * outstanding.</li>
+ * <li>-f Specifies the initial FS heap size in bytes of each CAS in the pool.</li>
+ * <li>-o Specifies an Output Directory. All CASes received by the client's CallbackListener will be
+ * serialized to XMI in the specified OutputDir. If ommitted, no XMI files will be output.</li>
+ * <li>-t Specifies a timeout period in seconds. If a CAS does not return within this time period it
+ * is considered an error. By default there is no timeout, so the client will wait forever.</li>
+ * <li>-i Causes the client to ignore errors returned from the service. If not specified, the client
  * terminates on the first error.</li>
  * <li>-log Output details on each process request.</li>
  * <li>-uimaEeDebug true causes various debugging things to happen, including *not* deleting the
- * generated spring file generated by running dd-2-spring.  This parameter only affects deployments 
- * specified using the -d parameter that follow
- * it in the command line sequence.</li>
+ * generated spring file generated by running dd-2-spring. This parameter only affects deployments
+ * specified using the -d parameter that follow it in the command line sequence.</li>
  * </ul>
  */
 public class RunRemoteAsyncAE {
@@ -88,42 +87,44 @@
   private int fsHeapSize = 2000000;
 
   private File outputDir = null;
-  
+
   private int timeout = 0;
-  
+
   private int getmeta_timeout = 60;
-  
+
   private int cpc_timeout = 0;
-  
+
   private boolean ignoreErrors = false;
-  
+
   private boolean logCas = false;
-  
+
   /**
    * Start time of the processing - used to compute elapsed time.
    */
-  private static long mStartTime = System.nanoTime()/1000000;
+  private static long mStartTime = System.nanoTime() / 1000000;
 
   private UimaAsynchronousEngine uimaEEEngine = null;
 
-  Map<String,Object> appCtx;
+  Map<String, Object> appCtx;
 
   // For logging CAS activity
   private ConcurrentHashMap casMap = new ConcurrentHashMap();
 
   /**
-   * Constructor for the class.  Parses command line arguments and sets the values of fields in this instance.
-   * If command line is invalid prints a message and calls System.exit().
+   * Constructor for the class. Parses command line arguments and sets the values of fields in this
+   * instance. If command line is invalid prints a message and calls System.exit().
    * 
    * @param args
    *          command line arguments into the program - see class description
    */
   public RunRemoteAsyncAE(String args[]) throws Exception {
-    
-    appCtx = new HashMap<String,Object>();
-    appCtx.put(UimaAsynchronousEngine.DD2SpringXsltFilePath, System.getenv("UIMA_HOME") + "/bin/dd2spring.xsl");
-    appCtx.put(UimaAsynchronousEngine.SaxonClasspath, "file:" + System.getenv("UIMA_HOME") + "/saxon/saxon8.jar");
-  
+
+    appCtx = new HashMap<String, Object>();
+    appCtx.put(UimaAsynchronousEngine.DD2SpringXsltFilePath, System.getenv("UIMA_HOME")
+            + "/bin/dd2spring.xsl");
+    appCtx.put(UimaAsynchronousEngine.SaxonClasspath, "file:" + System.getenv("UIMA_HOME")
+            + "/saxon/saxon8.jar");
+
     // parse command line
     for (int i = 0; i < args.length; i++) {
       if (args[i].startsWith("-")) {
@@ -140,7 +141,8 @@
           if (args[i].equals("-c")) {
             collectionReaderDescriptor = new File(args[++i]);
             if (!collectionReaderDescriptor.exists()) {
-              System.err.println("Collection Reader Descriptor file " + collectionReaderDescriptor.getPath() + " does not exist.");
+              System.err.println("Collection Reader Descriptor file "
+                      + collectionReaderDescriptor.getPath() + " does not exist.");
               printUsageAndExit();
             }
           } else if (args[i].equals("-p")) {
@@ -162,12 +164,12 @@
             }
           } else if (args[i].equals("-d")) {
             if (uimaEEEngine == null) {
-              //create Asynchronous Engine
+              // create Asynchronous Engine
               uimaEEEngine = new BaseUIMAAsynchronousEngine_impl();
             }
             String service = args[++i];
             System.out.println("Attempting to deploy " + service + " ...");
-            
+
             uimaEEEngine.deploy(service, appCtx);
           } else if (args[i].equals("-t")) {
             timeout = Integer.parseInt(args[++i]);
@@ -177,8 +179,7 @@
             cpc_timeout = Integer.parseInt(args[++i]);
           } else if (args[i].equals(UimaAsynchronousEngine.UimaEeDebug)) {
             appCtx.put(UimaAsynchronousEngine.UimaEeDebug, args[++i]);
-          }
-          else {
+          } else {
             System.err.println("Unknown switch " + args[i]);
             printUsageAndExit();
           }
@@ -186,14 +187,13 @@
       } else {
         if (brokerUrl == null) {
           brokerUrl = args[i];
-          //  Set System property that may be used by Spring while resolving a broker URL 
-          //  placeholder in the deployment descriptor. This is only used when launching
-          //  RunRemoteAsyncAE with -d option.
+          // Set System property that may be used by Spring while resolving a broker URL
+          // placeholder in the deployment descriptor. This is only used when launching
+          // RunRemoteAsyncAE with -d option.
           System.setProperty("defaultBrokerURL", brokerUrl);
         } else if (endpoint == null) {
           endpoint = args[i];
-        }
-        else {
+        } else {
           printUsageAndExit();
         }
       }
@@ -204,17 +204,17 @@
   }
 
   public void run() throws Exception {
-    
+
     if (uimaEEEngine == null) {
-      //create Asynchronous Engine
+      // create Asynchronous Engine
       uimaEEEngine = new BaseUIMAAsynchronousEngine_impl();
     }
 
-    //add Collection Reader if specified
+    // add Collection Reader if specified
     if (collectionReaderDescriptor != null) {
       CollectionReaderDescription collectionReaderDescription = UIMAFramework.getXMLParser()
               .parseCollectionReaderDescription(new XMLInputSource(collectionReaderDescriptor));
-  
+
       CollectionReader collectionReader = UIMAFramework
               .produceCollectionReader(collectionReaderDescription);
 
@@ -222,7 +222,7 @@
     }
     uimaEEEngine.addStatusCallbackListener(new StatusCallbackListenerImpl());
 
-    //set server URI and Endpoint
+    // set server URI and Endpoint
     // Add Broker URI
     appCtx.put(UimaAsynchronousEngine.ServerUri, brokerUrl);
     // Add Queue Name
@@ -234,32 +234,32 @@
 
     // Add the Cas Pool Size and initial FS heap size
     appCtx.put(UimaAsynchronousEngine.CasPoolSize, casPoolSize);
-    appCtx.put(UIMAFramework.CAS_INITIAL_HEAP_SIZE, Integer.valueOf(fsHeapSize/4).toString());
+    appCtx.put(UIMAFramework.CAS_INITIAL_HEAP_SIZE, Integer.valueOf(fsHeapSize / 4).toString());
 
-    //initialize
+    // initialize
     uimaEEEngine.initialize(appCtx);
 
-    //run
+    // run
     if (logCas) {
-        System.out.println("\nService-IPaddr\tSent\tDuration");
-      }
+      System.out.println("\nService-IPaddr\tSent\tDuration");
+    }
     if (collectionReaderDescriptor != null) {
       uimaEEEngine.process();
     } else {
-      //send an empty CAS
+      // send an empty CAS
       CAS cas = uimaEEEngine.getCAS();
       uimaEEEngine.sendCAS(cas);
       uimaEEEngine.collectionProcessingComplete();
     }
 
-//    if (logCas) {
-//      System.out.println();
-//      List<String> log = getLog();
-//      Iterator logline = log.iterator();
-//      while (logline.hasNext()) {
-//        System.out.println(logline.next());
-//      }
-//    }
+    // if (logCas) {
+    // System.out.println();
+    // List<String> log = getLog();
+    // Iterator logline = log.iterator();
+    // while (logline.hasNext()) {
+    // System.out.println(logline.next());
+    // }
+    // }
     uimaEEEngine.stop();
   }
 
@@ -267,34 +267,34 @@
    * 
    */
   private static void printUsageAndExit() {
-    System.out.println(
-      "Usage: runRemoteAsyncAE brokerUrl endpoint [options]\n\n" +
-      "This connects to a remote AE at specified brokerUrl and endpoint (which must match what is in the service's\n" +
-      "deployment descriptor.\n\nThe following optional arguments are accepted:\n" +
-      "-d  Specifies a deployment descriptor. The specified service will be deployed before processing begins." +
-      " Multiple -d entries can be given.\n" +
-      "-c  Specifies a CollectionReader descriptor.  The client will read CASes from the CollectionReader" +
-      " and send them to the service for processing.  If this option is ommitted, one empty CAS will be" +
-      " sent to the service (useful for services containing a CAS Multiplier acting as a collection reader).\n" +
-      "-b  Use binary serialization (default is xmi)\n" +
-      "-p  Specifies CAS pool size, which determines the maximum number of requests that can be outstanding.\n" +
-      "-f  Specifies the initial FS heap size in bytes of each CAS in the pool.\n" +
-      "-o  Specifies an Output Directory.  All CASes received by the client's CallbackListener will be serialized to XMI" +
-      " in the specified OutputDir.  If ommitted, no XMI files will be output.\n" +
-      "-t  Specifies a timeout period in seconds.  If a CAS does not return within this time period it" +
-      " is considered an error.  By default there is no timeout, so the client will wait forever.\n" +
-      "-it  Specifies a timeout period in seconds.  If the initialization request does not return within this time period it" +
-      " is considered an error.  By default the timeout is 60 seconds.\n" +
-      "-cpct  Specifies a timeout period in seconds.  When all CAS requests are completed, a collection process complete" +
-      " command is sent.  By default there is no timeout for CPC, so the client will wait forever.\n" +
-      "-log Output details on each process request: IP address of service that handled the request,\n" +
-      "     time in ms the CAS was sent, duration in ms from sendCas to receipt.\n" +
-      "-i  Causes the client to ignore errors returned from the service.  If not specified, the client" +
-      " terminates on the first error (including a timeout if the -t option is specified.\n" +
-      "-uimaEeDebug true    This is optional. Leave it out for normal operation. If specified, causes" +
-      " additional debugging things to happen, including *not* deleting the generated Spring xml file generated" +
-      " from running dd2spring.  It only affects deployments specified using the -d parameter that follow it on" +
-      " the command line");
+    System.out
+            .println("Usage: runRemoteAsyncAE brokerUrl endpoint [options]\n\n"
+                    + "This connects to a remote AE at specified brokerUrl and endpoint (which must match what is in the service's\n"
+                    + "deployment descriptor.\n\nThe following optional arguments are accepted:\n"
+                    + "-d  Specifies a deployment descriptor. The specified service will be deployed before processing begins."
+                    + " Multiple -d entries can be given.\n"
+                    + "-c  Specifies a CollectionReader descriptor.  The client will read CASes from the CollectionReader"
+                    + " and send them to the service for processing.  If this option is ommitted, one empty CAS will be"
+                    + " sent to the service (useful for services containing a CAS Multiplier acting as a collection reader).\n"
+                    + "-b  Use binary serialization (default is xmi)\n"
+                    + "-p  Specifies CAS pool size, which determines the maximum number of requests that can be outstanding.\n"
+                    + "-f  Specifies the initial FS heap size in bytes of each CAS in the pool.\n"
+                    + "-o  Specifies an Output Directory.  All CASes received by the client's CallbackListener will be serialized to XMI"
+                    + " in the specified OutputDir.  If ommitted, no XMI files will be output.\n"
+                    + "-t  Specifies a timeout period in seconds.  If a CAS does not return within this time period it"
+                    + " is considered an error.  By default there is no timeout, so the client will wait forever.\n"
+                    + "-it  Specifies a timeout period in seconds.  If the initialization request does not return within this time period it"
+                    + " is considered an error.  By default the timeout is 60 seconds.\n"
+                    + "-cpct  Specifies a timeout period in seconds.  When all CAS requests are completed, a collection process complete"
+                    + " command is sent.  By default there is no timeout for CPC, so the client will wait forever.\n"
+                    + "-log Output details on each process request: IP address of service that handled the request,\n"
+                    + "     time in ms the CAS was sent, duration in ms from sendCas to receipt.\n"
+                    + "-i  Causes the client to ignore errors returned from the service.  If not specified, the client"
+                    + " terminates on the first error (including a timeout if the -t option is specified.\n"
+                    + "-uimaEeDebug true    This is optional. Leave it out for normal operation. If specified, causes"
+                    + " additional debugging things to happen, including *not* deleting the generated Spring xml file generated"
+                    + " from running dd2spring.  It only affects deployments specified using the -d parameter that follow it on"
+                    + " the command line");
     System.exit(1);
   }
 
@@ -307,7 +307,7 @@
   public static void main(String[] args) throws Exception {
     RunRemoteAsyncAE runner = new RunRemoteAsyncAE(args);
     runner.run();
-//    System.exit(0);
+    // System.exit(0);
   }
 
   /**
@@ -338,7 +338,6 @@
       System.out.println("UIMAEE Initialization Complete");
     }
 
-
     /**
      * Called when the collection processing is completed.
      * 
@@ -359,9 +358,9 @@
         System.out.print("; " + size + " characters");
       }
       System.out.println();
-      long elapsedTime = System.nanoTime()/1000000 - mStartTime;
+      long elapsedTime = System.nanoTime() / 1000000 - mStartTime;
       System.out.println("Time Elapsed : " + elapsedTime + " ms ");
-      
+
       String perfReport = uimaEEEngine.getPerformanceReport();
       if (perfReport != null) {
         System.out.println("\n\n ------------------ PERFORMANCE REPORT ------------------\n");
@@ -381,8 +380,8 @@
      *          EntityProcessStatus that holds the status of all the events for aEntity
      */
     public void entityProcessComplete(CAS aCas, EntityProcessStatus aStatus) {
-      if (aStatus != null ) {
-        if ( aStatus.isException() ) {
+      if (aStatus != null) {
+        if (aStatus.isException()) {
           System.err.println("Error on process CAS call to remote service:");
           List exceptions = aStatus.getExceptions();
           for (int i = 0; i < exceptions.size(); i++) {
@@ -390,46 +389,46 @@
           }
           if (!ignoreErrors) {
             System.err.println("Terminating Client...");
-            // uimaEEEngine.stop();  TODO: Does not seem to work
+            // uimaEEEngine.stop(); TODO: Does not seem to work
             // return;
             System.exit(1);
           }
         }
         if (logCas) {
           String ip = "no IP";
-          List eList = aStatus.getProcessTrace().getEventsByComponentName("UimaEE",false);
-          for (int e=0; e<eList.size(); e++) {
-            ProcessTraceEvent event = (ProcessTraceEvent)eList.get(e);
+          List eList = aStatus.getProcessTrace().getEventsByComponentName("UimaEE", false);
+          for (int e = 0; e < eList.size(); e++) {
+            ProcessTraceEvent event = (ProcessTraceEvent) eList.get(e);
             if (event.getDescription().equals("Service IP")) {
               ip = event.getResultMessage();
             }
           }
-          String casId = ((UimaASProcessStatus)aStatus).getCasReferenceId();
-          if (  casId != null ) {
-              long current = System.nanoTime()/1000000 - mStartTime;
-              if ( casMap.containsKey(casId) ) {
-                Object value = casMap.get(casId);
-                if ( value != null && value instanceof Long ) {
-                  long start = ((Long)value).longValue();
-                  System.out.println(ip + "\t" + start + "\t" + (current-start));
-                }
+          String casId = ((UimaASProcessStatus) aStatus).getCasReferenceId();
+          if (casId != null) {
+            long current = System.nanoTime() / 1000000 - mStartTime;
+            if (casMap.containsKey(casId)) {
+              Object value = casMap.get(casId);
+              if (value != null && value instanceof Long) {
+                long start = ((Long) value).longValue();
+                System.out.println(ip + "\t" + start + "\t" + (current - start));
               }
+            }
           }
-            
-        }
-        else {
+
+        } else {
           System.out.print(".");
-            if (0 == (entityCount+1) % 50) {
-              System.out.print((entityCount+1) + " processed\n");
-            }
+          if (0 == (entityCount + 1) % 50) {
+            System.out.print((entityCount + 1) + " processed\n");
+          }
         }
       }
-      
-      //if output dir specified, dump CAS to XMI
+
+      // if output dir specified, dump CAS to XMI
       if (outputDir != null) {
         // try to retreive the filename of the input file from the CAS
         File outFile = null;
-        Type srcDocInfoType = aCas.getTypeSystem().getType("org.apache.uima.examples.SourceDocumentInformation");
+        Type srcDocInfoType = aCas.getTypeSystem().getType(
+                "org.apache.uima.examples.SourceDocumentInformation");
         if (srcDocInfoType != null) {
           FSIterator it = aCas.getIndexRepository().getAllIndexedFS(srcDocInfoType);
           if (it.hasNext()) {
@@ -448,7 +447,7 @@
               outFileName += ".xmi";
               outFile = new File(outputDir, outFileName);
             } catch (MalformedURLException e1) {
-            // invalid URI, use default processing below
+              // invalid URI, use default processing below
             }
           }
         }
@@ -459,8 +458,7 @@
           FileOutputStream outStream = new FileOutputStream(outFile);
           try {
             XmiCasSerializer.serialize(aCas, outStream);
-          }
-          finally {
+          } finally {
             outStream.close();
           }
         } catch (Exception e) {
@@ -468,18 +466,19 @@
           e.printStackTrace();
         }
       }
-      
-      //update stats
+
+      // update stats
       entityCount++;
       String docText = aCas.getDocumentText();
       if (docText != null) {
         size += docText.length();
-      }      
+      }
 
-    // Called just before sendCas with next CAS from collection reader
+      // Called just before sendCas with next CAS from collection reader
     }
+
     public void onBeforeMessageSend(UimaASProcessStatus status) {
-      long current = System.nanoTime()/1000000 - mStartTime;
+      long current = System.nanoTime() / 1000000 - mStartTime;
       casMap.put(status.getCasReferenceId(), current);
     }
 



Mime
View raw message