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

Revision 455, 17.0 KB checked in by jdalbey, 7 years ago (diff)

ConfigStatusTab? updated to fix @169.

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            theTrafficMgr.run();
294
295            theMediaMgr = new MediaManager(
296                    cadServerProperties.getProperty(
297                    CAD_PROPERTIES.MEDIA_PROP_FILE.name),
298                    theATMSMgr, theModel);
299
300            theParamicsSimMgr = new ParamicsSimulationManager(
301                    cadServerProperties.getProperty(
302                    CAD_PROPERTIES.PARAMICS_PROP_FILE.name),
303                    theCoordinator, theMediaMgr);
304
305            theSoundPlayer = new SoundPlayer(
306                    cadServerProperties.getProperty(
307                    CAD_PROPERTIES.AUDIO_LOCATION.name));
308            theSoundPlayer.start();
309
310            theIncidentMgr = new IncidentManager(theCoordinator, theSoundPlayer);
311
312
313            //Begin accepting Client connections
314            CADSimulatorSocketHandler tmsh = new CADSimulatorSocketHandler(
315                    Integer.parseInt(cadServerProperties.getProperty(
316                    CAD_PROPERTIES.CLIENT_PORT.name).trim()));
317            tmsh.start();
318        } catch (RemoteException e)
319        {
320            cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
321                    "Exception in starting Coordinator.", e);
322
323            throw new SimulationException(SimulationException.BINDING, e);
324        }
325
326        //Load CMS Diversion Information from the XML file
327        try
328        {
329            if (cadServerProperties.getProperty(
330                    CAD_PROPERTIES.CMS_XML_FILE.name) != null)
331            {
332                CMSDiversionDB.getInstance().loadFromXML(
333                        DocumentBuilderFactory.newInstance().newDocumentBuilder()
334                        .parse(new File(cadServerProperties.getProperty(
335                        CAD_PROPERTIES.CMS_XML_FILE.name))));
336            }
337        } catch (Exception e)
338        {
339            cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Constructor",
340                    "Exception in parsing CMSDiversion xml file.", e);
341
342            JOptionPane.showMessageDialog(new JWindow(), "Unable to open "
343                    + cadServerProperties.getProperty(CAD_PROPERTIES.CMS_XML_FILE.name),
344                    "Initialization Error", JOptionPane.WARNING_MESSAGE);
345        }
346
347        theViewer.setVisible(true);
348
349    }
350
351    /**
352     * Binds the Coordinator to an RMI port so that the SimulationManager can
353     * communicate with it, and so that the Coordinator can perform RMI callback
354     * method calls. The port numbers and RMI designators are parsed from the
355     * properties file file.
356     *
357     * @param theCoor A reference to the Coordinator object.
358     * @throws SimulationException if there are errors in binding the RMI to a
359     * port and name.
360     */
361    private void startRegistry(Integer regPort) throws SimulationException
362    {
363
364        try
365        {
366//            if (LocateRegistry.getRegistry(regPort) == null)
367//            {
368            LocateRegistry.createRegistry(regPort);
369            String registryURL = "rmi://localhost:" + regPort + "/coordinator";
370            Naming.rebind(registryURL, theCoordinator);
371//            }
372        } catch (Exception e)
373        {
374            throw new SimulationException(SimulationException.BINDING, e);
375        }
376    }
377
378    /**
379     * Method returns a String representation of the current time. String format
380     * is HHMM
381     *
382     * @return String representation of the current time.
383     */
384    public static String getCADTime()
385    {
386        String time = new String();
387
388        Calendar rightNow = Calendar.getInstance();
389
390        if (rightNow.get(Calendar.HOUR_OF_DAY) < 10)
391        {
392            time += "0";
393        }
394
395        time += (String.valueOf(rightNow.get(Calendar.HOUR_OF_DAY)));
396
397        if (rightNow.get(Calendar.MINUTE) < 10)
398        {
399            time += "0";
400        }
401
402        time += (String.valueOf(rightNow.get(Calendar.MINUTE)));
403
404        return time;
405    }
406
407    /**
408     * Returns a string representation of the current date. String format is:
409     * MMDDYY
410     *
411     * @return String format of the date.
412     */
413    public static String getCADDate()
414    {
415        String date = new String();
416
417        Calendar rightNow = Calendar.getInstance();
418
419        //Months are zero referenced
420        if (rightNow.get(Calendar.MONTH) + 1 < 10)
421        {
422            date += "0";
423        }
424
425        date += (String.valueOf(rightNow.get(Calendar.MONTH) + 1));
426
427        if (rightNow.get(Calendar.DAY_OF_MONTH) < 10)
428        {
429            date += "0";
430        }
431
432        date += (String.valueOf(rightNow.get(Calendar.DAY_OF_MONTH)));
433
434        if (rightNow.get(Calendar.YEAR) % 1000 < 10)
435        {
436            date += "0";
437        }
438
439        date += (String.valueOf(rightNow.get(Calendar.YEAR) % 1000));
440
441        return date;
442
443    }
444
445    /**
446     * Main class. Instantiate a CAD Simulator with the properties file
447     * specified on the command line or the default properties file
448     *
449     * @param args Command line arguments.
450     */
451    public static void main(String[] args)
452    {
453        if (System.getProperty("CONFIG_DIR") == null)
454        {
455            System.setProperty("CONFIG_DIR", "config");
456        }
457        if (System.getProperty("PROP_FILE") != null)
458        {
459            CONFIG_FILE_NAME = System.getProperty("PROP_FILE");
460        }
461        try
462        {
463            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
464            String propFile = System.getProperty("CONFIG_DIR")
465                    + System.getProperty("file.separator")
466                    + CONFIG_FILE_NAME;
467            new CADServer(propFile);
468        } catch (Exception e)
469        {
470            cadSimLogger.logp(Level.SEVERE, "CADSimulator", "Main",
471                    "Error initializing application.", e);
472
473            JOptionPane.showMessageDialog(new JWindow(), e.getMessage(),
474                    "Error - Program Exiting", JOptionPane.ERROR_MESSAGE);
475
476            System.exit(-1);
477        }
478
479    }
480}
Note: See TracBrowser for help on using the repository browser.