LISTSERV mailing list manager LISTSERV 16.5

Help for HPS-SVN Archives


HPS-SVN Archives

HPS-SVN Archives


HPS-SVN@LISTSERV.SLAC.STANFORD.EDU


View:

Message:

[

First

|

Previous

|

Next

|

Last

]

By Topic:

[

First

|

Previous

|

Next

|

Last

]

By Author:

[

First

|

Previous

|

Next

|

Last

]

Font:

Proportional Font

LISTSERV Archives

LISTSERV Archives

HPS-SVN Home

HPS-SVN Home

HPS-SVN  March 2015

HPS-SVN March 2015

Subject:

r2456 - in /java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application: ./ util/

From:

[log in to unmask]

Reply-To:

Notification of commits to the hps svn repository <[log in to unmask]>

Date:

Sat, 14 Mar 2015 23:45:57 -0000

Content-Type:

text/plain

Parts/Attachments:

Parts/Attachments

text/plain (808 lines)

Author: [log in to unmask]
Date: Sat Mar 14 16:45:51 2015
New Revision: 2456

Log:
Miscellaneous changes and updates to monitoring dev branch.

Modified:
    java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/ConditionsCollectionTableModel.java
    java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/EventProcessing.java
    java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/MonitoringApplication.java
    java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/MonitoringApplicationFrame.java
    java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/util/PreStartEtStation.java
    java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/util/RunnableEtStation.java

Modified: java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/ConditionsCollectionTableModel.java
 =============================================================================
--- java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/ConditionsCollectionTableModel.java	(original)
+++ java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/ConditionsCollectionTableModel.java	Sat Mar 14 16:45:51 2015
@@ -1,7 +1,6 @@
 package org.hps.monitoring.application;
 
-import javax.swing.table.AbstractTableModel;
-import javax.swing.table.TableRowSorter;
+import javax.swing.table.DefaultTableModel;
 
 import org.hps.conditions.api.ConditionsObject;
 import org.hps.conditions.api.ConditionsObjectCollection;
@@ -9,11 +8,11 @@
 import org.hps.conditions.database.TableMetaData;
 
 /**
- * 
+ * This is a table model for a collection of conditions objects.
  * @author Jeremy McCormick <[log in to unmask]>
  *
  */
-class ConditionsCollectionTableModel extends AbstractTableModel {
+class ConditionsCollectionTableModel extends DefaultTableModel {
 
     ConditionsObjectCollection<?> collection;
     int columnCount;
@@ -22,25 +21,6 @@
     Class<?>[] columnTypes;
     DatabaseConditionsManager manager;
     
-    /*
-    static class ConditionsCollectionTableRowSorter extends TableRowSorter<ConditionsCollectionTableModel> {
-        
-        ConditionsCollectionTableModel model;
-        
-        ConditionsCollectionTableRowSorter(ConditionsCollectionTableModel model) {
-            this.model = model;
-        }
-        
-        protected boolean useToString(int column) {
-            if (model.getColumnClass(column).equals(String.class)) {
-                return true;
-            } else {
-                return false;
-            }
-        }       
-     }
-     */
-
     ConditionsCollectionTableModel(DatabaseConditionsManager manager, ConditionsObjectCollection<?> collection) {
         
         // Set collection data.
@@ -69,9 +49,7 @@
             String fieldName = tableInfo.getFieldNames()[i];
             columnNames[i + 1] = fieldName;
             columnTypes[i + 1] = tableInfo.getFieldType(fieldName);
-            System.out.println("column " + (i + 1) + " = " + tableInfo.getFieldNames()[i] + " with type " + columnTypes[i + 1]);
         }
-        System.out.println("column count set to " + columnCount);        
     }
 
     @Override

Modified: java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/EventProcessing.java
 =============================================================================
--- java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/EventProcessing.java	(original)
+++ java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/EventProcessing.java	Sat Mar 14 16:45:51 2015
@@ -4,6 +4,7 @@
 import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
+import java.util.ArrayList;
 import java.util.List;
 import java.util.logging.Logger;
 
@@ -16,6 +17,7 @@
 import org.hps.monitoring.application.util.EtSystemUtil;
 import org.hps.monitoring.application.util.PhysicsSyncEventStation;
 import org.hps.monitoring.application.util.PreStartEtStation;
+import org.hps.monitoring.application.util.RunnableEtStation;
 import org.hps.monitoring.subsys.et.EtSystemMonitor;
 import org.hps.monitoring.subsys.et.EtSystemStripCharts;
 import org.hps.record.LCSimEventBuilder;
@@ -59,8 +61,8 @@
         CompositeLoop loop;
         EventProcessingThread processingThread;
         Thread sessionWatchdogThread;
-        Thread configThread;
-        Thread preStartThread;
+        ThreadGroup stationThreadGroup = new ThreadGroup("Station Threads");
+        List<RunnableEtStation> stations = new ArrayList<RunnableEtStation>();
         EtConnection connection;
     }
 
