Commit in hps-java/src/main/java/org/lcsim/hps/monitoring on MAIN
DefaultEtEventProcessor.java+242added 1.1
EtEventProcessor.java+76added 1.1
MonitoringApplication.java+338-4631.26 -> 1.27
+656-463
2 added + 1 modified, total 3 files
refactored monitoring app to put event processing logic in separate class and interface

hps-java/src/main/java/org/lcsim/hps/monitoring
DefaultEtEventProcessor.java added at 1.1
diff -N DefaultEtEventProcessor.java
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ DefaultEtEventProcessor.java	29 Apr 2012 18:11:26 -0000	1.1
@@ -0,0 +1,242 @@
+package org.lcsim.hps.monitoring;
+
+import java.io.IOException;
+import java.nio.BufferUnderflowException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.jlab.coda.et.EtEvent;
+import org.jlab.coda.et.enums.Modify;
+import org.jlab.coda.et.exception.EtTimeoutException;
+import org.jlab.coda.jevio.EvioEvent;
+import org.jlab.coda.jevio.EvioException;
+import org.jlab.coda.jevio.EvioReader;
+import org.lcsim.event.EventHeader;
+import org.lcsim.hps.evio.LCSimEventBuilder;
+import org.lcsim.job.JobControlManager;
+
+/**
+ * This class executes the default event processing chain for HPS Test Run monitoring: ET -> EVIO -> LCIO.
+ * @author Jeremy McCormick <[log in to unmask]>
+ * @version $Id: DefaultEtEventProcessor.java,v 1.1 2012/04/29 18:11:26 jeremy Exp $
+ */
+public class DefaultEtEventProcessor implements EtEventProcessor
+{
+    int maxEvents;
+    int eventsProcessed;
+    int errorEvents;
+    LCSimEventBuilder eventBuilder;
+    JobControlManager jobManager;
+    EtConnection et;
+    List<EtEventListener> listeners = new ArrayList<EtEventListener>();
+    int status;
+    boolean stopProcessing;
+    boolean stopOnError;
+
+    DefaultEtEventProcessor(EtConnection et, LCSimEventBuilder eventBuilder, JobControlManager jobManager, int maxEvents, boolean stopOnError) {
+        this.et = et;
+        this.eventBuilder = eventBuilder;
+        this.jobManager = jobManager;
+        this.maxEvents = maxEvents;
+        this.stopOnError = stopOnError;
+    }
+    
+    public void addListener(EtEventListener callme) {
+        listeners.add(callme);
+    }
+    
+    public void setMaxEvents(int maxEvents) {
+        this.maxEvents = maxEvents;
+    }
+    
+    void begin() {
+        for (EtEventListener listener : listeners) {
+            listener.begin();
+        }
+    }
+    
+    void startOfEvent() {
+        for (EtEventListener listener : listeners) {
+            listener.startOfEvent();
+        }
+    }
+    
+    void endOfEvent() {
+        for (EtEventListener listener : listeners) {
+            listener.endOfEvent();
+        }
+    }
+    
+    void errorOnEvent() {
+        ++errorEvents;
+        for (EtEventListener listener : listeners) {
+            listener.errorOnEvent();
+        }
+    }
+    
+    void finish() {
+        for (EtEventListener listener : listeners) {
+            listener.finish();
+        }
+    }
+    
+    public void stop() {
+        this.stopProcessing = true;
+    }
+       
+    public int getNumberOfEventsProcessed() {
+        return eventsProcessed;
+    }
+    
+    public int getNumberOfErrors() {
+        return errorEvents;
+    }
+    
+    public int getMaxEvents() {
+        return maxEvents;
+    }
+    
+    public void resetNumberOfEventsProcessed() {
+        eventsProcessed = 0;
+    }
+    
+    public int getStatus() {
+        return status;
+    }
+
+    // Get EtEvents and process them.
+    // If in wait mode, continue after waitTime in microseconds if there are no events.
+    // If in async mode, expects non-empty event list immediately or an error occurs.
+    // If in sleep mode, the call to getEvents() will block, including requests to wake-up, until events arrive.
+    public void processEtEvents() throws EtTimeoutException, MaxEventsException, EventProcessingException, Exception {
+
+        // Get events from the ET system.
+        EtEvent[] mevs = et.sys.getEvents(et.att, et.param.waitMode, Modify.NOTHING, et.param.waitTime, et.param.chunk);
+
+        // Loop over retrieved EtEvents.
+        for (EtEvent mev : mevs) {
+            if (stopProcessing)
+                break;
+            processEtEvent(mev);
+        }
+    }
+
+    public void processEtEvent(EtEvent mev) throws EventProcessingException, MaxEventsException {
+        
+        // Check if max events was reached or exceeded.
+        if (maxEvents != -1 && eventsProcessed >= maxEvents) {
+            System.out.println("Reached max events " + eventsProcessed + " of " + maxEvents);
+            throw new MaxEventsException();
+        }
+
+        // Notify registered listeners of start of single event processing.
+        startOfEvent();
+
+        // Increment number of events processed.
+        ++eventsProcessed;
+
+        // Attempt to create an EVIO event from the data buffer in the EtEvent.
+        EvioEvent evioEvent = null;
+        do {
+            // Create EvioEvent from EtEvent.
+            try {
+                evioEvent = createEvioEvent(mev);
+            }
+            catch (Exception e) {
+                throw new EventProcessingException("Failed to create EVIO event.", e);
+            }
+
+            // For now, non-physics events are simply skipped.
+        } while (!eventBuilder.isPhysicsEvent(evioEvent));
+
+        // Create the LCSim event.
+        EventHeader lcsimEvent = null;
+        try {
+            lcsimEvent = eventBuilder.makeLCSimEvent(evioEvent);
+        } 
+        catch (Exception e) {
+            throw new EventProcessingException("Failed to create LCSim event.", e);
+        }
+
+        // Process the LCSim event.
+        try {
+            jobManager.processEvent(lcsimEvent);
+        }
+        catch (Exception e) {
+            throw new EventProcessingException("Error processing LCSim event.", e);
+        }
+
+        // Notify listeners of end of event.
+        endOfEvent();
+    }
+
+    /**
+     * Static utility method for creating an EVIO event from an EtEvent
+     * @param etEvent The EtEvent.
+     * @return The EvioEvent.
+     * @throws IOException
+     * @throws EvioException
+     * @throws BufferUnderflowException
+     */
+    private static final EvioEvent createEvioEvent(EtEvent etEvent) throws IOException, EvioException, BufferUnderflowException {
+        return (new EvioReader(etEvent.getDataBuffer())).parseNextEvent();
+    }
+    
+    /**
+     * Run the event processing from the ET connection.
+     */
+    public void process() {
+             
+        // Check if the ET connection is valid before starting.
+        if (!et.sys.alive()) {
+            throw new RuntimeException("ET system is not alive.");
+        }
+        
+        // Set status to connected.
+        this.status = ConnectionStatus.CONNECTED;
+        
+        // Clear any leftover stop request.
+        stopProcessing = false;
+        
+        // Notify listeners of job start.
+        begin();
+        
+        // Loop until Exception is thrown that stops event processing.
+        while (true) { 
+
+            // Got a request to stop processing.
+            if (stopProcessing) {
+                this.status = ConnectionStatus.DISCONNECT_REQUESTED;
+                break;
+            }
+            
+            // Try to process the next set of ET events.
+            try {
+                processEtEvents();
+            } 
+            // The session timed out.
+            catch (EtTimeoutException e) {
+                this.status = ConnectionStatus.TIMED_OUT; 
+            }
+            // Reached max number of events.
+            catch (MaxEventsException e) {
+                this.status = ConnectionStatus.DISCONNECTING; 
+            }
+            // There was some error processing events.
+            catch (Exception e) {
+                e.printStackTrace();
+                if (stopOnError) {
+                    this.status = ConnectionStatus.ERROR;
+                }
+            }
+            finally {
+                if (this.status != ConnectionStatus.CONNECTED) {
+                    break;
+                }
+            }
+        }
+        
+        // Notify listeners of job end.
+        finish();
+    }
+}

