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

Revision 123, 14.5 KB checked in by jdalbey, 9 years ago (diff)

Multiple renaming of classes to improve clarity. Remove check for Paramics running before starting sim.

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