Warning: Can't use blame annotator:
svn blame failed on trunk/src/tmcsim/client/CADlogDisplay.java: ("Can't find a temporary directory: Internal error", 20014)

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

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

Create new ExportAction?.java for Sim Mgr and a new client, CADlogDisplay that outputs to console the current CAD log every 10 seconds.

RevLine 
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     * Instance of the ClockView.
73     */
74    private ClockView theView;
75    /**
76     * Properties object for the CADClient class.
77     */
78    private Properties cadClientProp;
79    /**
80     * RMI interface for communication with the remote Coordinator.
81     */
82    private static CoordinatorInterface theCoorInt;
83    /**
84     * reference to itself to be used for disconnecting from CADSimulator
85     */
86    private CADClientInterface client = this;
87    private static final String CONFIG_FILE_NAME = "cad_client_config.properties";
88    private final static int TEN_SECONDS = 10000;
89
90    /**
91     * Constructor. Initialize data from parsed properties file. Create a socket
92     * connection to the CADSimulator.
93     *
94     * @param propertiesFile File path (absolute or relative) to the properties
95     * file containing configuration data.
96     */
97    public CADlogDisplay(String propertiesFile) throws SimulationException,
98            RemoteException
99    {
100        if (!verifyProperties(propertiesFile))
101        {
102            System.exit(0);
103        }
104
105        connect(cadClientProp.getProperty(PROPERTIES.CAD_SIM_HOST.name).trim(),
106                cadClientProp.getProperty(PROPERTIES.CAD_RMI_PORT.name).trim());
107
108        //theView = new ClockView();
109        //theView.setVisible(true);
110
111        // Create a timer that fetches the simulation time every second.
112        Timer timer = new Timer(TEN_SECONDS, new ActionListener()
113        {
114            public void actionPerformed(ActionEvent e)
115            {
116                try
117                {
118                    Vector<Incident> incList = theCoorInt.getIncidentList(); 
119                    StringBuffer sb = new StringBuffer();
120
121                    for (Incident incident: incList)
122                    {
123                    // DefaultTableModel noteTable = (DefaultTableModel) theCoorInt.getCadDataIncidentTable(INC_TABLE.COMMENTS_NOTES, incident.getLogNum());
124                     // Output noteTable
125                        sb.append("Incident # " + incident.logNum + "\n");
126                        // Retrieve the table of comments/notes the users created
127                        DefaultTableModel notesTable = incident.getCommentsNotesTable();
128                        // Retrieve the notes chronologically (Most recent is in first row)
129                        for (int row=notesTable.getRowCount()-1; row >=0; row--)
130                        {
131                            // Combine the fields into one export entry
132                            sb.append(notesTable.getValueAt(row,1) + " "); // time
133                            String initials = (String) notesTable.getValueAt(row,2); // initials
134                            // If there are no user intials, it's a scripted item
135                            if (initials.length() == 0)
136                            {
137                                initials = "Script";
138                            }
139                            sb.append(initials + " ");
140                            sb.append(notesTable.getValueAt(row,4) + "\n"); // notes
141                        }
142                    }
143                    System.out.println(sb);
144                    //long simtime = theCoorInt.getCurrentSimulationTime();
145                    //theView.updateTime("" + formatInterval(simtime));
146                } catch (RemoteException ex)
147                {
148                    Logger.getLogger(CADlogDisplay.class.getName()).log(Level.SEVERE, null, ex);
149                }
150            }
151        });
152        timer.start();
153
154        ensureProperShutdown();
155    }
156
157    /**
158     * Connect to the Coordinator's RMI object, and register this object for
159     * callback with the Coordinator.
160     *
161     * @param hostname Host name of the CAD Simulator.
162     * @param portNumber Port number of the CAD Simulator RMI communication.
163     * @throws SimulationException if there is an error creating the RMI
164     * connection.
165     */
166    protected void connect(String hostname, String portNumber)
167            throws SimulationException
168    {
169
170        String coorIntURL = "";
171
172        try
173        {
174            coorIntURL = "rmi://" + hostname + ":" + portNumber
175                    + "/coordinator";
176            theCoorInt = (CoordinatorInterface) Naming.lookup(coorIntURL);
177            theCoorInt.registerForCallback(this);
178        } catch (Exception e)
179        {
180            throw new SimulationException(SimulationException.CAD_SIM_CONNECT,
181                    e);
182        }
183    }
184
185    /**
186     * This method verifies that the CAD Simulator Host and Port values are not
187     * null. Also, if a CAD Position or User ID do not exist in the properties
188     * file, the user is prompted to enter values. These values are written to
189     * the properties file. If the user cancels the process of entering these
190     * values, the verification fails.
191     *
192     * @param propertiesFile File path (absolute or relative) to the properties
193     * file containing configuration data.
194     * @return True if the properties file is valid, false if not.
195     * @throws SimulationException if there is an exception in verifying the
196     * properties file, or if the user cancels input.
197     */
198    private boolean verifyProperties(String propertiesFile)
199            throws SimulationException
200    {
201
202        // Load the properties file.
203        try
204        {
205            cadClientProp = new Properties();
206            cadClientProp.load(new FileInputStream(propertiesFile));
207        } catch (Exception e)
208        {
209            cadClientLogger.logp(Level.SEVERE, "SimulationManager",
210                    "Constructor", "Exception in reading properties file.", e);
211
212            throw new SimulationException(SimulationException.INITIALIZE_ERROR,
213                    e);
214        }
215
216
217        // Ensure that the properties file does not have null values for the
218        // CAD Simulator's connection information.
219        if (cadClientProp.getProperty(PROPERTIES.CAD_SIM_HOST.name) == null
220                || cadClientProp.getProperty(PROPERTIES.CAD_SIM_PORT.name) == null)
221        {
222            cadClientLogger.logp(Level.SEVERE, "SimulationManager",
223                    "Constructor", "Null value in properties file.");
224            throw new SimulationException(SimulationException.INITIALIZE_ERROR);
225        }
226
227        return true;
228    }
229
230    /**
231     * Format a time in seconds as HH:MM:SS
232     *
233     * @param l
234     * @return
235     */
236    private String formatInterval(final long l)
237    {
238        final long hr = TimeUnit.SECONDS.toHours(l);
239        final long min = TimeUnit.SECONDS.toMinutes(l - TimeUnit.HOURS.toSeconds(hr));
240        final long sec = TimeUnit.SECONDS.toSeconds(l - TimeUnit.HOURS.toSeconds(hr) - TimeUnit.MINUTES.toSeconds(min));
241        return String.format("%02d:%02d:%02d", hr, min, sec);
242    }
243
244    public void ensureProperShutdown()
245    {
246        Runtime.getRuntime().addShutdownHook(new Thread()
247        {
248            public void run()
249            {
250                try
251                {
252                    theCoorInt.unregisterForCallback(client);
253                } catch (RemoteException e)
254                {
255                    e.printStackTrace();
256                }
257            }
258        });
259    }
260
261    /**
262     * Construct the CADClient with the properties file path, either from the
263     * command line arguments or default.
264     *
265     * @param args Command line arguments.
266     */
267    public static void main(String[] args)
268    {
269        if (System.getProperty("CONFIG_DIR") == null)
270        {
271            System.setProperty("CONFIG_DIR", "config");
272        }
273
274        try
275        {
276            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
277            new CADlogDisplay(System.getProperty("CONFIG_DIR") + System.getProperty("file.separator") + CONFIG_FILE_NAME);
278
279        } catch (Exception e)
280        {
281            cadClientLogger.logp(Level.SEVERE, "SimulationManager", "Main",
282                    "Error initializing application.");
283
284            JOptionPane.showMessageDialog(new JWindow(), e.getMessage(),
285                    "Error - Program Exiting", JOptionPane.ERROR_MESSAGE);
286
287            System.exit(-1);
288        }
289
290    }
291}
Note: See TracBrowser for help on using the repository browser.