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 @ 654

Revision 654, 17.3 KB checked in by jdalbey, 4 years ago (diff)

TrafficModelManager?.java changed timer from Swing timer to java.util.timer to avoid any potential thread locking issues.
CADServer.java moved call to traffic mgr run() until after setVisible ... fix obscure bug on laptop NetBeans.

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