source: tmcsimulator/trunk/src/tmcsim/paramicslog/ParamicsLog.java @ 2

Revision 2, 10.0 KB checked in by jdalbey, 10 years ago (diff)

Initial Import of project files

Line 
1package tmcsim.paramicslog;
2
3import java.io.File;
4import java.io.FileInputStream;
5import java.io.FileWriter;
6import java.io.IOException;
7import java.rmi.Naming;
8import java.util.Observable;
9import java.util.Properties;
10import java.util.logging.Level;
11import java.util.logging.Logger;
12
13import javax.swing.JOptionPane;
14
15import org.w3c.dom.Element;
16
17import tmcsim.common.SimulationException;
18import tmcsim.interfaces.CoordinatorInterface;
19import tmcsim.paramicslog.gui.ParamicsLogGUI;
20
21/**
22 * Logs communication from ParamicsCommunicator to ParamicsSimulator.
23 *
24 * The system property "PARAMICS_LOG_CONFIG" should be set to the path
25 * where the properties file for this class is located. <br><br>
26 * The data for the properties file follows. <br>
27 * <code>
28 * -----------------------------------------------------------------<br>
29 * Log File                The file to write the communication to.
30 * CAD Simulator Host      The host that runs the CAD Simulator.
31 * CAD Simulator RMI Port  The port on the host that runs the CAD
32 *                         Simulator where the RMI Coordinator
33 *                         object is registered to.
34 * -----------------------------------------------------------------<br>
35 * Example File: <br>
36 * LogFile=c:\\log.txt
37 * CADSimulatorHost=localhost
38 * CADSimulatorRMIPort=4445
39 * -----------------------------------------------------------------<br>
40 * </code>
41 *
42 * @author Nathaniel Lehrer
43 * @version
44 */
45public class ParamicsLog extends Observable
46{   
47    /**
48     * Enmeration containing property names.
49     * @author Nathaniel Lehrer
50     */
51    private enum PROPERTIES
52    {
53        LOG_FILE      ("LogFile"),
54        CAD_SIM_HOST  ("CADSimulatorHost"),
55        CAD_SIM_PORT  ("CADSimulatorRMIPort");
56       
57        public String name;
58       
59        private PROPERTIES(String n)
60        {
61            name = n;
62        }
63    }
64   
65    /** Error logger. */
66    private static Logger paramLogger = Logger.getLogger("tmcsim.paramicslog");
67   
68    /** Static instance. */
69    private static ParamicsLog instance;
70   
71    /** Properties object. */
72    private Properties paramicsLogProp;
73   
74    /** File log entries are written to */
75    private File logFile;
76   
77    /** Stores the log entries. This contains the same information logFile. */
78    private StringBuilder log;
79
80    /** Remote reference to the simulation */
81    private CoordinatorInterface theCoorInt;
82   
83    /** Object for synchronizing IO */
84    Object lock;
85   
86    /**
87     * Creates the singleton instance of this class.
88     */
89    static
90    {
91        try 
92        {
93            if (System.getProperty("PARAMICS_LOG_PROPERTIES") != null)
94            {
95                instance = new ParamicsLog(System.getProperty("PARAMICS_LOG_PROPERTIES"));
96            }
97            else
98            {
99                throw new Exception("PARAMICS_LOG_PROPERTIES system property not defined.");
100            }
101        } 
102        catch (Exception e) 
103        {
104            instance = new ParamicsLog();
105           
106            paramLogger.logp(Level.WARNING, "ParamicsLog", "static initializer", 
107                    "Error occured initializing application", e);
108
109            JOptionPane.showMessageDialog(null, e.getMessage(), 
110                    "Error - ParamicsLog will not save log to file.", 
111                    JOptionPane.ERROR_MESSAGE); 
112        }
113       
114        instance.addObserver(ParamicsLogGUI.getInstance());
115    }
116   
117    /**
118     * Creates an instance of ParamicsLog that does not write to a file when
119     * writeToLog is called.
120     */
121    private ParamicsLog() {
122       
123        lock = new Object();
124        log = new StringBuilder("");
125    }
126   
127    /**
128     * Creates an instance of ParamicsLog that writes to a file when writeToLog is called.
129     * @param propertiesFile
130     */
131    private ParamicsLog(String propertiesFile) {
132        this();
133       
134        String logFile = null;
135        String CADSIMHost = null;
136        String CADSIMPort = null;
137       
138        try {
139            paramicsLogProp = new Properties();
140            paramicsLogProp.load(new FileInputStream(propertiesFile));
141           
142            if ((logFile = paramicsLogProp.getProperty(PROPERTIES.LOG_FILE.name)) == null)
143            {
144                throw new Exception("Properties file missing log file location.");
145            }
146            else if ((CADSIMHost = paramicsLogProp.getProperty(PROPERTIES.CAD_SIM_HOST.name)) == null)
147            {   
148                throw new Exception("Properties file missing CAD Simulator host.");
149            }
150            else if ((CADSIMPort = paramicsLogProp.getProperty(PROPERTIES.CAD_SIM_PORT.name)) == null)
151            {
152                throw new Exception("Properties file missing CAD Simulator RMI port.");
153            }
154           
155            try
156            {
157                connect(CADSIMHost, CADSIMPort);
158            }
159            catch (Exception e)
160            {
161                JOptionPane.showMessageDialog(null, 
162                        "ParamicsLog: Could not connect to remote Coordinator object.", 
163                        "Network Error", JOptionPane.ERROR_MESSAGE);               
164            }
165           
166            try 
167            {
168                createLogFile(logFile);
169            }
170            catch (Exception e)
171            {
172                JOptionPane.showMessageDialog(null, 
173                        "ParamicsLog: Could not create new log file.", 
174                        "File Error", JOptionPane.ERROR_MESSAGE);
175            }
176           
177        } catch (Exception e) {
178           
179            paramLogger.logp(Level.WARNING, "ParamicsLog", "ParamicsLog constructor", 
180                    "Properties file incorrect or missing.", e);
181           
182            JOptionPane.showMessageDialog(null, 
183                    "ParamicsLog: Properties file invalid.", 
184                    "Invalid Configuration", JOptionPane.ERROR_MESSAGE);
185        }
186    }
187   
188    /**
189     * Creates the log file.
190     * @param filePath The path to the file including the file name.
191     * @throws IOException If the log file could not be created.
192     */
193    private void createLogFile(String filePath) throws IOException
194    {
195        try {
196            logFile = new File(filePath);
197           
198            if (logFile.exists()) {
199                logFile.delete();
200            }
201           
202            logFile.createNewFile();
203           
204        } catch (Exception e) {
205           
206            logFile = null;
207           
208            paramLogger.logp(Level.WARNING, "ParamicsLog", "ParamicsLog constructor", 
209                    "Could not create new log file.", e);
210           
211            throw new IOException("Could not create log file.");
212        }               
213    }
214   
215    /**
216     * Connect to the Coordinator's RMI object.
217     * @param hostname Host name of the CAD Simulator.   
218     * @param portNumber Port number of the CAD Simulator RMI communication.
219     * @throws SimulationException if there is an error creating the RMI connection.
220     */ 
221    private void connect(String hostname, String portNumber) 
222        throws SimulationException {
223       
224        String coorIntURL = "";
225       
226        try { 
227            coorIntURL = "rmi://" + hostname + ":" + portNumber + "/coordinator"; 
228           
229            theCoorInt = (CoordinatorInterface)Naming.lookup(coorIntURL);           
230        }
231        catch (Exception e) 
232        {
233            paramLogger.logp(Level.WARNING, "ParamicsLog", 
234                    "establishRMIConnection", "Unable to establish RMI " +
235                    "communication with the CAD Simulator.  URL <" + coorIntURL + ">", e);
236        }   
237    }
238   
239    /**
240     * Accessor to the entries in the log. No file IO is used.
241     * @return The entries in the log.
242     */
243    public String getLog() {
244       
245        return log.toString();
246    }
247   
248    /**
249     * Writes an entry to the log.
250     * The simulator time when the message was sent is prepended to the entry.
251     * Entries are padded by a blank line before and after them.
252     * TODO: Ensure output is written in order of request.
253     * @param entry
254     */
255    public void writeToLog(String entry) {
256       
257        String time = "?";
258        String formattedEntry;
259       
260        if (theCoorInt != null)
261        {
262            try
263            {
264                time = formatTime(theCoorInt.getCurrentSimulationTime());
265            }
266            catch (Exception e)
267            {
268                paramLogger.logp(Level.WARNING, "ParamicsLog", 
269                        "RMICommunication", "Unable to communicate with RMI object", e);
270            }
271        }
272       
273        formattedEntry = "\n" + "<!-- Time written to file: " + time + " -->\n" + entry + "\n";
274        log.append(formattedEntry);
275       
276        if (logFile != null)
277        {
278            try 
279            {
280                synchronized(lock)
281                {
282                    FileWriter writer = new FileWriter(logFile, true);
283                    writer.append(formattedEntry);
284                    writer.flush();
285                    writer.close();
286                }
287            } 
288            catch (IOException e) 
289            {
290                paramLogger.logp(Level.WARNING, "ParamicsLog", "writeToLog", 
291                        "Could not write to log file.", e);
292            }
293        }
294       
295        setChanged();
296        notifyObservers(entry);
297    }
298   
299    /**
300     * Formats the time given in seconds to hh:mm:ss format.
301     * @param time The time in seconds.
302     */
303    private String formatTime(long time)
304    {
305        long seconds = time % 60;
306        long minutes = (time - seconds) / 60;
307        long hours = (time - seconds - minutes * 60) / 60;
308
309        return padr(hours) + ":" + padr(minutes) + ":" + padr(seconds);
310    }
311   
312    private String padr(long n)
313    {
314        if (n < 10)
315        {
316            return "0" + n;
317        }
318        {
319            return "" + n;
320        }
321    }
322   
323    /**
324     * Accessor for static instance of this class.
325     * @return The instance of this class.
326     */
327    public static ParamicsLog getInstance() {
328       
329        return instance;
330    }
331}
Note: See TracBrowser for help on using the repository browser.