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

Revision 210, 15.1 KB checked in by jdalbey, 9 years ago (diff)

Integrate TrafficModelViewer? into the CAD Server GUI as an additional tab. Eliminates the separate window for traffic mgr view.

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 final 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        public String name;
133
134        private CAD_PROPERTIES(String nam)
135        {
136            name = nam;
137        }
138    };
139    /** NOTE: Protected fields are accessed by Coordinator */
140    /**
141     * CADSimulatorViewer instance.
142     */
143    protected static CADViewer theViewer;
144    //protected static CADSimulatorViewer theViewer;
145    //protected static CADConsoleViewer theConsole;
146    protected static CADSimulatorState theModel;
147    /**
148     * Coordinator instance.
149     */
150    protected static Coordinator theCoordinator;
151    /**
152     * SoundPlayer instance.
153     */
154    protected static SoundPlayer theSoundPlayer = null;
155    /**
156     * SimulationControlManager instance.
157     */
158    protected static SimulationClockManager theSimulationCntrlMgr = null;
159    /**
160     * ParamicsSimulationManager instance.
161     */
162    protected static ParamicsSimulationManager theParamicsSimMgr = null;
163    /**
164     * IncidentManager instance.
165     */
166    protected static IncidentManager theIncidentMgr = null;
167    /**
168     * MediaManager instance.
169     */
170    protected static MediaManager theMediaMgr = null;
171    /**
172     * ATMSManager instance.
173     */
174    protected static ATMSManager theATMSMgr = null;
175    /**
176     * Traffic Model Manager instance
177     */
178    protected static TrafficModelManager theTrafficMgr = null;
179   
180    /**
181     * Properties file for the CADSimulator.
182     */
183    private Properties cadSimulatorProperties;
184
185    /**
186     * Constructor. Load the Properties file and initialize all CAD Simulator
187     * Managers and establish Manager data relationships. A
188     * CADSimulatorSocketHandler is instantiated and started to being listening
189     * for remote CAD connections. The CMSDiversionDB is initialized with the
190     * XML data(incomplete design).
191     *
192     * @param propertiesFile Filename of CAD Simulator properties file.
193     * @throws SimulationException if there is an error in initializing the CAD
194     * Simulator.
195     */
196    public CADServer(String propertiesFile) throws SimulationException
197    {
198
199        try
200        {
201            cadSimulatorProperties = new Properties();
202            cadSimulatorProperties.load(new FileInputStream(propertiesFile));
203            cadSimLogger.logp(Level.INFO, "CADSimulator", "Constructor",
204                    "Properties loaded from " + propertiesFile);
205        } catch (Exception e)
206        {
207            cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
208                    "Exception in reading properties file.", e);
209
210            throw new SimulationException(SimulationException.INITIALIZE_ERROR, e);
211        }
212
213        //Create the Coordinator and register it for RMI communicator.  Start the
214        //CAD Simulator Socket Handler to begin to accept connections from CAD Clients.
215        try
216        {
217            String userInterfaceName =
218                    cadSimulatorProperties.getProperty(
219                    CAD_PROPERTIES.USER_INTERFACE.name);
220            if (userInterfaceName == null)
221            {
222                cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
223                        propertiesFile + " missing property for user interface.");
224                throw new SimulationException(SimulationException.INITIALIZE_ERROR);
225            }
226            try
227            {
228                Class uiClass = Class.forName(userInterfaceName);
229                theViewer = (CADViewer) uiClass.newInstance();
230            } catch (Exception exc)
231            {
232                cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
233                        "Unable to instantiate user interface: " + userInterfaceName
234                        + " " + exc);
235                throw new SimulationException(SimulationException.INITIALIZE_ERROR);
236            }
237            theModel = new CADSimulatorState();
238            theModel.addObserver(theViewer);
239
240            theCoordinator = new Coordinator(theModel);
241
242            startRegistry(Integer.parseInt(
243                    cadSimulatorProperties.getProperty(
244                    CAD_PROPERTIES.COOR_RMI_PORT.name).trim()));
245            startRegistry(Integer.parseInt(
246                    cadSimulatorProperties.getProperty(
247                    CAD_PROPERTIES.CAD_RMI_PORT.name).trim()));
248
249            theSimulationCntrlMgr = new SimulationClockManager(theCoordinator);
250
251            theATMSMgr = new ATMSManager(
252                    cadSimulatorProperties.getProperty(
253                    CAD_PROPERTIES.ATMS_PROP_FILE.name));
254           
255            theTrafficMgr = new TrafficModelManager(
256                    cadSimulatorProperties.getProperty(
257                    CAD_PROPERTIES.TRAFFICMGR_PROP_FILE.name),
258                    theCoordinator);
259            theTrafficMgr.addObserver(theViewer);
260            theTrafficMgr.run();
261
262            theMediaMgr = new MediaManager(
263                    cadSimulatorProperties.getProperty(
264                    CAD_PROPERTIES.MEDIA_PROP_FILE.name),
265                    theATMSMgr, theModel);
266
267            theParamicsSimMgr = new ParamicsSimulationManager(
268                    cadSimulatorProperties.getProperty(
269                    CAD_PROPERTIES.PARAMICS_PROP_FILE.name),
270                    theCoordinator, theMediaMgr);
271
272            theSoundPlayer = new SoundPlayer(
273                    cadSimulatorProperties.getProperty(
274                    CAD_PROPERTIES.AUDIO_LOCATION.name));
275            theSoundPlayer.start();
276
277            theIncidentMgr = new IncidentManager(theCoordinator, theSoundPlayer);
278
279
280            //Begin accepting Client connections
281            CADSimulatorSocketHandler tmsh = new CADSimulatorSocketHandler(
282                    Integer.parseInt(cadSimulatorProperties.getProperty(
283                    CAD_PROPERTIES.CLIENT_PORT.name).trim()));
284            tmsh.start();
285        } catch (RemoteException e)
286        {
287            cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
288                    "Exception in starting Coordinator.", e);
289
290            throw new SimulationException(SimulationException.BINDING, e);
291        }
292
293        //Load CMS Diversion Information from the XML file
294        try
295        {
296            if (cadSimulatorProperties.getProperty(
297                    CAD_PROPERTIES.CMS_XML_FILE.name) != null)
298            {
299                CMSDiversionDB.getInstance().loadFromXML(
300                        DocumentBuilderFactory.newInstance().newDocumentBuilder()
301                        .parse(new File(cadSimulatorProperties.getProperty(
302                        CAD_PROPERTIES.CMS_XML_FILE.name))));
303            }
304        } catch (Exception e)
305        {
306            cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
307                    "Exception in parsing CMSDiversion xml file.", e);
308
309            JOptionPane.showMessageDialog(new JWindow(), "Unable to open "
310                    + cadSimulatorProperties.getProperty(CAD_PROPERTIES.CMS_XML_FILE.name),
311                    "Initialization Error", JOptionPane.WARNING_MESSAGE);
312        }
313
314        theViewer.setVisible(true);
315
316    }
317
318    /**
319     * Binds the Coordinator to an RMI port so that the SimulationManager can
320     * communicate with it, and so that the Coordinator can perform RMI callback
321     * method calls. The port numbers and RMI designators are parsed from the
322     * properties file file.
323     *
324     * @param theCoor A reference to the Coordinator object.
325     * @throws SimulationException if there are errors in binding the RMI to a
326     * port and name.
327     */
328    private void startRegistry(Integer regPort) throws SimulationException
329    {
330
331        try
332        {
333//            if (LocateRegistry.getRegistry(regPort) == null)
334//            {
335            LocateRegistry.createRegistry(regPort);
336            String registryURL = "rmi://localhost:" + regPort + "/coordinator";
337            Naming.rebind(registryURL, theCoordinator);
338//            }
339        } catch (Exception e)
340        {
341            throw new SimulationException(SimulationException.BINDING, e);
342        }
343    }
344
345    /**
346     * Method returns a String representation of the current time. String format
347     * is HHMM
348     *
349     * @return String representation of the current time.
350     */
351    public static String getCADTime()
352    {
353        String time = new String();
354
355        Calendar rightNow = Calendar.getInstance();
356
357        if (rightNow.get(Calendar.HOUR_OF_DAY) < 10)
358        {
359            time += "0";
360        }
361
362        time += (String.valueOf(rightNow.get(Calendar.HOUR_OF_DAY)));
363
364        if (rightNow.get(Calendar.MINUTE) < 10)
365        {
366            time += "0";
367        }
368
369        time += (String.valueOf(rightNow.get(Calendar.MINUTE)));
370
371        return time;
372    }
373
374    /**
375     * Returns a string representation of the current date. String format is:
376     * MMDDYY
377     *
378     * @return String format of the date.
379     */
380    public static String getCADDate()
381    {
382        String date = new String();
383
384        Calendar rightNow = Calendar.getInstance();
385
386        //Months are zero referenced
387        if (rightNow.get(Calendar.MONTH) + 1 < 10)
388        {
389            date += "0";
390        }
391
392        date += (String.valueOf(rightNow.get(Calendar.MONTH) + 1));
393
394        if (rightNow.get(Calendar.DAY_OF_MONTH) < 10)
395        {
396            date += "0";
397        }
398
399        date += (String.valueOf(rightNow.get(Calendar.DAY_OF_MONTH)));
400
401        if (rightNow.get(Calendar.YEAR) % 1000 < 10)
402        {
403            date += "0";
404        }
405
406        date += (String.valueOf(rightNow.get(Calendar.YEAR) % 1000));
407
408        return date;
409
410    }
411
412    /**
413     * Main class. Instantiate a CAD Simulator with the properties file
414     * specified on the command line or the default properties file
415     *
416     * @param args Command line arguments.
417     */
418    public static void main(String[] args)
419    {
420        if (System.getProperty("CONFIG_DIR") == null)
421        {
422            System.setProperty("CONFIG_DIR", "config");
423        }
424        try
425        {
426            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
427            String propFile = System.getProperty("CONFIG_DIR")
428                    + System.getProperty("file.separator")
429                    + CONFIG_FILE_NAME;
430            new CADServer(propFile);
431        } catch (Exception e)
432        {
433            cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Main",
434                    "Error initializing application.", e);
435
436            JOptionPane.showMessageDialog(new JWindow(), e.getMessage(),
437                    "Error - Program Exiting", JOptionPane.ERROR_MESSAGE);
438
439            System.exit(-1);
440        }
441
442    }
443}
Note: See TracBrowser for help on using the repository browser.