hps-java/src/main/java/org/lcsim/hps/monitoring
EtEventProcessor.java added at 1.1
diff -N EtEventProcessor.java
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ EtEventProcessor.java	29 Apr 2012 18:11:26 -0000	1.1
@@ -0,0 +1,76 @@
+package org.lcsim.hps.monitoring;
+
+import org.jlab.coda.et.EtEvent;
+import org.jlab.coda.et.exception.EtTimeoutException;
+
+interface EtEventProcessor
+{
+    // Process a single EtEvent.
+    void processEtEvent(EtEvent event) throws EventProcessingException, MaxEventsException;
+    
+    // Process the next array of EtEvents.  This method may block for a long time or forever.
+    // The default implementation calls processEtEvent() on each event, but this is not required.
+    void processEtEvents() throws EtTimeoutException, MaxEventsException, EventProcessingException, Exception;
+    
+    // Process all incoming EtEvents until ET system goes down or stop is requested.
+    void process();
+    
+    // Get the current status.
+    int getStatus();
+    
+    // Total number of events processed, including those with errors.
+    int getNumberOfEventsProcessed();
+    
+    // Max events to process.
+    int getMaxEvents();
+    
+    // Reset the number of events processed.
+    void resetNumberOfEventsProcessed();
+    
+    // Add a callback object that will receive notification of start, end, and error.
+    void addListener(EtEventListener callme);
+    
+    // Request that the processor stop processing events.
+    void stop();
+    
+    // Set maximum number of events to process.
+    void setMaxEvents(int maxEvents);
+   
+    // Interface for notification of start, end, and error during event processing.
+    // FIXME: Should the callback methods get an EtEvent or event number?
+    interface EtEventListener {
+        
+        // Called at beginning of event processing job.
+        void begin();
+        
+        // Called at start of processing one event.
+        void startOfEvent();
+        
+        // Called at end of processing one event.
+        void endOfEvent();
+        
+        // Called when an error occurs during single event processing.
+        void errorOnEvent();
+        
+        // Called at end of event processing job.
+        void finish();
+    }
+    
+    // Exception that is thrown when an error occurs during event processing.
+    static class EventProcessingException extends Exception {
+        EventProcessingException(Exception e) {
+            super(e);
+        }
+        
+        EventProcessingException(String m, Exception e) {
+            super(m, e);
+        }
+    }
+    
+    // Exception that is thrown when max number of events is reached or exceeded.
+    static final class MaxEventsException extends Exception {
+        MaxEventsException() {
+            super("Maximum number of events was reached.");
+        }
+    }
+}
\ No newline at end of file

hps-java/src/main/java/org/lcsim/hps/monitoring
MonitoringApplication.java 1.26 -> 1.27
diff -u -r1.26 -r1.27
--- MonitoringApplication.java	26 Apr 2012 21:16:50 -0000	1.26
+++ MonitoringApplication.java	29 Apr 2012 18:11:26 -0000	1.27
@@ -34,7 +34,6 @@
 import java.io.InputStream;
 import java.io.PrintStream;
 import java.net.InetAddress;
-import java.nio.ByteBuffer;
 
 import javax.imageio.ImageIO;
 import javax.swing.JFileChooser;
@@ -48,16 +47,6 @@
 import javax.swing.SwingUtilities;
 import javax.swing.Timer;
 