@@ -212,7 +214,6 @@
         if (configurationModel.hasValidProperty(ConfigurationModel.MAX_EVENTS_PROPERTY)) {
             long maxEvents = configurationModel.getMaxEvents();
             if (maxEvents > 0L) {
-                // logger.config("processing will stop after max events: " + maxEvents);
                 loopConfig.setMaxRecords(maxEvents);
             }
         }
@@ -247,11 +248,9 @@
             logger.config("added extra Driver " + driver.getName() + " to job");
         }
 
-        // Enable conditions system activation from EVIO event data if using an EVIO file source.
-        if (configurationModel.getDataSourceType().equals(DataSourceType.EVIO_FILE)) {            
-            logger.config("added EvioDetectorConditionsProcessor to job with detector " + configurationModel.getDetectorName());
-            loopConfig.add(new EvioDetectorConditionsProcessor(configurationModel.getDetectorName()));
-        }
+        // Enable conditions system activation from EVIO event data in case the PRESTART is missed.
+        logger.config("added EvioDetectorConditionsProcessor to job with detector " + configurationModel.getDetectorName());
+        loopConfig.add(new EvioDetectorConditionsProcessor(configurationModel.getDetectorName()));
 
         // Create the CompositeLoop with the configuration.
         sessionState.loop = new CompositeLoop(loopConfig);
