source: tmcsimulator/trunk/src/tmcsim/client/CADlogDisplay.java @ 425

Revision 425, 10.1 KB checked in by jdalbey, 7 years ago (diff)

build.xml updated to include new highway model package. CADlogDisplay altered to show only user entries not scripted ones.

Line 
1package tmcsim.client;
2
3import java.awt.event.ActionEvent;
4import java.awt.event.ActionListener;
5import java.io.FileInputStream;
6import java.rmi.Naming;
7import java.rmi.RemoteException;
8import java.rmi.server.UnicastRemoteObject;
9import java.util.Properties;
10import java.util.Vector;
11import java.util.concurrent.TimeUnit;
12import java.util.logging.Level;
13import java.util.logging.Logger;
14import javax.swing.JOptionPane;
15import javax.swing.JWindow;
16import javax.swing.Timer;
17import javax.swing.UIManager;
18import javax.swing.table.DefaultTableModel;
19import tmcsim.client.cadclientgui.data.Incident;
20import tmcsim.client.cadclientgui.enums.CADDataEnums.INC_TABLE;
21import tmcsim.common.SimulationException;
22import tmcsim.interfaces.CADClientInterface;
23import tmcsim.interfaces.CoordinatorInterface;
24
25/**
26 * CADlogDisplays shows the current CAD log for all incidents. It operates as a client of the
27 * CAD server, using RMI to poll the server every second for the current
28 * list of incidents and associated comments/notes table.
29 *
30 * @author jdalbey
31 */
32public class CADlogDisplay extends UnicastRemoteObject implements
33        CADClientInterface
34{
35    /**
36     * Error logger.
37     */
38    private static Logger cadClientLogger = Logger.getLogger("tmcsim.client");
39
40    @Override
41    public void refresh() throws RemoteException
42    {
43        throw new UnsupportedOperationException("Not supported yet.");
44    }
45
46    /**
47     * Enumeration containing properties name values. See CADClient class
48     * description for more information.
49     *
50     * @author Matthew Cechini
51     * @see CADClient
52     */
53    private static enum PROPERTIES
54    {
55        CAD_SIM_HOST("CADSimulatorHost"), CAD_SIM_PORT("CADSimulatorSocketPort"), CAD_RMI_PORT(
56        "CADRmiPort"), CLIENT_CAD_POS("CADPosition"), CLIENT_USER_ID(
57        "CADUserID"), KEYBOARD_TYPE("KeyboardType"), DISPLAY_TYPE(
58        "DisplayType");
59        public String name;
60
61        private PROPERTIES(String n)
62        {
63            name = n;
64        }
65    }
66    /**
67     * CADClientSocket Object to handle socket communication between the Client
68     * and CAD Simulator.
69     */
70    private CADClientSocket theClientSocket;
71
72    /**
73     * Properties object for the CADClient class.
74     */
75    private Properties cadClientProp;
76    /**
77     * RMI interface for communication with the remote Coordinator.
78     */
79    private static CoordinatorInterface theCoorInt;
80    /**
81     * reference to itself to be used for disconnecting from CADSimulator
82     */
83    private CADClientInterface client = this;
84    private static final String CONFIG_FILE_NAME = "cad_client_config.properties";
85    private final static int TEN_SECONDS = 10000;
86
87    /**
88     * Constructor. Initialize data from parsed properties file. Create a socket
89     * connection to the CADSimulator.
90     *
91     * @param propertiesFile File path (absolute or relative) to the properties
92     * file containing configuration data.
93     */
94    public CADlogDisplay(String propertiesFile) throws SimulationException,
95            RemoteException
96    {
97        if (!verifyProperties(propertiesFile))
98        {
99            System.exit(0);
100        }
101
102        connect(cadClientProp.getProperty(PROPERTIES.CAD_SIM_HOST.name).trim(),
103                cadClientProp.getProperty(PROPERTIES.CAD_RMI_PORT.name).trim());
104
105        //theView = new ClockView();
106        //theView.setVisible(true);
107
108        // Create a timer that fetches the simulation time every second.
109        Timer timer = new Timer(TEN_SECONDS, new ActionListener()
110        {
111            public void actionPerformed(ActionEvent e)
112            {
113                try
114                {
115                    Vector<Incident> incList = theCoorInt.getIncidentList(); 
116                    StringBuffer sb = new StringBuffer();
117
118                    for (Incident incident: incList)
119                    {
120                    // DefaultTableModel noteTable = (DefaultTableModel) theCoorInt.getCadDataIncidentTable(INC_TABLE.COMMENTS_NOTES, incident.getLogNum());
121                     // Output noteTable
122                        sb.append("Incident # " + incident.logNum + "\n");
123                        // Retrieve the table of comments/notes the users created
124                        DefaultTableModel notesTable = incident.getCommentsNotesTable();
125                        // Retrieve the notes chronologically (Most recent is in first row)
126                        for (int row=notesTable.getRowCount()-1; row >=0; row--)
127                        {
128                            // Combine the fields into one export entry
129                            sb.append(notesTable.getValueAt(row,1) + " "); // time
130                            String initials = (String) notesTable.getValueAt(row,2); // initials
131                            // If there are user intials, include this item.
132                            // Zero length initials mean it's a scripted item
133                            if (initials.length() > 0)
134                            {
135                                sb.append(initials + " ");
136                                sb.append(notesTable.getValueAt(row,4) + "\n"); // notes
137                            }
138                        }
139                    }
140                    System.out.println(sb);
141                    //long simtime = theCoorInt.getCurrentSimulationTime();
142                    //theView.updateTime("" + formatInterval(simtime));
143                } catch (RemoteException ex)
144                {
145                    Logger.getLogger(CADlogDisplay.class.getName()).log(Level.SEVERE, null, ex);
146                }
147            }
148        });
149        timer.start();
150
151        ensureProperShutdown();
152    }
153
154    /**
155     * Connect to the Coordinator's RMI object, and register this object for
156     * callback with the Coordinator.
157     *
158     * @param hostname Host name of the CAD Simulator.
159     * @param portNumber Port number of the CAD Simulator RMI communication.
160     * @throws SimulationException if there is an error creating the RMI
161     * connection.
162     */
163    protected void connect(String hostname, String portNumber)
164            throws SimulationException
165    {
166
167        String coorIntURL = "";
168
169        try
170        {
171            coorIntURL = "rmi://" + hostname + ":" + portNumber
172                    + "/coordinator";
173            theCoorInt = (CoordinatorInterface) Naming.lookup(coorIntURL);
174            theCoorInt.registerForCallback(this);
175        } catch (Exception e)
176        {
177            throw new SimulationException(SimulationException.CAD_SIM_CONNECT,
178                    e);
179        }
180    }
181
182    /**
183     * This method verifies that the CAD Simulator Host and Port values are not
184     * null. Also, if a CAD Position or User ID do not exist in the properties
185     * file, the user is prompted to enter values. These values are written to
186     * the properties file. If the user cancels the process of entering these
187     * values, the verification fails.
188     *
189     * @param propertiesFile File path (absolute or relative) to the properties
190     * file containing configuration data.
191     * @return True if the properties file is valid, false if not.
192     * @throws SimulationException if there is an exception in verifying the
193     * properties file, or if the user cancels input.
194     */
195    private boolean verifyProperties(String propertiesFile)
196            throws SimulationException
197    {
198
199        // Load the properties file.
200        try
201        {
202            cadClientProp = new Properties();
203            cadClientProp.load(new FileInputStream(propertiesFile));
204        } catch (Exception e)
205        {
206            cadClientLogger.logp(Level.SEVERE, "SimulationManager",
207                    "Constructor", "Exception in reading properties file.", e);
208
209            throw new SimulationException(SimulationException.INITIALIZE_ERROR,
210                    e);
211        }
212
213
214        // Ensure that the properties file does not have null values for the
215        // CAD Simulator's connection information.
216        if (cadClientProp.getProperty(PROPERTIES.CAD_SIM_HOST.name) == null
217                || cadClientProp.getProperty(PROPERTIES.CAD_SIM_PORT.name) == null)
218        {
219            cadClientLogger.logp(Level.SEVERE, "SimulationManager",
220                    "Constructor", "Null value in properties file.");
221            throw new SimulationException(SimulationException.INITIALIZE_ERROR);
222        }
223
224        return true;
225    }
226
227    /**
228     * Format a time in seconds as HH:MM:SS
229     *
230     * @param l
231     * @return
232     */
233    private String formatInterval(final long l)
234    {
235        final long hr = TimeUnit.SECONDS.toHours(l);
236        final long min = TimeUnit.SECONDS.toMinutes(l - TimeUnit.HOURS.toSeconds(hr));
237        final long sec = TimeUnit.SECONDS.toSeconds(l - TimeUnit.HOURS.toSeconds(hr) - TimeUnit.MINUTES.toSeconds(min));
238        return String.format("%02d:%02d:%02d", hr, min, sec);
239    }
240
241    public void ensureProperShutdown()
242    {
243        Runtime.getRuntime().addShutdownHook(new Thread()
244        {
245            public void run()
246            {
247                try
248                {
249                    theCoorInt.unregisterForCallback(client);
250                } catch (RemoteException e)
251                {
252                    e.printStackTrace();
253                }
254            }
255        });
256    }
257
258    /**
259     * Construct the CADClient with the properties file path, either from the
260     * command line arguments or default.
261     *
262     * @param args Command line arguments.
263     */
264    public static void main(String[] args)
265    {
266        if (System.getProperty("CONFIG_DIR") == null)
267        {
268            System.setProperty("CONFIG_DIR", "config");
269        }
270
271        try
272        {
273            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
274            new CADlogDisplay(System.getProperty("CONFIG_DIR") + System.getProperty("file.separator") + CONFIG_FILE_NAME);
275
276        } catch (Exception e)
277        {
278            cadClientLogger.logp(Level.SEVERE, "SimulationManager", "Main",
279                    "Error initializing application.");
280
281            JOptionPane.showMessageDialog(new JWindow(), e.getMessage(),
282                    "Error - Program Exiting", JOptionPane.ERROR_MESSAGE);
283
284            System.exit(-1);
285        }
286
287    }
288}
Note: See TracBrowser for help on using the repository browser.