-import org.jlab.coda.et.EtAttachment;
-import org.jlab.coda.et.EtEvent;
-import org.jlab.coda.et.EtSystem;
-import org.jlab.coda.et.enums.Mode;
-import org.jlab.coda.et.enums.Modify;
-import org.jlab.coda.et.exception.EtTimeoutException;
-import org.jlab.coda.jevio.EvioEvent;
-import org.jlab.coda.jevio.EvioException;
-import org.jlab.coda.jevio.EvioReader;
-import org.lcsim.event.EventHeader;
 import org.lcsim.hps.evio.LCSimEventBuilder;
 import org.lcsim.hps.evio.LCSimTestRunEventBuilder;
 import org.lcsim.job.JobControlManager;
@@ -65,14 +54,12 @@
 import org.lcsim.util.aida.AIDA;
 
 /**
- * Implementation of a full monitoring application for HPS Test Run, which can
- * run LCSim steering files on data converted from the ET ring.  This class is
- * only currently accessible to users by calling its main() method.
+ * Monitoring application for HPS Test Run, which can run LCSim steering files 
+ * on data converted from the ET ring.  This class is accessible to users by 
+ * calling its main() method.
  * 
  * @author Jeremy McCormick <[log in to unmask]>
  */
-// TODO: Move the parts of this class having to do with processing Et/Evio/LCSim events to a separate class.
-// TODO: Move the Swing parts of this class to MonitoringGui class.
 public class MonitoringApplication {
     
     private JPanel mainPanel;
@@ -80,8 +67,7 @@
 	private ConnectionPanel connectionPanel;
 	private ConnectionStatusPanel connectionStatusPanel;
 	private EventPanel eventPanel;
-	private JobPanel jobPanel;		
-	
+	private JobPanel jobPanel;			
 	private JMenuBar menuBar;	
 	private JMenuItem connectItem;
 	private JMenuItem disconnectItem;
@@ -97,37 +83,233 @@
 	private JMenuItem terminalItem;
 	private JMenuItem screenshotItem;
 	private JMenuItem steeringItem;
-	private JMenuItem maxEventsItem;
-			
+	private JMenuItem maxEventsItem;		
 	private final PrintStream sysOut = System.out;
 	private final PrintStream sysErr = System.err;
-			
 	private ConnectionParameters connectionParameters;
 	private EtConnection connection;
-    private EtSystem sys;
-    private EtAttachment att;
-    private Mode waitMode;
-    private int waitTime;
-    private int chunk;    
-	private int connectionStatus = ConnectionStatus.DISCONNECTED;
-	
+	private int connectionStatus = ConnectionStatus.DISCONNECTED;	
 	private JobControlManager jobManager;
 	private LCSimEventBuilder eventBuilder;
-	
 	private MonitoringApplicationActionListener actionListener;
-	
 	private Timer timer;
-	
 	private long jobStartTime;
-	
-	// Number of events processed since reset.
-	private int eventsProcessed = 0;
-	
-	// Maximum number of events to process before disconnect; for unlimited -1 is used.	
-	private int maxEvents = -1;
-	
     private static final String screenshotFormat = "png";
-	
+    EtEventProcessor eventProcessor;
+    
+    MonitoringApplication() {
+        
+        // Create ActionEvent listener.
+        actionListener = new MonitoringApplicationActionListener(this);
+        
+        // Main panel for the application.
+        mainPanel = new JPanel();
+        mainPanel.setLayout(new GridBagLayout());
+        
+        // Setup the menus.
+        createMenu();
+        
+        // Main panel.
+        GridBagConstraints c = new GridBagConstraints();
+        c.gridx = 0;
+        c.gridy = 0;
+        c.anchor = GridBagConstraints.NORTHWEST;
+        connectionStatusPanel = new ConnectionStatusPanel();
+        mainPanel.add(connectionStatusPanel, c);
+    
+        // Sub-panels.
+        connectionPanel = new ConnectionPanel();
+        eventPanel = new EventPanel();
+        jobPanel = new JobPanel();
+    
+        // Tabs.
+        JPanel tabsPanel = new JPanel();
+        tabs = new JTabbedPane();
+        tabs.addTab("Connection", connectionPanel);
+        tabs.addTab("Event Monitor", eventPanel);
+        tabs.addTab("Job Settings", jobPanel);
+        tabsPanel.add(tabs);
+        
+        // Add tabs to main panel.
+        c = new GridBagConstraints();
+        c.gridx = 0;
+        c.gridy = 1;        
+        mainPanel.add(tabsPanel, c);
+    }
+    
+    private void createMenu() {
+        
+        menuBar = new JMenuBar();
+        
+        JMenu connectionMenu = new JMenu("Connection");
+        connectionMenu.setMnemonic(KeyEvent.VK_C);
+        menuBar.add(connectionMenu);        
+        
+        connectItem = new JMenuItem("Connect");
+        connectItem.setMnemonic(KeyEvent.VK_C);
+        connectItem.setActionCommand(connectCmd);
+        connectItem.addActionListener(actionListener);
+        connectionMenu.add(connectItem);
+        
+        disconnectItem = new JMenuItem("Disconnect");
+        disconnectItem.setMnemonic(KeyEvent.VK_D);
+        disconnectItem.setActionCommand(disconnectCmd);
+        disconnectItem.addActionListener(actionListener);
+        disconnectItem.setEnabled(false);
+        connectionMenu.add(disconnectItem);
+        
+        resetConnectionItem = new JMenuItem("Reset Connection Settings");
+        resetConnectionItem.setMnemonic(KeyEvent.VK_R);
+        resetConnectionItem.setActionCommand(resetConnectionSettingsCmd);
+        resetConnectionItem.addActionListener(actionListener);
+        connectionMenu.add(resetConnectionItem);
+                
+        connectionLoadItem = new JMenuItem("Load Connection...");
+        connectionLoadItem.setMnemonic(KeyEvent.VK_L);
+        connectionLoadItem.setActionCommand(loadConnectionCmd);
+        connectionLoadItem.addActionListener(actionListener);
+        connectionMenu.add(connectionLoadItem);
+        
+        connectionSaveItem = new JMenuItem("Save Connection...");
+        connectionSaveItem.setMnemonic(KeyEvent.VK_S);
+        connectionSaveItem.setActionCommand(saveConnectionCmd);
+        connectionSaveItem.addActionListener(actionListener);
+        connectionMenu.add(connectionSaveItem);
+        
+        exitItem = new JMenuItem("Exit");
+        exitItem.setMnemonic(KeyEvent.VK_X);
+        exitItem.setActionCommand(exitCmd);
+        exitItem.addActionListener(actionListener);
+        connectionMenu.add(exitItem);
+        
+        JMenu eventMenu = new JMenu("Event");
+        eventMenu.setMnemonic(KeyEvent.VK_E);
+        menuBar.add(eventMenu);
+        
+        resetEventsItem = new JMenuItem("Reset Event Monitor");
+        resetEventsItem.setMnemonic(KeyEvent.VK_E);
+        resetEventsItem.setActionCommand(resetEventsCmd);
+        resetEventsItem.addActionListener(actionListener);
+        eventMenu.add(resetEventsItem);     
+        
+        eventRefreshItem = new JMenuItem("Set Event Refresh...");
+        eventRefreshItem.setMnemonic(KeyEvent.VK_V);
+        eventRefreshItem.setActionCommand(eventRefreshCmd);
+        eventRefreshItem.addActionListener(actionListener);
+        eventMenu.add(eventRefreshItem);        
+        
+        maxEventsItem = new JMenuItem("Set Max Events...");
+        maxEventsItem.setMnemonic(KeyEvent.VK_M);
+        maxEventsItem.setActionCommand(setMaxEventsCmd);
+        maxEventsItem.addActionListener(actionListener);
+        eventMenu.add(maxEventsItem);
+        
+        JMenu jobMenu = new JMenu("Job");
+        jobMenu.setMnemonic(KeyEvent.VK_J);
+        menuBar.add(jobMenu);
+        
+        steeringItem = new JMenuItem("Set Steering File...");
+          steeringItem.setMnemonic(KeyEvent.VK_S);
+        steeringItem.setActionCommand(setSteeringFileCmd);
+        steeringItem.addActionListener(actionListener);
+        jobMenu.add(steeringItem);
+        
+        savePlotsItem = new JMenuItem("Save Plots to AIDA File...");
+        savePlotsItem.setMnemonic(KeyEvent.VK_P);
+        savePlotsItem.setActionCommand(savePlotsCmd);
+        savePlotsItem.addActionListener(actionListener);
+        savePlotsItem.setEnabled(false);
+        jobMenu.add(savePlotsItem);     
+        
+        resetDriversItem = new JMenuItem("Reset LCSim Drivers");
+        resetDriversItem.setMnemonic(KeyEvent.VK_D);
+        resetDriversItem.setActionCommand(resetDriversCmd);
+        resetDriversItem.addActionListener(actionListener);
+        resetDriversItem.setEnabled(false);
+        jobMenu.add(resetDriversItem);
+        
+        logItem = new JMenuItem("Log to File...");
+        logItem.setMnemonic(KeyEvent.VK_F);
+        logItem.setActionCommand(logCmd);
+        logItem.addActionListener(actionListener);
+        logItem.setEnabled(true);
+        jobMenu.add(logItem);
+        
+        terminalItem = new JMenuItem("Log to Terminal");
+        terminalItem.setMnemonic(KeyEvent.VK_T);
+        terminalItem.setActionCommand(terminalCmd);
+        terminalItem.addActionListener(actionListener);
+        terminalItem.setEnabled(false);
+        jobMenu.add(terminalItem);
+        
+        screenshotItem = new JMenuItem("Take a screenshot...");
+        screenshotItem.setMnemonic(KeyEvent.VK_N);
+        screenshotItem.setActionCommand(screenshotCmd);
+        screenshotItem.addActionListener(actionListener);
+        jobMenu.add(screenshotItem);
+    }
+    
+    private static final MonitoringApplication createMonitoringApplication() {
+        final MonitoringApplication app = new MonitoringApplication();
+        SwingUtilities.invokeLater(new Runnable() {
+            public void run() {
+                app.createApplicationFrame();
+            }
+        });
+        return app;
+    }
+    
+    /**
+     * Run the monitoring application.
+     * @param args The command line arguments.
+     */
+    public static void main(String[] args)
+    {   
+        final String defaultDetectorName;
+        final String defaultSteering;
+        final String defaultEventBuilder;
+        
+        if (args.length == 0) {
+            defaultDetectorName = "HPS-Test-JLAB-v4pt0";
+            defaultSteering = "/org/lcsim/hps/steering/TestRunMonitoring.lcsim";
+            defaultEventBuilder = LCSimTestRunEventBuilder.class.getCanonicalName();
+        }
+        else {
+            if (args.length != 3) {
+                System.out.println("Usage: MonitoringApplication [detectorName] [steeringFile] [eventBuilderClass]");
+                System.exit(1);
+            }
+            defaultDetectorName = args[0];
+            defaultSteering = args[1];
+            defaultEventBuilder = args[2];
+        }
+               
+        // Create the main app class.
+        MonitoringApplication app = MonitoringApplication.createMonitoringApplication();
+               
+        // Set job parameters.
+        app.setJobParameters(new JobParameters(new String[] {defaultDetectorName, defaultSteering, defaultEventBuilder}));
+        
+        // Run the app.
+        app.run();
+    }
+    
+    private void run() {
+        // GUI outer loop.  
+        while (true) {  
+            try {                
+                // Start job with current parameters.
+                runJob();
+            }
+            // Top-level exception catcher.
+            catch (Exception e) {
+                e.printStackTrace();
+                disconnect(ConnectionStatus.ERROR);
+                showDialog(e.getMessage());
+            }
+        }      
+    }
+    
 	private static final class JobParameters {
 		private String detectorName;
 		private String steeringResource;
@@ -143,7 +325,7 @@
 	}
 	
 	/**
-	 * This is the ActionListener implementation for the MonitoringApplication class.
+	 * The ActionListener implementation for the MonitoringApplication class.
 	 * @author Jeremy McCormick <[log in to unmask]>
 	 */
 	private static final class MonitoringApplicationActionListener implements ActionListener {
@@ -160,6 +342,7 @@
 	            app.requestConnection();
 	        } 
 	        else if (disconnectCmd.equals(cmd)) {
+	            app.eventProcessor.stop();
 	            app.disconnect(ConnectionStatus.DISCONNECTING);
 	        } 
 	        else if (eventRefreshCmd.equals(cmd)) {
@@ -207,163 +390,57 @@
 	    } 
 	}
 	
