source: tmcsimulator/trunk/src/tmcsim/client/ATMSBatchDriver.java @ 129

Revision 129, 16.0 KB checked in by jdalbey, 9 years ago (diff)

ATMSBatchDriver.java Updated to add an incident field to each event and create a map of incidents to list of events. This should enable implementing the feature that allows operator to clear all events for an incident.

Line 
1package tmcsim.client;
2
3import atmsdriver.ATMSDriver;
4import atmsdriver.ConsoleDriver;
5import atmsdriver.ExchangeInfo;
6import atmsdriver.model.Highways;
7import atmsdriver.model.Station;
8import java.awt.event.ActionEvent;
9import java.awt.event.ActionListener;
10import java.io.FileInputStream;
11import java.io.FileNotFoundException;
12import java.rmi.Naming;
13import java.rmi.RemoteException;
14import java.rmi.server.UnicastRemoteObject;
15import java.text.ParseException;
16import java.text.SimpleDateFormat;
17import java.util.ArrayList;
18import java.util.Date;
19import java.util.HashMap;
20import java.util.InputMismatchException;
21import java.util.LinkedList;
22import java.util.List;
23import java.util.Map;
24import java.util.Properties;
25import java.util.Queue;
26import java.util.Scanner;
27import java.util.concurrent.TimeUnit;
28import java.util.logging.Level;
29import java.util.logging.Logger;
30import javax.swing.JOptionPane;
31import javax.swing.JWindow;
32import javax.swing.Timer;
33import javax.swing.UIManager;
34import tmcsim.common.SimulationException;
35import tmcsim.interfaces.CADClientInterface;
36import tmcsim.interfaces.CoordinatorInterface;
37
38/**
39 * Skeleton for ATMS Driver that reads a "batch" file of highway
40 * status update commands.
41 * It operates as a client of the
42 * CAD server, using RMI to poll the server every second for the current
43 * simulation clock time.  It uses the simulation clock time
44 * to fire update commands at the desired time.
45 * Note: Sim Mgr must be running before starting this application.
46 * TODO: We probably want to be able to "override" a command, to force
47 * clearing an incident.
48
49 * @author jdalbey
50 */
51public class ATMSBatchDriver extends UnicastRemoteObject implements
52        CADClientInterface
53{
54    private static final String CONFIG_FILE_NAME = "cad_client_config.properties";
55    private final static int ONE_SECOND = 1000;
56    private static final int FEPSIM_INTERVAL = 30000;
57    private final static SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
58    /**
59     * Error logger.
60     */
61    private static Logger cadClientLogger = Logger.getLogger("tmcsim.client");
62
63    @Override
64    public void refresh() throws RemoteException
65    {
66        System.out.println("ATMSBatchDriver.refresh() was invoked.");
67    }
68
69    /**
70     * Enumeration containing properties name values. See CADClient class
71     * description for more information.
72     *
73     * @author Matthew Cechini
74     * @see CADClient
75     */
76    private static enum PROPERTIES
77    {
78        CAD_SIM_HOST("CADSimulatorHost"), CAD_SIM_PORT("CADSimulatorSocketPort"), CAD_RMI_PORT(
79        "CADRmiPort"), CLIENT_CAD_POS("CADPosition"), CLIENT_USER_ID(
80        "CADUserID"), KEYBOARD_TYPE("KeyboardType"), DISPLAY_TYPE(
81        "DisplayType");
82        public String name;
83
84        private PROPERTIES(String n)
85        {
86            name = n;
87        }
88    }
89    /**
90     * CADClientSocket Object to handle socket communication between the Client
91     * and CAD Simulator.
92     */
93    private CADClientSocket theClientSocket;
94
95    /**
96     * Properties object for the CADClient class.
97     */
98    private Properties cadClientProp;
99    /**
100     * RMI interface for communication with the remote Coordinator.
101     */
102    private static CoordinatorInterface theCoorInt;
103    /**
104     * reference to itself to be used for disconnecting from CADSimulator
105     */
106    private CADClientInterface client = this;
107
108    /**
109     * Highways in traffic network
110     */
111    final private Highways highways;
112   
113    /**
114     * Queue of batch events
115     */
116    private Queue<String> eventQueue;
117    /**
118     * Map of incidents to events
119     */
120    private Map<String, List<String>> incidents;
121   
122    /** Instance of ConsoleDriver that contains the highway model */
123    private ConsoleDriver console;
124   
125    /** GUI for this driver */
126    private ATMSBatchViewer theView;
127   
128    /**
129     * Constructor. Initialize data from parsed properties file. Create a socket
130     * connection to the CADSimulator.
131     *
132     * @param propertiesFile File path (absolute or relative) to the properties
133     * file containing configuration data.
134     */
135    public ATMSBatchDriver(String propertiesFile) throws SimulationException,
136            RemoteException
137    {
138        if (!verifyProperties(propertiesFile))
139        {
140            System.exit(0);
141        }
142        incidents = new HashMap<String, List<String>> ();
143        highways = new Highways(
144        "config/vds_data/lds.txt",
145        "config/vds_data/loop.txt",
146        "config/vds_data/highwaysMeta.txt",
147        "localhost", 8080);
148        // Create console driver but don't start run() method
149        console = new ConsoleDriver(highways);
150       
151        connect(cadClientProp.getProperty(PROPERTIES.CAD_SIM_HOST.name).trim(),
152                cadClientProp.getProperty(PROPERTIES.CAD_RMI_PORT.name).trim());
153
154        // READ THE BATCH FILE OF COMMANDS and put in a queue
155        readBatchFile();
156        // Launch the display
157        theView = new ATMSBatchViewer();
158        theView.setVisible(true);
159        theView.update("0:00", eventQueue);       
160        // Create a timer that fetches the simulation time every second.
161        Timer timer = new Timer(ONE_SECOND, new ActionListener()
162        {
163            // Every second, see if an event should be launched
164            public void actionPerformed(ActionEvent e)
165            {
166                String currentClock = "";
167                Date simClock = new Date();               
168                // Obtain the simulation time from the CAD server
169                try
170                {
171                    long simtime = theCoorInt.getCurrentSimulationTime();
172                    currentClock = formatInterval(simtime);
173                    try {
174                        simClock = formatter.parse(currentClock);
175                    } catch (ParseException ex) {
176                        Logger.getLogger(ATMSBatchDriver.class.getName()).log(Level.SEVERE, null, ex);
177                        System.out.println("Invalid simulation clock time found in ATMSDriverClient");
178                        System.exit(-1);
179                    }                   
180                    //System.out.println("Current clock: " + currentClock);
181                } catch (RemoteException ex)
182                {
183                    Logger.getLogger(ATMSBatchDriver.class.getName()).log(Level.SEVERE, null, ex);
184                }
185                // If we have any events left to process
186                if (!eventQueue.isEmpty())
187                {
188                    // Get the time to launch the next event
189                    String nextEvent = eventQueue.peek();
190//                    String eventTimeField = nextEvent.substring(0,8);
191                    Scanner evtScan = new Scanner(nextEvent);
192                    String inci = evtScan.next();     
193                    String eventTimeField = evtScan.next();
194                    Date eventTime = new Date();
195                    try {
196                        eventTime = formatter.parse(eventTimeField);
197                    } catch (ParseException ex) {
198                        Logger.getLogger(ATMSBatchDriver.class.getName()).log(Level.WARNING, null, ex);
199                        System.out.println("Unable to parse event time: " + nextEvent + " skipping.");
200                        eventQueue.remove();
201                    }
202                    //System.out.println("Next event will be launched at: " + formatter.format(eventTime));
203                    theView.update(currentClock, eventQueue);
204                    // Check the queue of events to see if the first
205                    // item should be launched.  IF so,
206                    // issue that command and remove it from queue.
207                    if (eventTime.before(simClock) || eventTime.equals(simClock))
208                    {
209                        System.out.println("LAUNCHING EVENT at " + nextEvent );
210                        // Extract fields from event and prepare them
211                        Scanner lineScan = new Scanner(nextEvent);
212                        try
213                        {
214                        lineScan.next(); // skip incident number field
215                        lineScan.next(); // skip time field
216                        int routeNumber = lineScan.nextInt();
217                        Station.DIRECTION dir = Station.DIRECTION.toDirection(lineScan.next());
218                        double postmile = lineScan.nextDouble();
219                        int range = lineScan.nextInt();
220                        ConsoleDriver.DOTCOLOR dotcolor = ConsoleDriver.DOTCOLOR.toDotColor(lineScan.next());
221                        // apply colorization to highways
222                        console.applyColorToHighwayStretch(routeNumber, dir, postmile, range, dotcolor);
223                        // Remove this event from the queue, we're done with it.
224                        eventQueue.remove();
225                        }
226                        catch (InputMismatchException ex)
227                        {
228                            System.out.println("Wrong format data in batch event file: " + nextEvent + " \nskipping.");
229                            eventQueue.remove();
230                        }
231                    }
232                }
233            }
234        });
235        timer.start();
236
237        // Start the FEP thread (to update ATMS every 30 sec). (See class def below)
238        new WriteToFEPThread().run();
239
240        ensureProperShutdown();
241    }
242
243    private void readBatchFile()
244    {
245        FileInputStream fis;
246        try {
247            fis = new FileInputStream("config/vds_data/atmsBatchEvents.txt");
248            eventQueue = new LinkedList<String>();
249            // Read all lines from the file of events
250            Scanner scan = new Scanner(fis);
251            while (scan.hasNext())
252            {
253                // Read a line and add it to the event queue
254                String line = scan.nextLine();
255                eventQueue.add(line);
256                // Parse the incident from the line
257                Scanner lineScan = new Scanner(line);
258                String incident = lineScan.next();
259                // Add the line to the list for the corresponding incident
260                List evtList;
261                if (incidents.containsKey(incident))
262                {
263                    evtList = incidents.get(incident);
264                }
265                else
266                {
267                    evtList = new ArrayList<String>();
268                }               
269                evtList.add(line);
270                // and put it back in the map
271                incidents.put(incident, evtList);
272            }
273        } catch (FileNotFoundException ex) {
274            Logger.getLogger(ATMSBatchDriver.class.getName()).log(Level.SEVERE, null, ex);
275        }
276        System.out.println("Events file read, " + eventQueue.size() + " events queued.");
277    }
278   
279    /**
280     * Connect to the Coordinator's RMI object, and register this object for
281     * callback with the Coordinator.
282     *
283     * @param hostname Host name of the CAD Simulator.
284     * @param portNumber Port number of the CAD Simulator RMI communication.
285     * @throws SimulationException if there is an error creating the RMI
286     * connection.
287     */
288    protected void connect(String hostname, String portNumber)
289            throws SimulationException
290    {
291
292        String coorIntURL = "";
293
294        try
295        {
296            coorIntURL = "rmi://" + hostname + ":" + portNumber
297                    + "/coordinator";
298            theCoorInt = (CoordinatorInterface) Naming.lookup(coorIntURL);
299            theCoorInt.registerForCallback(this);
300        } catch (Exception e)
301        {
302            throw new SimulationException(SimulationException.CAD_SIM_CONNECT,
303                    e);
304        }
305    }
306
307    /**
308     * This method verifies that the CAD Simulator Host and Port values are not
309     * null. Also, if a CAD Position or User ID do not exist in the properties
310     * file, the user is prompted to enter values. These values are written to
311     * the properties file. If the user cancels the process of entering these
312     * values, the verification fails.
313     *
314     * @param propertiesFile File path (absolute or relative) to the properties
315     * file containing configuration data.
316     * @return True if the properties file is valid, false if not.
317     * @throws SimulationException if there is an exception in verifying the
318     * properties file, or if the user cancels input.
319     */
320    private boolean verifyProperties(String propertiesFile)
321            throws SimulationException
322    {
323
324        // Load the properties file.
325        try
326        {
327            cadClientProp = new Properties();
328            cadClientProp.load(new FileInputStream(propertiesFile));
329        } catch (Exception e)
330        {
331            cadClientLogger.logp(Level.SEVERE, "SimulationManager",
332                    "Constructor", "Exception in reading properties file.", e);
333
334            throw new SimulationException(SimulationException.INITIALIZE_ERROR,
335                    e);
336        }
337
338
339        // Ensure that the properties file does not have null values for the
340        // CAD Simulator's connection information.
341        if (cadClientProp.getProperty(PROPERTIES.CAD_SIM_HOST.name) == null
342                || cadClientProp.getProperty(PROPERTIES.CAD_SIM_PORT.name) == null)
343        {
344            cadClientLogger.logp(Level.SEVERE, "SimulationManager",
345                    "Constructor", "Null value in properties file.");
346            throw new SimulationException(SimulationException.INITIALIZE_ERROR);
347        }
348
349        return true;
350    }
351
352    /**
353     * Format a time in seconds as HH:MM:SS
354     *
355     * @param l
356     * @return
357     */
358    private String formatInterval(final long l)
359    {
360        final long hr = TimeUnit.SECONDS.toHours(l);
361        final long min = TimeUnit.SECONDS.toMinutes(l - TimeUnit.HOURS.toSeconds(hr));
362        final long sec = TimeUnit.SECONDS.toSeconds(l - TimeUnit.HOURS.toSeconds(hr) - TimeUnit.MINUTES.toSeconds(min));
363        return String.format("%02d:%02d:%02d", hr, min, sec);
364    }
365
366    public void ensureProperShutdown()
367    {
368        Runtime.getRuntime().addShutdownHook(new Thread()
369        {
370            public void run()
371            {
372                try
373                {
374                    theCoorInt.unregisterForCallback(client);
375                } catch (RemoteException e)
376                {
377                    e.printStackTrace();
378                }
379            }
380        });
381    }
382
383    /**
384     * Construct the CADClient with the properties file path, either from the
385     * command line arguments or default.
386     *
387     * @param args Command line arguments.
388     */
389    public static void main(String[] args)
390    {
391        if (System.getProperty("CONFIG_DIR") == null)
392        {
393            System.setProperty("CONFIG_DIR", "config");
394        }
395
396        try
397        {
398            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
399            new ATMSBatchDriver(System.getProperty("CONFIG_DIR") + System.getProperty("file.separator") + CONFIG_FILE_NAME);
400
401        } catch (Exception e)
402        {
403            cadClientLogger.logp(Level.SEVERE, "SimulationManager", "Main",
404                    "Error initializing application.");
405
406            JOptionPane.showMessageDialog(new JWindow(), e.getMessage(),
407                    "Error - Program Exiting", JOptionPane.ERROR_MESSAGE);
408
409            System.exit(-1);
410        }
411
412    }
413
414    class WriteToFEPThread extends Thread
415    {
416
417        public void run()
418        {
419            System.out.println("WriteToFEP Thread starting.");
420            // Run indefinitely
421            while (true)
422            {
423                try {
424                    // Write the highway network status to the FEP Simulator
425                    highways.writeToFEP();
426                } catch (SimulationException ex) 
427                {
428                    System.out.println("Skipping writeToFEP...");
429                }
430
431                // Wait for FEP Sim to process the data we just sent
432                try
433                {
434                    Thread.sleep(FEPSIM_INTERVAL);
435                }
436                catch (InterruptedException ie)
437                {
438                    ie.printStackTrace();
439                }
440            }
441
442        }
443    }
444}
Note: See TracBrowser for help on using the repository browser.