Warning: Can't use blame annotator:
svn blame failed on trunk/src/tmcsim/cadsimulator/CADServer.java: ("Can't find a temporary directory: Internal error", 20014)

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

Revision 407, 16.2 KB checked in by jdalbey, 7 years ago (diff)

Fix for #155 to make simulation time filename configurable.

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