-	private static final class MaxEventsException extends Exception {
-	    MaxEventsException() {
-	        super("Maximum number of events was reached.");
-	    }
-	}
-	
-	MonitoringApplication() {
-		
-	    // Create ActionEvent listener.
-	    actionListener = new MonitoringApplicationActionListener(this);
-	    
-	    // Main panel for the application.
-		mainPanel = new JPanel();
-		mainPanel.setLayout(new GridBagLayout());
-		
-		// Setup the menus.
-		createMenu();
-		
-		// Main panel.
-		GridBagConstraints c = new GridBagConstraints();
-		c.gridx = 0;
-		c.gridy = 0;
-		c.anchor = GridBagConstraints.NORTHWEST;
-		connectionStatusPanel = new ConnectionStatusPanel();
-		mainPanel.add(connectionStatusPanel, c);
-	
-		// Sub-panels.
-		connectionPanel = new ConnectionPanel();
-		eventPanel = new EventPanel();
-		jobPanel = new JobPanel();
-	
-		// Tabs.
-		JPanel tabsPanel = new JPanel();
-	    tabs = new JTabbedPane();
-		tabs.addTab("Connection", connectionPanel);
-		tabs.addTab("Event Monitor", eventPanel);
-		tabs.addTab("Job Settings", jobPanel);
-		tabsPanel.add(tabs);
-		
-		// Add tabs to main panel.
-		c = new GridBagConstraints();
-		c.gridx = 0;
-		c.gridy = 1;		
-		mainPanel.add(tabsPanel, c);
-	}
-		
-	private void createMenu() {
-		
-		menuBar = new JMenuBar();
-		
-		JMenu connectionMenu = new JMenu("Connection");
-		connectionMenu.setMnemonic(KeyEvent.VK_C);
-		menuBar.add(connectionMenu);		
-		
-		connectItem = new JMenuItem("Connect");
-		connectItem.setMnemonic(KeyEvent.VK_C);
-		connectItem.setActionCommand(connectCmd);
-		connectItem.addActionListener(actionListener);
-		connectionMenu.add(connectItem);
-		
-		disconnectItem = new JMenuItem("Disconnect");
-		disconnectItem.setMnemonic(KeyEvent.VK_D);
-		disconnectItem.setActionCommand(disconnectCmd);
-		disconnectItem.addActionListener(actionListener);
-		disconnectItem.setEnabled(false);
-		connectionMenu.add(disconnectItem);
-		
-		resetConnectionItem = new JMenuItem("Reset Connection Settings");
-		resetConnectionItem.setMnemonic(KeyEvent.VK_R);
-		resetConnectionItem.setActionCommand(resetConnectionSettingsCmd);
-		resetConnectionItem.addActionListener(actionListener);
-		connectionMenu.add(resetConnectionItem);
-				
-		connectionLoadItem = new JMenuItem("Load Connection...");
-		connectionLoadItem.setMnemonic(KeyEvent.VK_L);
-		connectionLoadItem.setActionCommand(loadConnectionCmd);
-		connectionLoadItem.addActionListener(actionListener);
-		connectionMenu.add(connectionLoadItem);
-		
-		connectionSaveItem = new JMenuItem("Save Connection...");
-		connectionSaveItem.setMnemonic(KeyEvent.VK_S);
-		connectionSaveItem.setActionCommand(saveConnectionCmd);
-		connectionSaveItem.addActionListener(actionListener);
-		connectionMenu.add(connectionSaveItem);
-		
-		exitItem = new JMenuItem("Exit");
-		exitItem.setMnemonic(KeyEvent.VK_X);
-		exitItem.setActionCommand(exitCmd);
-		exitItem.addActionListener(actionListener);
-		connectionMenu.add(exitItem);
-		
-		JMenu eventMenu = new JMenu("Event");
-		eventMenu.setMnemonic(KeyEvent.VK_E);
-		menuBar.add(eventMenu);
-		
-		resetEventsItem = new JMenuItem("Reset Event Monitor");
-		resetEventsItem.setMnemonic(KeyEvent.VK_E);
-		resetEventsItem.setActionCommand(resetEventsCmd);
-		resetEventsItem.addActionListener(actionListener);
-		eventMenu.add(resetEventsItem);		
-		
-		eventRefreshItem = new JMenuItem("Set Event Refresh...");
-		eventRefreshItem.setMnemonic(KeyEvent.VK_V);
-		eventRefreshItem.setActionCommand(eventRefreshCmd);
-		eventRefreshItem.addActionListener(actionListener);
-		eventMenu.add(eventRefreshItem);		
-		
-		maxEventsItem = new JMenuItem("Set Max Events...");
-		maxEventsItem.setMnemonic(KeyEvent.VK_M);
-		maxEventsItem.setActionCommand(setMaxEventsCmd);
-		maxEventsItem.addActionListener(actionListener);
-		eventMenu.add(maxEventsItem);
-		
-		JMenu jobMenu = new JMenu("Job");
-		jobMenu.setMnemonic(KeyEvent.VK_J);
-		menuBar.add(jobMenu);
-		
-		steeringItem = new JMenuItem("Set Steering File...");
-	      steeringItem.setMnemonic(KeyEvent.VK_S);
-		steeringItem.setActionCommand(setSteeringFileCmd);
-		steeringItem.addActionListener(actionListener);
-		jobMenu.add(steeringItem);
-		
-		savePlotsItem = new JMenuItem("Save Plots to AIDA File...");
-		savePlotsItem.setMnemonic(KeyEvent.VK_P);
-		savePlotsItem.setActionCommand(savePlotsCmd);
-		savePlotsItem.addActionListener(actionListener);
-		savePlotsItem.setEnabled(false);
-		jobMenu.add(savePlotsItem);		
-		
-		resetDriversItem = new JMenuItem("Reset LCSim Drivers");
-		resetDriversItem.setMnemonic(KeyEvent.VK_D);
-		resetDriversItem.setActionCommand(resetDriversCmd);
-		resetDriversItem.addActionListener(actionListener);
-		resetDriversItem.setEnabled(false);
-		jobMenu.add(resetDriversItem);
-		
-		logItem = new JMenuItem("Log to File...");
-		logItem.setMnemonic(KeyEvent.VK_F);
-		logItem.setActionCommand(logCmd);
-		logItem.addActionListener(actionListener);
-		logItem.setEnabled(true);
-		jobMenu.add(logItem);
-		
-		terminalItem = new JMenuItem("Log to Terminal");
-		terminalItem.setMnemonic(KeyEvent.VK_T);
-		terminalItem.setActionCommand(terminalCmd);
-		terminalItem.addActionListener(actionListener);
-		terminalItem.setEnabled(false);
-		jobMenu.add(terminalItem);
-		
-		screenshotItem = new JMenuItem("Take a screenshot...");
-		screenshotItem.setMnemonic(KeyEvent.VK_N);
-		screenshotItem.setActionCommand(screenshotCmd);
-		screenshotItem.addActionListener(actionListener);
-		jobMenu.add(screenshotItem);
-	}
+    private static final class MonitoringApplicationEtListener implements EtEventProcessor.EtEventListener {
+
+        MonitoringApplication app;
+        
+        MonitoringApplicationEtListener(MonitoringApplication app) {
+            this.app = app;
+        }
+        
+        public void begin() {
+            // Reset event GUI.
+            app.eventPanel.reset();
+
+            // This is only reset between different jobs.
+            app.eventPanel.resetSessionSupplied();
+
+            // Start the job timer.
+            app.startTimer();
+        }
+        
+        public void startOfEvent() {
+            app.eventPanel.updateEventCount();
+        }
+
+        public void endOfEvent() {
+            app.eventPanel.updateAverageEventRate(app.jobStartTime);
+        }
+
+        public void errorOnEvent() {
+            app.eventPanel.updateBadEventCount();
+        }
+
+        public void finish() {
+            try {
+                // Call cleanup methods of Drivers.
+                if (app.jobManager != null)
+                    app.jobManager.finish();
+                
+                // Stop the job timer.
+                app.timer.stop();
+                app.timer = null;
+                
+                // Push final event counts to GUI.
+                app.eventPanel.endJob();
+            }
+            catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+    }
+    
+
 	
 	private void setJobParameters(JobParameters p) {		
     	jobPanel.setDetectorName(p.detectorName);
@@ -452,14 +529,13 @@
 	
 	private static String getUserName() {
 	    if (System.getProperty("user.name") == null) {
-	        return "NO_ONE";
+	        return "UNKNOWN_USER";
 	    } 
 	    else {
 	        return System.getProperty("user.name");
 	    }
 	}
 
-    // FIXME: Put this in JobManager???
 	private synchronized void resetDrivers() {
 		if (jobManager != null) {
 			for (Driver driver : jobManager.getDriverExecList()) {
@@ -532,8 +608,10 @@
                 showDialog("Max Events is set to unlimited.");
                 newMaxEvents = -1;
             }
+            // Set max events in panel.
             eventPanel.setMaxEvents(newMaxEvents);
-            maxEvents = newMaxEvents;
+            // Set max events in event processor.
+            eventProcessor.setMaxEvents(newMaxEvents);
         }
         catch (Exception e) {
             showDialog("The value " + inputValue + " is not valid for Max Events.");
@@ -622,86 +700,79 @@
 		return jobPanel.getSteeringType();
 	}
 	
-    // Wait for connection request from GUI.
 	private void waitForConnectionRequest() {
         while (!connectionRequested()) {
             try { Thread.sleep(1000); } catch (InterruptedException e)  {};
         }        
 	}
 	
-	// Job is everything that happens from waiting for and getting a connect (or cancel/error) to disconnect.
-	private void startJob() {
+	private int getMaxEvents() {
+	    return eventPanel.getMaxEvents();
+	}
+	
+	/**
+	 * Run a job, which is everything that happens from waiting for and getting a connect request to disconnecting
+	 * after event processing is done.
+	 */
+	private void runJob() {
 
-        // Wait until connection is requested.
+        // Wait until connection is requested by the GUI.
         waitForConnectionRequest();
 	    
-	    // Connect to LCSim and ET system.
+        // Setup LCSim.
+        setupLCSim();
+        
+	    // Connect to the ET system.
 	    connect();
 	    
-	    // Reset event GUI.
-	    eventPanel.reset();
+	    // Create the event processing thread.
+	    Thread t = createEventProcessorThread();
 	    
-	    // This is only reset between different jobs (disconnects).
-        eventPanel.resetSessionSupplied();
+	    // Start up the event processing thread.
+        t.start();
         
-        // Start the job timer.
-        startTimer();
-
-	    // Start the event processing loop.
-	    int status = eventLoop();
-	    
-	    // If event loop finishes, then disconnect.
-	    disconnect(status);
-	}
+        // Wait for event processing to finish.
+        try {
+            t.join();
+        }
+        catch (InterruptedException e) {}
+          
+        // Disconnect with the status which was set by the event processor.
+        disconnect(eventProcessor.getStatus());
+	}
+
+    private Thread createEventProcessorThread()
+    {
+        eventProcessor = new DefaultEtEventProcessor(
+                this.connection, 
+                this.eventBuilder, 
+                this.jobManager, 
+                getMaxEvents(), 
+                disconnectOnError());
+        eventProcessor.addListener(new MonitoringApplicationEtListener(this));
+        Runnable run = new Runnable() {
+            public void run() {
+                eventProcessor.process();
+            }
+        };
+        return new Thread(run, "EtEvent Processing Thread");
+    }
 	
+    /**
+     * Connect to the ET system specified in the GUI's connection panel settings.
+     */
 	private void connect() {
 	    
 	    // Make sure applicable menu items are enabled or disabled.
         setConnectedGuiState();
 
-        // Setup LCSim.
-        setupLCSim();
-
         // Create a connection to the ET server.
         createEtConnection();
         
-        // If this method completes should be connected to valid Et/LCSim session.
+        // Set status to connected.
         connectionStatusPanel.setStatus(ConnectionStatus.CONNECTED);
 	}
-	
-	private void stopJob() {        
-	    // Call cleanup methods of Drivers.
-	    if (jobManager != null)
-            jobManager.finish();
-	    
-	    // Stop the job timer.
-        timer.stop();
-        timer = null;
-        
-        // Reset number of events processed.
-        eventsProcessed = 0;
-        
-        // Push final event counts to GUI.
-        eventPanel.endJob();
-	}
-	
-	private void startEvent() {
-		eventPanel.updateEventCount();
-	}
-	
-	private void endEvent() {
-
-		// Update the average event rate.
-		eventPanel.updateAverageEventRate(jobStartTime);
 		
-		// Increment number of events processed.
-		++eventsProcessed;		
-	}
-	
-	private void badEvent() {
-		eventPanel.updateBadEventCount();
-	}
-	
 	private boolean validSteering() {
 		return jobPanel.validSteering();
 	}
@@ -726,9 +797,6 @@
 	    return jobPanel.disconnectOnErrorCheckBox.isSelected();
 	}
 
-	/*
-	 *  Disconnect from an ET session.
-	 */
 	synchronized private void disconnect(int status) {
 	    	   
 	    // Show a warning dialog box before disconnecting, if this option is selected.
@@ -736,26 +804,18 @@
 	        showDialog("You are about to be disconnected.");
 	    }
 	    
-	    // Set the application status from caller.
+	    // Set the application status from the caller while disconnecting.
 	    setConnectionStatus(status);
 	    
-        // Stop the LCSim job.
-	    try {
-	        stopJob();
-	    } catch (Exception e) {
-	        e.printStackTrace();
-	    }
-	    
 	    // Disconnect from the ET system.
 	    if (connection != null) {
 	        
-	        // Disconnect from ET system.
-	        connection.cleanup();
+	        // Disconnect from the ET system.
+	        // FIXME: This can block forever!
+	        connection.cleanup(); 
 	        
-	        // These are now unusable.
+	        // The connection is now unusable.
 	        connection = null;
-	        sys = null;
-	        att = null;
 	    }
 	    
 	    // Update state of GUI to disconnected.
@@ -767,11 +827,11 @@
 	
 	private void setupLCSim() {
 
-	    // Steering file looks valid?
+	    // Check if the LCSim steering file looks valid.
 	    if (!validSteering())
 	            throw new RuntimeException("Invalid steering file or resource.");
 
-	    // Get steering resource or file as a String.
+	    // Get steering resource or file as a String parameter.
 	    String steering = getSteering();
 	    
 	    // Try to setup LCSim based on type.  
@@ -787,7 +847,7 @@
 	            jobManager.setup(new File(steering));
 	        } 
 	            	                        
-	        // Reset reference to event builder.
+	        // Reset the reference to the event builder.
 	        createEventBuilder();
 	            
 	    } catch (Exception e) {
@@ -806,158 +866,11 @@
 	    } catch (Exception e) {         
 	        throw new RuntimeException("Failed to create LCSimEventBuilder class.", e);
 	    }           
-	    if (eventBuilder == null)
-	        throw new RuntimeException("LCSimEventBuilder points to null");
 	        
 	    // Set the detector name on the event builder so it can find conditions data.
 	    eventBuilder.setDetectorName(getDetectorName());
 	}       
