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

Revision 360, 15.3 KB checked in by jdalbey, 7 years ago (diff)

add spike ShowUserDir?.java

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 cadServerProperties;
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            cadServerProperties = new Properties();
202            cadServerProperties.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            JOptionPane.showMessageDialog(new JWindow(), e.getMessage() +
210                    "\nUser.Dir=" + System.getProperty("user.dir"),
211                    "Fatal Error - Exiting", JOptionPane.ERROR_MESSAGE);
212                       
213            throw new SimulationException(SimulationException.PROPERTY_READ_ERROR, e);
214        }
215
216        //Create the Coordinator and register it for RMI communicator.  Start the
217        //CAD Simulator Socket Handler to begin to accept connections from CAD Clients.
218        try
219        {
220            String userInterfaceName =
221                    cadServerProperties.getProperty(
222                    CAD_PROPERTIES.USER_INTERFACE.name);
223            if (userInterfaceName == null)
224            {
225                cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
226                        propertiesFile + " missing property for user interface.");
227                throw new SimulationException(SimulationException.PROPERTY_MISSING_ERROR);
228            }
229            try
230            {
231                Class uiClass = Class.forName(userInterfaceName);
232                theViewer = (CADViewer) uiClass.newInstance();
233            } catch (Exception exc)
234            {
235                cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
236                        "Unable to instantiate user interface: " + userInterfaceName
237                        + " " + exc);
238                throw new SimulationException(SimulationException.INSTANTIATION_FAILURE);
239            }
240            theModel = new CADSimulatorState();
241            theModel.addObserver(theViewer);
242
243            theCoordinator = new Coordinator(theModel);
244
245            startRegistry(Integer.parseInt(
246                    cadServerProperties.getProperty(
247                    CAD_PROPERTIES.COOR_RMI_PORT.name).trim()));
248            startRegistry(Integer.parseInt(
249                    cadServerProperties.getProperty(
250                    CAD_PROPERTIES.CAD_RMI_PORT.name).trim()));
251
252            theSimulationCntrlMgr = new SimulationClockManager(theCoordinator);
253
254            theATMSMgr = new ATMSManager(
255                    cadServerProperties.getProperty(
256                    CAD_PROPERTIES.ATMS_PROP_FILE.name));
257           
258            theTrafficMgr = new TrafficModelManager(
259                    cadServerProperties.getProperty(
260                    CAD_PROPERTIES.TRAFFICMGR_PROP_FILE.name),
261                    theCoordinator);
262            theTrafficMgr.addObserver(theViewer);
263            theTrafficMgr.run();
264
265            theMediaMgr = new MediaManager(
266                    cadServerProperties.getProperty(
267                    CAD_PROPERTIES.MEDIA_PROP_FILE.name),
268                    theATMSMgr, theModel);
269
270            theParamicsSimMgr = new ParamicsSimulationManager(
271                    cadServerProperties.getProperty(
272                    CAD_PROPERTIES.PARAMICS_PROP_FILE.name),
273                    theCoordinator, theMediaMgr);
274
275            theSoundPlayer = new SoundPlayer(
276                    cadServerProperties.getProperty(
277                    CAD_PROPERTIES.AUDIO_LOCATION.name));
278            theSoundPlayer.start();
279
280            theIncidentMgr = new IncidentManager(theCoordinator, theSoundPlayer);
281
282
283            //Begin accepting Client connections
284            CADSimulatorSocketHandler tmsh = new CADSimulatorSocketHandler(
285                    Integer.parseInt(cadServerProperties.getProperty(
286                    CAD_PROPERTIES.CLIENT_PORT.name).trim()));
287            tmsh.start();
288        } catch (RemoteException e)
289        {
290            cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
291                    "Exception in starting Coordinator.", e);
292
293            throw new SimulationException(SimulationException.BINDING, e);
294        }
295
296        //Load CMS Diversion Information from the XML file
297        try
298        {
299            if (cadServerProperties.getProperty(
300                    CAD_PROPERTIES.CMS_XML_FILE.name) != null)
301            {
302                CMSDiversionDB.getInstance().loadFromXML(
303                        DocumentBuilderFactory.newInstance().newDocumentBuilder()
304                        .parse(new File(cadServerProperties.getProperty(
305                        CAD_PROPERTIES.CMS_XML_FILE.name))));
306            }
307        } catch (Exception e)
308        {
309            cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
310                    "Exception in parsing CMSDiversion xml file.", e);
311
312            JOptionPane.showMessageDialog(new JWindow(), "Unable to open "
313                    + cadServerProperties.getProperty(CAD_PROPERTIES.CMS_XML_FILE.name),
314                    "Initialization Error", JOptionPane.WARNING_MESSAGE);
315        }
316
317        theViewer.setVisible(true);
318
319    }
320
321    /**
322     * Binds the Coordinator to an RMI port so that the SimulationManager can
323     * communicate with it, and so that the Coordinator can perform RMI callback
324     * method calls. The port numbers and RMI designators are parsed from the
325     * properties file file.
326     *
327     * @param theCoor A reference to the Coordinator object.
328     * @throws SimulationException if there are errors in binding the RMI to a
329     * port and name.
330     */
331    private void startRegistry(Integer regPort) throws SimulationException
332    {
333
334        try
335        {
336//            if (LocateRegistry.getRegistry(regPort) == null)
337//            {
338            LocateRegistry.createRegistry(regPort);
339            String registryURL = "rmi://localhost:" + regPort + "/coordinator";
340            Naming.rebind(registryURL, theCoordinator);
341//            }
342        } catch (Exception e)
343        {
344            throw new SimulationException(SimulationException.BINDING, e);
345        }
346    }
347
348    /**
349     * Method returns a String representation of the current time. String format
350     * is HHMM
351     *
352     * @return String representation of the current time.
353     */
354    public static String getCADTime()
355    {
356        String time = new String();
357
358        Calendar rightNow = Calendar.getInstance();
359
360        if (rightNow.get(Calendar.HOUR_OF_DAY) < 10)
361        {
362            time += "0";
363        }
364
365        time += (String.valueOf(rightNow.get(Calendar.HOUR_OF_DAY)));
366
367        if (rightNow.get(Calendar.MINUTE) < 10)
368        {
369            time += "0";
370        }
371
372        time += (String.valueOf(rightNow.get(Calendar.MINUTE)));
373
374        return time;
375    }
376
377    /**
378     * Returns a string representation of the current date. String format is:
379     * MMDDYY
380     *
381     * @return String format of the date.
382     */
383    public static String getCADDate()
384    {
385        String date = new String();
386
387        Calendar rightNow = Calendar.getInstance();
388
389        //Months are zero referenced
390        if (rightNow.get(Calendar.MONTH) + 1 < 10)
391        {
392            date += "0";
393        }
394
395        date += (String.valueOf(rightNow.get(Calendar.MONTH) + 1));
396
397        if (rightNow.get(Calendar.DAY_OF_MONTH) < 10)
398        {
399            date += "0";
400        }
401
402        date += (String.valueOf(rightNow.get(Calendar.DAY_OF_MONTH)));
403
404        if (rightNow.get(Calendar.YEAR) % 1000 < 10)
405        {
406            date += "0";
407        }
408
409        date += (String.valueOf(rightNow.get(Calendar.YEAR) % 1000));
410
411        return date;
412
413    }
414
415    /**
416     * Main class. Instantiate a CAD Simulator with the properties file
417     * specified on the command line or the default properties file
418     *
419     * @param args Command line arguments.
420     */
421    public static void main(String[] args)
422    {
423        if (System.getProperty("CONFIG_DIR") == null)
424        {
425            System.setProperty("CONFIG_DIR", "config");
426        }
427        try
428        {
429            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
430            String propFile = System.getProperty("CONFIG_DIR")
431                    + System.getProperty("file.separator")
432                    + CONFIG_FILE_NAME;
433            new CADServer(propFile);
434        } catch (Exception e)
435        {
436            cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Main",
437                    "Error initializing application.", e);
438
439            JOptionPane.showMessageDialog(new JWindow(), e.getMessage(),
440                    "Error - Program Exiting", JOptionPane.ERROR_MESSAGE);
441
442            System.exit(-1);
443        }
444
445    }
446}
Note: See TracBrowser for help on using the repository browser.