source: tmcsimulator/trunk/src/tmcsim/cadsimulator/CADServer.java @ 448

Revision 448, 16.9 KB checked in by jdalbey, 7 years ago (diff)

Add CADcomments.log filename to CADserver config properties so Coordinator know where to write comments log.

Line 
1package tmcsim.cadsimulator;
2
3import java.io.File;
4import java.io.FileInputStream;
5import java.rmi.Naming;
6import java.rmi.RemoteException;
7import java.rmi.registry.LocateRegistry;
8import java.util.Calendar;
9import java.util.Properties;
10import java.util.logging.Level;
11import java.util.logging.Logger;
12import javax.swing.JOptionPane;
13import javax.swing.JWindow;
14import javax.swing.UIManager;
15import javax.xml.parsers.DocumentBuilderFactory;
16import tmcsim.cadsimulator.db.CMSDiversionDB;
17import tmcsim.cadsimulator.managers.ATMSManager;
18import tmcsim.cadsimulator.managers.IncidentManager;
19import tmcsim.cadsimulator.managers.MediaManager;
20import tmcsim.cadsimulator.managers.ParamicsSimulationManager;
21import tmcsim.cadsimulator.managers.SimulationClockManager;
22import tmcsim.cadsimulator.managers.TrafficModelManager;
23import tmcsim.cadsimulator.viewer.model.CADSimulatorState;
24import tmcsim.common.SimulationException;
25import tmcsim.interfaces.CADViewer;
26
27/**
28 * CADSimulator is main class for the CAD Simulator application. At construction
29 * the Coordinator, CoordinatorViewer, and all CAD Simulator Managers are
30 * initialized and data relationships are established. Simulation control is
31 * managed through the Coordinator and Managers. The CADSimulator contains the
32 * instances of all Manager Objects that are used to control the Simulation flow
33 * of data.<br>
34 * <br>
35 *
36 * The CADSimulator is initialized with a properties file containing the
37 * following data items:<br>
38 * <code>
39 * -----------------------------------------------------------------------------<br>
40 * CADClientPort The port number to use for remote CAD Client connections.<br>
41 * CoordinatorRMIPort The port number to use for binding the Coordinator.<br>
42 * CMSDiversionXML The filepath for the xml file containing initialization data
43 * for the Diversion "database." AudioFileLocation The root directory path where
44 * audio files are referenced from.<br>
45 * ParamicsProperties The filepath for the properties file to initialize the
46 * ParamicsControlManager.<br>
47 * ATMSProperties The filepath for the properties file to initialize the
48 * ATMSManager.<br>
49 * MediaProperties The filepath for the properties file to initialize the
50 * MediaManager.<br>
51 * ErrorFile The filename of the error file used for logging errors.<br>
52 * ----------------------------------------------------------------------------<br>
53 * Example File:<br>
54 * CADClientPort = 4444<br>
55 * CoordinatorRMIPort = 4445<br>
56 * CMSDiversionXML = ../data/cmsdiversions.xml<br>
57 * AudioFileLocation = ../audio/<br>
58 * ParamicsProperties = ../config/paramics.properties<br>
59 * ATMSProperties = ../config/atms.properties<br>
60 * MediaProperties = ../config/media.properties<br>
61 * ErrorFile = cad_sim_error.xml<br>
62 * </code>
63 *
64 * @author Matthew Cechini (mcechini@calpoly.edu) jdalbey
65 * @version $Date: 2009/04/17 16:27:46 $ $Revision: 1.5 $
66 */
67public class CADServer
68{
69
70    private static String CONFIG_FILE_NAME = "cad_simulator_config.properties";
71    /**
72     * Error logger.
73     */
74    private static Logger cadSimLogger = Logger.getLogger("tmcsim.cadsimulator");
75
76    /**
77     * Enumeration containing properties name values. See CADSimulator class
78     * description for more information.
79     *
80     * @author Matthew
81     * @see CADServer
82     */
83    private static enum CAD_PROPERTIES
84    {
85
86        /**
87         * RMI port to accept CAD Client connections.
88         */
89        CLIENT_PORT("CADClientPort"),
90        /**
91         * RMI port to bind the Coordinator to for RMI communication.
92         */
93        COOR_RMI_PORT("CoordinatorRMIPort"),
94        CAD_RMI_PORT("CADRmiPort"),
95        /**
96         * Filepath for xml file containing diversion data.
97         */
98        CMS_XML_FILE("CMSDiversionXML"),
99        /**
100         * Filepath for xml file containing dvd control data.
101         */
102        DVD_XML_FILE("DVDPlayerXML"),
103        /**
104         * Filepath for xml file containing still image control data.
105         */
106        IMAGE_XML_FILE("StillImagesXML"),
107        /**
108         * Root directory path where audio files are referenced from.
109         */
110        AUDIO_LOCATION("AudioFileLocation"),
111        /**
112         * Filepath for the properties file to initialize the media manager.
113         */
114        MEDIA_PROP_FILE("MediaProperties"),
115        /**
116         * Filepath for the properties file to initialize the paramics control
117         * manager.
118         */
119        PARAMICS_PROP_FILE("ParamicsProperties"),
120        /**
121         * Filepath for the properties file to initialize the atms manager.
122         */
123        ATMS_PROP_FILE("ATMSProperties"),
124        /**
125         * Filepath for the properties file to initialize the traffic manager.
126         */
127        TRAFFICMGR_PROP_FILE("TrafficMgrProperties"),
128        /**
129         * Class name of desired user interface.
130         */
131        USER_INTERFACE("UserInterface"),
132        /**
133         *  Filepath to which is written the simulation time.
134         */
135        ELAPSED_TIME_FILE("ElapsedTimeFile"),
136        /**
137         *  Filepath to which is written the CADcomments log.
138         */
139        CAD_COMMENTS_LOG("CADcommentsLog");
140       
141        public String name;
142
143        private CAD_PROPERTIES(String nam)
144        {
145            name = nam;
146        }
147    };
148    /** NOTE: Protected fields are accessed by Coordinator */
149    /**
150     * CADSimulatorViewer instance.
151     */
152    protected static CADViewer theViewer;
153    //protected static CADSimulatorViewer theViewer;
154    //protected static CADConsoleViewer theConsole;
155    protected static CADSimulatorState theModel;
156    /**
157     * Coordinator instance.
158     */
159    protected static Coordinator theCoordinator;
160    /**
161     * SoundPlayer instance.
162     */
163    protected static SoundPlayer theSoundPlayer = null;
164    /**
165     * SimulationControlManager instance.
166     */
167    protected static SimulationClockManager theSimulationCntrlMgr = null;
168    /**
169     * ParamicsSimulationManager instance.
170     */
171    protected static ParamicsSimulationManager theParamicsSimMgr = null;
172    /**
173     * IncidentManager instance.
174     */
175    protected static IncidentManager theIncidentMgr = null;
176    /**
177     * MediaManager instance.
178     */
179    protected static MediaManager theMediaMgr = null;
180    /**
181     * ATMSManager instance.
182     */
183    protected static ATMSManager theATMSMgr = null;
184    /**
185     * Traffic Model Manager instance
186     */
187    protected static TrafficModelManager theTrafficMgr = null;
188   
189    /**
190     * Properties file for the CADSimulator.
191     */
192    private Properties cadServerProperties;
193
194    /**
195     * Constructor. Load the Properties file and initialize all CAD Simulator
196     * Managers and establish Manager data relationships. A
197     * CADSimulatorSocketHandler is instantiated and started to being listening
198     * for remote CAD connections. The CMSDiversionDB is initialized with the
199     * XML data(incomplete design).
200     *
201     * @param propertiesFile Filename of CAD Simulator properties file.
202     * @throws SimulationException if there is an error in initializing the CAD
203     * Simulator.
204     */
205    public CADServer(String propertiesFile) throws SimulationException
206    {
207
208        try
209        {
210            cadServerProperties = new Properties();
211            cadServerProperties.load(new FileInputStream(propertiesFile));
212            cadSimLogger.logp(Level.INFO, "CADSimulator", "Constructor",
213                    "Properties loaded from " + propertiesFile);
214        } catch (Exception e)
215        {
216            cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
217                    "Exception in reading properties file.", e);
218            JOptionPane.showMessageDialog(new JWindow(), e.getMessage() +
219                    "\nUser.Dir=" + System.getProperty("user.dir"),
220                    "Fatal Error - Exiting", JOptionPane.ERROR_MESSAGE);
221                       
222            throw new SimulationException(SimulationException.PROPERTY_READ_ERROR, e);
223        }
224
225        //Create the Coordinator and register it for RMI communicator.  Start the
226        //CAD Simulator Socket Handler to begin to accept connections from CAD Clients.
227        try
228        {
229            String userInterfaceName =
230                    cadServerProperties.getProperty(
231                    CAD_PROPERTIES.USER_INTERFACE.name);
232            if (userInterfaceName == null)
233            {
234                cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
235                        propertiesFile + " missing property for user interface.");
236                throw new SimulationException(SimulationException.PROPERTY_MISSING_ERROR);
237            }
238            try
239            {
240                Class uiClass = Class.forName(userInterfaceName);
241                theViewer = (CADViewer) uiClass.newInstance();
242            } catch (Exception exc)
243            {
244                cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
245                        "Unable to instantiate user interface: " + userInterfaceName
246                        + " " + exc);
247                throw new SimulationException(SimulationException.INSTANTIATION_FAILURE);
248            }
249            theModel = new CADSimulatorState();
250            theModel.addObserver(theViewer);
251            /** Load the simulation time filename from properties */
252            String simTimeFilename =
253                    cadServerProperties.getProperty(
254                    CAD_PROPERTIES.ELAPSED_TIME_FILE.name);
255            if (simTimeFilename == null)
256            {
257                cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
258                        propertiesFile + " missing property for " + CAD_PROPERTIES.ELAPSED_TIME_FILE.name);
259                throw new SimulationException(SimulationException.PROPERTY_MISSING_ERROR);
260            }
261            /** Load the CAD comments log filename from properties */
262            String commentLogname =
263                    cadServerProperties.getProperty(
264                    CAD_PROPERTIES.CAD_COMMENTS_LOG.name);
265            if (commentLogname == null)
266            {
267                cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
268                        propertiesFile + " missing property for " + CAD_PROPERTIES.CAD_COMMENTS_LOG.name);
269                throw new SimulationException(SimulationException.PROPERTY_MISSING_ERROR);
270            }
271            theCoordinator = new Coordinator(theModel, simTimeFilename, commentLogname);
272
273            startRegistry(Integer.parseInt(
274                    cadServerProperties.getProperty(
275                    CAD_PROPERTIES.COOR_RMI_PORT.name).trim()));
276            startRegistry(Integer.parseInt(
277                    cadServerProperties.getProperty(
278                    CAD_PROPERTIES.CAD_RMI_PORT.name).trim()));
279
280            theSimulationCntrlMgr = new SimulationClockManager(theCoordinator);
281
282            theATMSMgr = new ATMSManager(
283                    cadServerProperties.getProperty(
284                    CAD_PROPERTIES.ATMS_PROP_FILE.name));
285           
286            theTrafficMgr = new TrafficModelManager(
287                    cadServerProperties.getProperty(
288                    CAD_PROPERTIES.TRAFFICMGR_PROP_FILE.name),
289                    theCoordinator);
290            theTrafficMgr.addObserver(theViewer);
291            theTrafficMgr.run();
292
293            theMediaMgr = new MediaManager(
294                    cadServerProperties.getProperty(
295                    CAD_PROPERTIES.MEDIA_PROP_FILE.name),
296                    theATMSMgr, theModel);
297
298            theParamicsSimMgr = new ParamicsSimulationManager(
299                    cadServerProperties.getProperty(
300                    CAD_PROPERTIES.PARAMICS_PROP_FILE.name),
301                    theCoordinator, theMediaMgr);
302
303            theSoundPlayer = new SoundPlayer(
304                    cadServerProperties.getProperty(
305                    CAD_PROPERTIES.AUDIO_LOCATION.name));
306            theSoundPlayer.start();
307
308            theIncidentMgr = new IncidentManager(theCoordinator, theSoundPlayer);
309
310
311            //Begin accepting Client connections
312            CADSimulatorSocketHandler tmsh = new CADSimulatorSocketHandler(
313                    Integer.parseInt(cadServerProperties.getProperty(
314                    CAD_PROPERTIES.CLIENT_PORT.name).trim()));
315            tmsh.start();
316        } catch (RemoteException e)
317        {
318            cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
319                    "Exception in starting Coordinator.", e);
320
321            throw new SimulationException(SimulationException.BINDING, e);
322        }
323
324        //Load CMS Diversion Information from the XML file
325        try
326        {
327            if (cadServerProperties.getProperty(
328                    CAD_PROPERTIES.CMS_XML_FILE.name) != null)
329            {
330                CMSDiversionDB.getInstance().loadFromXML(
331                        DocumentBuilderFactory.newInstance().newDocumentBuilder()
332                        .parse(new File(cadServerProperties.getProperty(
333                        CAD_PROPERTIES.CMS_XML_FILE.name))));
334            }
335        } catch (Exception e)
336        {
337            cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
338                    "Exception in parsing CMSDiversion xml file.", e);
339
340            JOptionPane.showMessageDialog(new JWindow(), "Unable to open "
341                    + cadServerProperties.getProperty(CAD_PROPERTIES.CMS_XML_FILE.name),
342                    "Initialization Error", JOptionPane.WARNING_MESSAGE);
343        }
344
345        theViewer.setVisible(true);
346
347    }
348
349    /**
350     * Binds the Coordinator to an RMI port so that the SimulationManager can
351     * communicate with it, and so that the Coordinator can perform RMI callback
352     * method calls. The port numbers and RMI designators are parsed from the
353     * properties file file.
354     *
355     * @param theCoor A reference to the Coordinator object.
356     * @throws SimulationException if there are errors in binding the RMI to a
357     * port and name.
358     */
359    private void startRegistry(Integer regPort) throws SimulationException
360    {
361
362        try
363        {
364//            if (LocateRegistry.getRegistry(regPort) == null)
365//            {
366            LocateRegistry.createRegistry(regPort);
367            String registryURL = "rmi://localhost:" + regPort + "/coordinator";
368            Naming.rebind(registryURL, theCoordinator);
369//            }
370        } catch (Exception e)
371        {
372            throw new SimulationException(SimulationException.BINDING, e);
373        }
374    }
375
376    /**
377     * Method returns a String representation of the current time. String format
378     * is HHMM
379     *
380     * @return String representation of the current time.
381     */
382    public static String getCADTime()
383    {
384        String time = new String();
385
386        Calendar rightNow = Calendar.getInstance();
387
388        if (rightNow.get(Calendar.HOUR_OF_DAY) < 10)
389        {
390            time += "0";
391        }
392
393        time += (String.valueOf(rightNow.get(Calendar.HOUR_OF_DAY)));
394
395        if (rightNow.get(Calendar.MINUTE) < 10)
396        {
397            time += "0";
398        }
399
400        time += (String.valueOf(rightNow.get(Calendar.MINUTE)));
401
402        return time;
403    }
404
405    /**
406     * Returns a string representation of the current date. String format is:
407     * MMDDYY
408     *
409     * @return String format of the date.
410     */
411    public static String getCADDate()
412    {
413        String date = new String();
414
415        Calendar rightNow = Calendar.getInstance();
416
417        //Months are zero referenced
418        if (rightNow.get(Calendar.MONTH) + 1 < 10)
419        {
420            date += "0";
421        }
422
423        date += (String.valueOf(rightNow.get(Calendar.MONTH) + 1));
424
425        if (rightNow.get(Calendar.DAY_OF_MONTH) < 10)
426        {
427            date += "0";
428        }
429
430        date += (String.valueOf(rightNow.get(Calendar.DAY_OF_MONTH)));
431
432        if (rightNow.get(Calendar.YEAR) % 1000 < 10)
433        {
434            date += "0";
435        }
436
437        date += (String.valueOf(rightNow.get(Calendar.YEAR) % 1000));
438
439        return date;
440
441    }
442
443    /**
444     * Main class. Instantiate a CAD Simulator with the properties file
445     * specified on the command line or the default properties file
446     *
447     * @param args Command line arguments.
448     */
449    public static void main(String[] args)
450    {
451        if (System.getProperty("CONFIG_DIR") == null)
452        {
453            System.setProperty("CONFIG_DIR", "config");
454        }
455        if (System.getProperty("PROP_FILE") != null)
456        {
457            CONFIG_FILE_NAME = System.getProperty("PROP_FILE");
458        }
459        try
460        {
461            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
462            String propFile = System.getProperty("CONFIG_DIR")
463                    + System.getProperty("file.separator")
464                    + CONFIG_FILE_NAME;
465            new CADServer(propFile);
466        } catch (Exception e)
467        {
468            cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Main",
469                    "Error initializing application.", e);
470
471            JOptionPane.showMessageDialog(new JWindow(), e.getMessage(),
472                    "Error - Program Exiting", JOptionPane.ERROR_MESSAGE);
473
474            System.exit(-1);
475        }
476
477    }
478}
Note: See TracBrowser for help on using the repository browser.