-
-	private void processEtEvent(EtEvent mev) throws Exception {
-        try {            
-            
-            // Check if max events was reached or exceeded.
-            if (maxEvents != -1 && eventsProcessed >= maxEvents) {
-                //System.out.println("eventsProcessed=" + eventsProcessed);
-                //System.out.println("maxEvents=" + maxEvents);
-                throw new MaxEventsException();
-            }
-            
-            // Start of event GUI hook.
-            startEvent();
-		EvioEvent evioEvent = null;
-		EventHeader lcsimEvent = null;
-		do {
-			// Create EvioEvent from EtEvent and skip if failed.
-			evioEvent = createEvioEvent(mev);
-
-			// Throw an error if EVIO event is null.
-			if (evioEvent == null) {
-				throw new RuntimeException("Failed to create EVIO event.");
-			}
-		} while (!eventBuilder.isPhysicsEvent(evioEvent));
-
-		// Create the LCSim event.
-		lcsimEvent = eventBuilder.makeLCSimEvent(evioEvent);
-       
-            // Throw an error if LCSim event is null.             
-            if (lcsimEvent == null) 
-                throw new RuntimeException("Failed to create LCSim event.");     
-            
-            // Process the LCSim event.
-            jobManager.processEvent(lcsimEvent);
-            
-            // End of event GUI hook.
-            endEvent();            
-        }
-        // Hit max events.
-        catch (MaxEventsException e) {
-            throw e;
-        }
-        // Catch other event processing exceptions.
-        catch (Exception e) {
-            
-            // Print a stack trace.
-            e.printStackTrace();
-            
-            // Bad event GUI hook.
-            badEvent();
-            
-            // If user wants to disconnect on error, then throw the exception to caller.
-            if (disconnectOnError()) {
-                throw new RuntimeException(e);
-            }
-        }
-	}
-	
-	private EvioEvent createEvioEvent(EtEvent etEvent) throws IOException, EvioException {
-	    ByteBuffer buf = etEvent.getDataBuffer();
-	    EvioReader reader = new EvioReader(buf);
-	    EvioEvent evioEvent = null;
-	    try {
-	        evioEvent = reader.parseNextEvent();
-	    } catch (java.nio.BufferUnderflowException e) {
-	        e.printStackTrace();
-	    }
-	    return evioEvent;
-	}
-	
-    private static final MonitoringApplication createMonitoringApplication() {
-        final MonitoringApplication app = new MonitoringApplication();
-        SwingUtilities.invokeLater(new Runnable() {
-            public void run() {
-                app.createApplicationFrame();
-            }
-        });
-        return app;
-    }
-    
-    /**
-     * Run the monitoring application.
-     * @param args The command line arguments.
-     */
-    public static void main(String[] args)
-    {   
-        final String defaultDetectorName;
-        final String defaultSteering;
-        final String defaultEventBuilder;
-        
-        if (args.length == 0) {
-            defaultDetectorName = "HPS-Test-JLAB-v4pt0";
-            defaultSteering = "/org/lcsim/hps/steering/TestRunMonitoring.lcsim";
-            defaultEventBuilder = LCSimTestRunEventBuilder.class.getCanonicalName();
-        }
-        else {
-            if (args.length != 3) {
-                System.out.println("Usage: MonitoringApplication [detectorName] [steeringFile] [eventBuilderClass]");
-                System.exit(1);
-            }
-            defaultDetectorName = args[0];
-            defaultSteering = args[1];
-            defaultEventBuilder = args[2];
-        }
-               
-        // Create the main app class.
-        MonitoringApplication app = MonitoringApplication.createMonitoringApplication();
-               
-        // Set job parameters.
-        app.setJobParameters(new JobParameters(new String[] {defaultDetectorName, defaultSteering, defaultEventBuilder}));
-        
-        // Run the app.
-        app.run();
-    }
-    
-    private void run() {
-        // GUI outer loop.  
-        while (true) {  
-            try {                
-                // Start job with current parameters.
-                startJob();
-            }
-            // Top-level exception catcher.
-            catch (Exception e) {
-                disconnect(ConnectionStatus.ERROR);
-                showDialog(e.getMessage());
-            }
-        }      
-    }
     
