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

Revision 206, 15.3 KB checked in by jdalbey, 9 years ago (diff)

TrafficModelManager?.java Refactor to use Observable, along with the view. Add Reload button functionality.

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