@@ -281,31 +280,21 @@
     synchronized void stop() {
 
         // Kill session watchdog thread.
-        logger.fine("killing watchdog thread ...");
         killWatchdogThread();
-        logger.fine("watchdog thread killed");
-
-        // Wake up ET system in case it is blocked in a getEvents() call.
-        if (sessionState.connection != null) {
-            try {
-                logger.fine("waking up ET stations ...");
-                sessionState.connection.getEtSystem().wakeUpAll(sessionState.connection.getEtStation());
-                logger.fine("ET stations woken up");
-            } catch (IOException | EtException | EtClosedException e) {
-                e.printStackTrace();
-            }
-        }
-
-        // Stop event processing.
-        logger.fine("commanding event processing to stop ...");
+
+        // Wake up all ET stations to unblock the system and make sure secondary stations are detached.
+        wakeUpEtStations();
+        
+        // Stop the event processing now that ET system is unblocked.
+        logger.fine("sending STOP command to loop ...");
         sessionState.loop.execute(Command.STOP);
-        logger.fine("event processing commanded to stop");
-
-        // Cleanup the event processing thread.
+        logger.fine("loop got command STOP");
+
+        // Cleanup the event processing thread since it was told to stop now.
         try {
-            logger.fine("joining on event processing thread ...");
+            logger.fine("waiting for event processing thread to end ...");
             sessionState.processingThread.join();
-            logger.fine("event processing thread joined");
+            logger.fine("event processing thread ended");
 
             // Invalidate event processing thread.
             sessionState.processingThread = null;
@@ -319,13 +308,65 @@
             application.errorHandler.setError(sessionState.loop.getLastError()).log();
         }
 
-        // Invalidate loop.
+        // Invalidate the loop.
         sessionState.loop = null;
 
         // Disconnect from the ET system.
-        logger.fine("disconnecting from ET system ...");
         disconnect();
-        logger.fine("ET system disconnected");
+        
+        // Invalidate the event processing object so it is unusable now.
+        invalidate();
+    }
+
+    /**
+     * Wake up all ET stations associated with event processing.
+     */
+    private void wakeUpEtStations() {
+        if (sessionState.connection != null) {
+            logger.fine("waking up ET stations ...");
+
+            // Wake up secondary ET stations.
+            for (RunnableEtStation station : sessionState.stations) {
+                if (station.getEtStation().isUsable()) {
+                    // Wake up the station which will automatically trigger a detach.
+                    try {
+                        logger.finest("waking up " + station.getEtStation().getName() + " ...");
+                        sessionState.connection.getEtSystem().wakeUpAll(station.getEtStation());
+                        logger.finest(station.getEtStation().getName() + " woken up");
+                    } catch (IOException | EtException | EtClosedException e) {
+                        e.printStackTrace();
+                    }
+                }
+            }
+
+            // Wait for station threads to die after being woken up.
+            while (sessionState.stationThreadGroup.activeCount() != 0) {
+                logger.finest("waiting for station threads to die ...");
+                Object lock = new Object();
+                synchronized (lock) {
+                    try {
+                        lock.wait(500);
+                    } catch (InterruptedException e) {
+                        e.printStackTrace();
+                    }
+                }
+            }
+
+            logger.finest("destroying station thread group");
+            sessionState.stationThreadGroup.destroy();
+            logger.finest("station thread group destroyed");
+
+            // Wake up the primary ET station doing the event processing.
+            logger.finest("waking up event processing station ...");
+            try {
+                sessionState.connection.getEtSystem().wakeUpAll(sessionState.connection.getEtStation());
+                logger.finest("event processing station woken up");
+            } catch (IOException | EtException | EtClosedException e) {
+                e.printStackTrace();
+            }
+
+            logger.finest("ET stations woken up");
+        }
     }
 
     /**
@@ -388,9 +429,9 @@
      * Interrupt and join to the processing watchdog thread.
      */
     synchronized void killWatchdogThread() {
-        logger.fine("killing watchdog thread");
         // Is the session watchdog thread not null?
         if (sessionState.sessionWatchdogThread != null) {
+            logger.finest("killing watchdog thread ...");
             // Is the thread still alive?
             if (sessionState.sessionWatchdogThread.isAlive()) {
                 // Interrupt the thread which should cause it to stop.
@@ -405,8 +446,8 @@
             }
             // Set the thread object to null.
             sessionState.sessionWatchdogThread = null;
-        }
-        logger.fine("watchdog thread killed");
+            logger.finest("watchdog thread killed");
+        }
     }
 
     /**
@@ -416,9 +457,9 @@
         if (sessionState.connection != null) {
             logger.fine("closing ET connection");
             if (sessionState.connection.getEtSystem().alive()) {
-                logger.fine("cleaning up the connection ...");
+                logger.finest("cleaning up the connection ...");
                 sessionState.connection.cleanup();
-                logger.fine("connection cleanup successful");
+                logger.finest("connection cleanup successful");
             }
             sessionState.connection = null;
             logger.fine("ET connection closed");
@@ -480,7 +521,6 @@
         if (sessionState.connection != null) {
             // Set status to connected as there is now a live ET connection.
             application.connectionModel.setConnectionStatus(ConnectionStatus.CONNECTED);
-            // logger.info("successfully connected to ET system");
         } else {
             application.errorHandler.setError(new RuntimeException("Failed to create ET connection.")).log().printStackTrace().raiseException();
         }
@@ -493,10 +533,10 @@
         logger.fine("creating physics SYNC station ...");       
         PhysicsSyncEventStation configStation = new PhysicsSyncEventStation(
                 this.sessionState.connection.getEtSystem(),
-                this.sessionState.connection.getEtStation().getName() + "_PhysicsSyncStation",
+                this.sessionState.connection.getEtStation().getName() + "_PhysicsSync",
                 getNextStationPosition());
-        sessionState.configThread = new Thread(configStation);
-        sessionState.configThread.start();
+        sessionState.stations.add(configStation);
+        new Thread(sessionState.stationThreadGroup, configStation).start();
         logger.fine("physics SYNC station created");
     }
     
@@ -507,16 +547,15 @@
         logger.fine("creating PRESTART station ...");
         String detectorName = this.application.configurationModel.getDetectorName();
         EtSystem system = this.sessionState.connection.getEtSystem();
-        String stationName = this.sessionState.connection.getEtStation().getName() + "_GoStation";
+        String stationName = this.sessionState.connection.getEtStation().getName() + "_PreStart";
         int order = getNextStationPosition();
         PreStartEtStation preStartStation = new PreStartEtStation(
                 detectorName, 
                 system, 
                 stationName, 
                 order);
-
-        sessionState.preStartThread = new Thread(preStartStation);
-        sessionState.preStartThread.start();
+        sessionState.stations.add(preStartStation);
+        new Thread(sessionState.stationThreadGroup, preStartStation).start();
         logger.fine("PRESTART station created");
     }
 
@@ -525,28 +564,12 @@
      * @param status The connection status.
      */
     synchronized void disconnect() {
-
-        logger.fine("disconnecting ET system ...");
-        
-        if (sessionState.configThread != null) {
-            if (sessionState.configThread.isAlive()) {
-                sessionState.configThread.interrupt();
-            }
-        }
-        
-        if (sessionState.preStartThread != null) {
-            if (sessionState.preStartThread.isAlive()) {
-                sessionState.preStartThread.interrupt();
-            }
-        }
-        
+                
         // Cleanup the ET connection.
         closeEtConnection();
 
         // Change application state to disconnected.
         application.connectionModel.setConnectionStatus(ConnectionStatus.DISCONNECTED);
-
-        logger.fine("ET system disconnected successfully");
     }
 
     /**
@@ -568,14 +591,33 @@
 
                 // Activate a disconnect using the ActionEvent which is used by the disconnect
                 // button.
-                logger.fine("processing thread ended so automatic disconnect is happening");
+                logger.finest("processing thread ended so automatic disconnect is happening");
                 application.actionPerformed(new ActionEvent(Thread.currentThread(), 0, Commands.DISCONNECT));
 
             } catch (InterruptedException e) {
-                logger.fine("SessionWatchdogThread got interrupted");
+                logger.finest("SessionWatchdogThread got interrupted");
                 // This happens when the thread is interrupted by the user pressing the disconnect
                 // button.
             }
         }
     }
+    
+    void invalidate() {
+
+        this.application = null;
+        this.conditionsListeners = null;
+        this.drivers = null;
+        this.logger = null;
+        this.processors = null;        
+
+        this.sessionState.jobManager = null;
+        this.sessionState.eventBuilder = null;
+        this.sessionState.loop = null;
+        this.sessionState.processingThread = null;
+        this.sessionState.sessionWatchdogThread = null;
+        this.sessionState.stationThreadGroup = null;
+        this.sessionState.stations = null;
+        this.sessionState.connection = null;
+        this.sessionState = null;
+    }
 }

Modified: java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/MonitoringApplication.java
 =============================================================================
--- java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/MonitoringApplication.java	(original)
+++ java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/MonitoringApplication.java	Sat Mar 14 16:45:51 2015
@@ -7,6 +7,8 @@
 
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
+import java.awt.event.WindowEvent;
+import java.awt.event.WindowListener;
 import java.awt.image.BufferedImage;
 import java.beans.PropertyChangeEvent;
 import java.beans.PropertyChangeListener;
@@ -32,6 +34,7 @@
 import javax.swing.filechooser.FileFilter;
 import javax.swing.filechooser.FileNameExtensionFilter;
 
+import org.hps.conditions.database.DatabaseConditionsManager;
 import org.hps.monitoring.application.DataSourceComboBox.DataSourceItem;
 import org.hps.monitoring.application.LogTable.LogRecordModel;
 import org.hps.monitoring.application.model.Configuration;
@@ -47,7 +50,6 @@
 import org.hps.monitoring.plotting.MonitoringAnalysisFactory;
 import org.hps.monitoring.plotting.MonitoringPlotFactory;
 import org.hps.monitoring.subsys.SystemStatus;
-import org.hps.monitoring.subsys.SystemStatusListener;
 import org.hps.monitoring.subsys.SystemStatusRegistry;
 import org.hps.record.composite.CompositeRecordProcessor;
 import org.hps.record.enums.DataSourceType;
@@ -75,6 +77,7 @@
 
     // Default log stream.
     MonitoringApplicationStreamHandler streamHandler;
+    LogHandler logHandler;
     PrintStream sysOut = System.out;
     PrintStream sysErr = System.err;
     
@@ -147,7 +150,7 @@
             super.setOutputStream(out);
         }        
     }
-             
+                 
     /**
      * Instantiate and show the monitoring application with the given configuration.
      * @param configuration The Configuration object containing application settings.
@@ -158,6 +161,39 @@
         
             // Setup the main GUI component.
             frame = new MonitoringApplicationFrame(this);
+            
+            // Add window listener to perform clean shutdown.
+            frame.addWindowListener(new WindowListener() {
+
+                @Override
+                public void windowOpened(WindowEvent e) {
+                }
+
+                @Override
+                public void windowClosing(WindowEvent e) {
+                }
+
+                @Override
+                public void windowClosed(WindowEvent e) {
+                    exit();
+                }
+
+                @Override
+                public void windowIconified(WindowEvent e) {
+                }
+
+                @Override
+                public void windowDeiconified(WindowEvent e) {
+                }
+
+                @Override
+                public void windowActivated(WindowEvent e) {
+                }
+
+                @Override
+                public void windowDeactivated(WindowEvent e) {
+                }
+            });
         
             // Setup the error handler.
             errorHandler = new ErrorHandler(frame, logger);
@@ -188,11 +224,12 @@
             logger.info("application initialized successfully");
         
         } catch (Exception e) {
+            // Don't use the ErrorHandler here because we don't know that it initialized successfully.
             System.err.println("MonitoringApplication failed to initialize without errors!");
             DialogUtil.showErrorDialog(null, "Error Starting Monitoring Application", "Monitoring application failed to initialize.");
             e.printStackTrace();
             System.exit(1);
-        }
+        }        
     }
     
     /**
@@ -200,7 +237,8 @@
      */
     void setupLogger() {
         logger.setUseParentHandlers(false);        
-        logger.addHandler(new LogHandler());
+        logHandler = new LogHandler();
+        logger.addHandler(logHandler);
         streamHandler = new MonitoringApplicationStreamHandler(System.out);
         logger.addHandler(streamHandler);
         for (Handler handler : logger.getHandlers()) {
@@ -210,6 +248,12 @@
         logger.info("logging initialized");
     }
     
+    void flushLogger() {
+        for (Handler handler : logger.getHandlers()) {
+            handler.flush();
+        }
+    }
+    
     /**
      * Static utility method for creating new instance.
      * @param configuration The application settings.
@@ -240,15 +284,12 @@
         if (Commands.CONNECT.equals(command)) {
             startSession();
         } else if (Commands.DISCONNECT.equals(command)) {
-            // TODO: Start this on new thread.
-            //processing.stop();
-            System.out.println("MonitoringApplication.actionPerformed - running disconnect thread ...");
             runDisconnectThread();
-            System.out.println("MonitoringApplication.actionPerformed - disconnect thread is done!");
         } else if (Commands.SAVE_PLOTS.equals(command)) {
             savePlots();
         } else if (Commands.EXIT.equals(command)) {
-            exit();
+            // This will trigger the window closing action that cleans everything up.
+            frame.dispose();
         } else if (Commands.PAUSE.equals(command)) { 
             processing.pause();
         } else if (Commands.NEXT.equals(command)) {
@@ -415,7 +456,7 @@
             // Setup the system status monitor table.
             setupSystemStatusMonitor();
                                             
-            // Start the event processing thread.
+            // Start the event processing thread.            
             processing.start();            
             
             logger.info("new session successfully initialized");
@@ -434,17 +475,17 @@
     }
            
     /**
-     * Exit from the application.
+     * Exit from the application from exit menu item or hitting close window button.
      */
     void exit() {        
         if (connectionModel.isConnected()) {
             processing.stop();
         }
+        logHandler.setLevel(Level.OFF);
         logger.info("exiting the application");
-        logger.getHandlers()[0].flush();
-        frame.setVisible(false);
+        streamHandler.flush();
         System.exit(0);
-    }              
+    }
             
     /**
      * Save AIDA plots to a file using a file chooser.
@@ -801,7 +842,7 @@
                 logger.fine("disconnect thread is running ...");
                 connectionModel.setConnectionStatus(ConnectionStatus.DISCONNECTING);
                 MonitoringApplication.this.processing.stop();
-                logger.fine("disconnect thread finished");
+                logger.fine("disconnect thread finished!");
             }
         }.run();
     }

Modified: java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/MonitoringApplicationFrame.java
 =============================================================================
--- java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/MonitoringApplicationFrame.java	(original)
+++ java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/MonitoringApplicationFrame.java	Sat Mar 14 16:45:51 2015
@@ -5,6 +5,8 @@
 import java.awt.FlowLayout;
 import java.awt.GraphicsEnvironment;
 import java.awt.Rectangle;
+import java.awt.event.WindowEvent;
+import java.awt.event.WindowListener;
 
 import javax.swing.JFrame;
 import javax.swing.JPanel;
@@ -149,8 +151,8 @@
         dataSourceComboBox.addActionListener(menu);
         
         // Setup the settings dialog box (invisible until activated).
-        settingsDialog = new SettingsDialog(application.configurationModel, application);
-        
+        settingsDialog = new SettingsDialog(application.configurationModel, application);        
+               
         // Setup the frame now that all components have been added.        
         pack();
         setExtendedState(JFrame.MAXIMIZED_BOTH);

Modified: java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/util/PreStartEtStation.java
 =============================================================================
--- java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/util/PreStartEtStation.java	(original)
+++ java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/util/PreStartEtStation.java	Sat Mar 14 16:45:51 2015
@@ -11,6 +11,9 @@
 import org.jlab.coda.jevio.EvioReader;
 
 /**
+ * This is an ET station that will initialize the conditions system
+ * from EVIO PRESTART events.
+ * 
  * @author Jeremy McCormick <[log in to unmask]>
  */
 public class PreStartEtStation extends RunnableEtStation {

Modified: java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/util/RunnableEtStation.java
 =============================================================================
--- java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/util/RunnableEtStation.java	(original)
+++ java/branches/monitoring-app-dev/src/main/java/org/hps/monitoring/application/util/RunnableEtStation.java	Sat Mar 14 16:45:51 2015
@@ -15,9 +15,13 @@
 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.EtBusyException;
 import org.jlab.coda.et.exception.EtClosedException;
 import org.jlab.coda.et.exception.EtDeadException;
+import org.jlab.coda.et.exception.EtEmptyException;
 import org.jlab.coda.et.exception.EtException;
+import org.jlab.coda.et.exception.EtTimeoutException;
+import org.jlab.coda.et.exception.EtWakeUpException;
 
 /**
  * This is an implementation of Runnable that wraps an ET station.
@@ -26,12 +30,22 @@
  */
 public abstract class RunnableEtStation implements Runnable {
     
+    // ET system objects.
     protected EtStation station;
     protected EtAttachment attachment;
-    protected boolean disconnect = false;    
+
+    // Config for this object.
     protected RunnableEtStationConfiguration config;
+    
+    // An event filter which by default will accept all EvioEvents.
     protected EventTagFilter filter = new AcceptAllFilter();
     
+    // Sub-classes should set this if the station needs to disconnect during the run method.
+    protected volatile boolean disconnect = false;    
+    
+    /**
+     * Configuration parameters for setting up an object of this class.
+     */
     public static final class RunnableEtStationConfiguration {
         
         public EtSystem system;
@@ -60,6 +74,10 @@
     protected RunnableEtStation() {
     }
 
+    /**
+     * Create the runnable ET station with the given config.
+     * @param config The configuration parameters.
+     */
     public RunnableEtStation(RunnableEtStationConfiguration config) {
         if (config == null) {
             throw new IllegalArgumentException("config is null");
@@ -67,7 +85,19 @@
         config.validate();
         this.config = config;
     }
-
+    
+    /**
+     * Process a single ET event.  
+     * Sub-classes must implement this method.
+     * @param event The EtEvent to process.
+     */
+    public abstract void processEvent(EtEvent event); 
+
+    /**
+     * Run this station by reading ET events and processing them.
+     * Disconnection (detachment of the station) will occur automatically 
+     * at the end of this method.
+     */
     public void run() {
         
         setup();
@@ -75,36 +105,56 @@
         try {
             for (;;) {
                 // Get the next array of events from the server.
-                EtEvent[] events = config.system.getEvents(
-                        attachment, Mode.SLEEP, Modify.NOTHING, 0, config.readEvents);
-                
-                // Process the events.
-                for (EtEvent event : events) {
-                    // Process an event if it passes the filter (by default accepts all).
-                    if (filter.accept(event.getControl()[0])) {
-                        processEvent(event);
+                EtEvent[] events;
+                
+                try {
+                    events = config.system.getEvents(attachment, Mode.SLEEP, Modify.NOTHING, 0, config.readEvents);
+                } catch (EtWakeUpException e) {
+                    System.out.println("ET station " + this.config.name + " was woken up and will disconnect");
+                    break;
+                } catch (EtException | EtDeadException | 
+                        EtClosedException | EtEmptyException | 
+                        EtBusyException | EtTimeoutException | 
+                        IOException e) {
+                    System.err.println("ET station " + this.config.name + " failed to read events ...");
+                    e.printStackTrace();
+                    break;
+                }
+                
+                try {
+                    // Process the events.
+                    for (EtEvent event : events) {
+                        // Process an event if it passes the filter (by default accepts all).
+                        if (filter.accept(event.getControl()[0])) {
+                            processEvent(event);
+                        }
                     }
-                }
-                
-                // Disconnect if flag is set (by sub-class changing disconnect value).
+                } catch (Exception e) {
+                    System.err.println("ET station " + this.config.name + " had event processing error ...");
+                    e.printStackTrace();
+                    continue;
+                }
+                
+                // Disconnect if flag is set (by sub-class in its processEvent method).
                 if (disconnect) {
                     break;
                 }
-            }
-        } catch (Exception e) {
-            System.err.println("Error running " + this.config.name + " ...");
-            e.printStackTrace();
+                
+                // Disconnect if interrupted.
+                if (Thread.currentThread().isInterrupted()) {
+                    break;
+                }
+            }             
         } finally {
-            if (config.system.alive()) {
-                System.out.println(this.config.name + " is disconnecting ...");
+            if (config.system.alive()) {               
                 disconnect();
-                System.out.println("disconnected " + this.config.name);
-            }
-        }
-    }
-
-    public abstract void processEvent(EtEvent event); 
-        
+            } 
+        }       
+    }
+       
+    /**
+     * Setup the ET station.
+     */
     protected void setup() {
         try {
             // Create the basic station config.
@@ -122,22 +172,22 @@
             }
 
             // Create station and attach to the ET system.
-            EtStation station = config.system.createStation(stationConfig, config.name, config.order);
+            station = config.system.createStation(stationConfig, config.name, config.order);
             attachment = config.system.attach(station);
 
         } catch (Exception e) {
-            System.err.println("Error while running setup of " + config.name + " ...");
-            e.printStackTrace();
-            // Any errors during setup are rethrown.
+            // Any errors during setup are re-thrown.
             throw new RuntimeException(e);
         }
     }
 
-    public synchronized void disconnect() {
+    /**
+     * Detach the station if the ET system is still alive.
+     */
+    synchronized void disconnect() {
         if (config.system.alive()) {
             if (attachment.isUsable()) {
                 try {
-                    config.system.wakeUpAll(station);
                     config.system.detach(attachment);
                 } catch (IOException | EtException | EtClosedException | EtDeadException e) {
                     e.printStackTrace();
@@ -145,4 +195,12 @@
             }
         }
     }
+    
+    /**
+     * Get the ET station.
+     * @return The ET station.
+     */
+    public EtStation getEtStation() {
+        return this.station;
+    }
 }

Top of Message | Previous Page | Permalink

Advanced Options


Options

Log In

Log In

Get Password

Get Password


Search Archives

Search Archives


Subscribe or Unsubscribe

Subscribe or Unsubscribe


Archives

November 2017
August 2017
July 2017
January 2017
December 2016
November 2016
October 2016
September 2016
August 2016
July 2016
June 2016
May 2016
April 2016
March 2016
February 2016
January 2016
December 2015
November 2015
October 2015
September 2015
August 2015
July 2015
June 2015
May 2015
April 2015
March 2015
February 2015
January 2015
December 2014
November 2014
October 2014
September 2014
August 2014
July 2014
June 2014
May 2014
April 2014
March 2014
February 2014
January 2014
December 2013
November 2013

ATOM RSS1 RSS2



LISTSERV.SLAC.STANFORD.EDU

Secured by F-Secure Anti-Virus CataList Email List Search Powered by the LISTSERV Email List Manager

Privacy Notice, Security Notice and Terms of Use