-    private void processEtEvents() throws Exception {
-        
-        // Get EtEvents.
-        // If in wait mode, continue after waitTime in microseconds if there are no events.
-        // If in async mode, expects non-empty event list or an error occurs.
-        // If in sleep mode, this call will pretty much block everything, including requests to wake-up, until events arrive.
-        EtEvent[] mevs = sys.getEvents(att, waitMode, Modify.NOTHING, waitTime, chunk);
-
-        // Loop over retrieved EtEvents.
-        for (EtEvent mev : mevs) {
-            
-            // Process one EtEvent.
-            processEtEvent(mev);
-        }
-    }
-
     private void createEtConnection() {
 
         // Cache connection parameters.
@@ -966,16 +879,6 @@
         // Setup connection to ET system.
         connection = EtConnection.createEtConnection(connectionParameters);
         if (connection != null) {
-            
-            // Cache the ET objects.
-            sys = connection.getEtSystem();
-            att = connection.getEtAttachment();
-            
-            // Cache these too as they are needed for every EtSystem.getEvents() call.
-            chunk = connectionParameters.chunk;
-            waitMode = connectionParameters.waitMode;
-            waitTime = connectionParameters.waitTime;
-            
             // Set status to connected as there is now a live ET connection.
             setConnectionStatus(ConnectionStatus.CONNECTED);
         } 
@@ -986,42 +889,12 @@
         }
     }
     
