source: tmcsimulator/trunk/src/tmcsim/cadsimulator/CADSimulator.java @ 44

Revision 44, 14.3 KB checked in by jdalbey, 10 years ago (diff)

MultiFile? commit: Add CADViewer Interface and change CADSimulator to Observer Pattern.

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