-    // Run the event loop and return the connection status for disconnect.
-    private int eventLoop() {
-        while (true) { 
-            
-            // User wants to disconnect or ET connection went down.
-            if (getConnectionStatus() != ConnectionStatus.CONNECTED) { 
-                return getConnectionStatus();
-            }
-
-            // Try to process the next set of ET events.
-            try {
-                processEtEvents();
-            } 
-            // The session timed out.
-            catch (EtTimeoutException e) {
-                return ConnectionStatus.TIMED_OUT;
-            }
-            // Reached max number of events.
-            catch (MaxEventsException e) {
-                showDialog(e.getMessage());
-                return ConnectionStatus.DISCONNECTING;
-            }
-            // There was some error processing events.
-            catch (Exception e) {
-                e.printStackTrace();
-                return ConnectionStatus.ERROR;
-            }
-        }
-    }
-    
     private void startTimer() {
         timer = new Timer(1000, actionListener);
         timer.setActionCommand(udpateTimeCmd);
         jobStartTime = System.currentTimeMillis();
         timer.start();
-    }   
+    }
     
     private void updateTime() {
         final long elapsedTime = (System.currentTimeMillis() - jobStartTime)/1000;
@@ -1029,11 +902,13 @@
     }
     
     private void resetJob() {
+        // Reset GUI.
         jobStartTime = System.currentTimeMillis();
-        eventsProcessed = 0;
         eventPanel.reset();
         if (getConnectionStatus() == ConnectionStatus.DISCONNECTED) {
[truncated at 1000 lines; 7 more skipped]
CVSspam 0.2.12


Use REPLY-ALL to reply to list

To unsubscribe from the LCD-CVS list, click the following link:
https://listserv.slac.stanford.edu/cgi-bin/wa?SUBED1=LCD-CVS&A=1