source: trunk/autoquest-htmlmonitor/src/main/java/de/ugoe/cs/autoquest/htmlmonitor/HtmlMonitorOutputWriter.java @ 1022

Last change on this file since 1022 was 1022, checked in by pharms, 12 years ago
  • removed todos
File size: 12.2 KB
Line 
1//   Copyright 2012 Georg-August-Universität Göttingen, Germany
2//
3//   Licensed under the Apache License, Version 2.0 (the "License");
4//   you may not use this file except in compliance with the License.
5//   You may obtain a copy of the License at
6//
7//       http://www.apache.org/licenses/LICENSE-2.0
8//
9//   Unless required by applicable law or agreed to in writing, software
10//   distributed under the License is distributed on an "AS IS" BASIS,
11//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//   See the License for the specific language governing permissions and
13//   limitations under the License.
14
15package de.ugoe.cs.autoquest.htmlmonitor;
16
17import java.io.File;
18import java.io.FileOutputStream;
19import java.io.IOException;
20import java.io.OutputStreamWriter;
21import java.io.PrintWriter;
22import java.text.DecimalFormat;
23
24import de.ugoe.cs.util.StringTools;
25import de.ugoe.cs.util.console.Console;
26
27/**
28 * <p>
29 * dumps messages to a log file belonging to a specific client id. In the provided base log
30 * directory, it creates a subdirectory with the client id. In this directory it creates
31 * appropriate log files. The name of each finished log file starts with the "htmlmonitor_"
32 * followed by the client id and an index of the log file. An unfinished log file has no index yet.
33 * A log file is finished if
34 * <ul>
35 *   <li>the client session is closed by a timeout</li>
36 *   <li>the HTML monitor is normally shut down</li>
37 *   <li>on startup an unfinished log file is detected.</li>
38 *   <li>the {@link #MAXIMUM_LOG_FILE_SIZE} is reached</li>
39 * </ul>
40 * </p>
41 *
42 * @author Patrick Harms
43 * @version 1.0
44 *
45 */
46public class HtmlMonitorOutputWriter implements HtmlMonitorComponent, HtmlMonitorMessageListener {
47   
48    /**
49     * the maximum size of an individual log file
50     */
51    private static final int MAXIMUM_LOG_FILE_SIZE = 10000000;
52
53    /**
54     * the default log base directory if none is provided through the constructor
55     */
56    private static final String DEFAULT_LOG_FILE_BASE_DIR = "logs";
57
58    /**
59     * the currently used log file base directory
60     */
61    private File logFileBaseDir;
62
63    /**
64     * the is of the client of which all messages are logged through this writer
65     */
66    private String clientId;
67
68    /**
69     * the log file into which all messages are currently written
70     */
71    private File logFile;
72
73    /**
74     * an output writer to be used for writing into the log file
75     */
76    private PrintWriter outputWriter;
77
78    /**
79     * the time stamp of the last action taken on this writer (such as logging a message)
80     */
81    private long lastUpdate;
82
83    /**
84     * <p>
85     * initializes the writer with the log file base directory and the id of the client for which
86     * this writer logs the messages.
87     * </p>
88     *
89     * @param logFileBaseDir the log file base directory, or null if the default directory shall
90     *                       be taken
91     * @param clientId       the ID of the client, for which this writer logs
92     */
93    public HtmlMonitorOutputWriter(String logFileBaseDir, String clientId) {
94        if (logFileBaseDir == null) {
95            this.logFileBaseDir = new File(DEFAULT_LOG_FILE_BASE_DIR);
96        }
97        else {
98            this.logFileBaseDir = new File(logFileBaseDir);
99        }
100       
101        this.clientId = clientId;
102       
103        lastUpdate = System.currentTimeMillis();
104    }
105
106    /* (non-Javadoc)
107     * @see de.ugoe.cs.autoquest.htmlmonitor.HtmlMonitorComponent#init()
108     */
109    @Override
110    public synchronized void init() throws HtmlMonitorException {
111        if (outputWriter != null) {
112            throw new IllegalStateException("already initialized. Call close() first");
113        }
114       
115        synchronized (HtmlMonitorOutputWriter.class) {
116            try {
117                File clientLogDir = new File(logFileBaseDir, clientId);
118           
119                if (!clientLogDir.exists()) {
120                    if (!clientLogDir.mkdirs()) {
121                        throw new HtmlMonitorException("client log file directory " + clientLogDir +
122                                                       " can not be created");
123                    }
124                }
125                else if (!clientLogDir.isDirectory()) {
126                    throw new HtmlMonitorException("client log file directory " + clientLogDir +
127                                                   " already exists as a file");
128                }
129               
130                logFile = new File(clientLogDir, getLogFileName(-1));
131               
132                if (logFile.exists()) {
133                    rotateLogFile();
134                }
135           
136                createLogWriter();
137            }
138            catch (IOException e) {
139                throw new HtmlMonitorException("could not open logfile " + logFile, e);
140            }
141        }
142       
143        lastUpdate = System.currentTimeMillis();
144    }
145
146    /**
147     * <p>
148     * used to calculate a log file name. If the provided index is smaller 0, then no index
149     * is added to the file name. A filename is e.g. "htmlmonitor_12345_001.log".
150     * </p>
151     *
152     * @param index the index of the log file or -1 one, if no index shall be added
153     *
154     * @return the file name as described
155     */
156    private String getLogFileName(int index) {
157        String result = "htmlmonitor_" + clientId;
158       
159        if (index >= 0) {
160            result += "_" + new DecimalFormat("000" ).format(index);
161        }
162       
163        result += ".log";
164       
165        return result;
166    }
167
168    /* (non-Javadoc)
169     * @see de.ugoe.cs.autoquest.htmlmonitor.HtmlMonitorComponent#start()
170     */
171    @Override
172    public synchronized void start() throws IllegalStateException, HtmlMonitorException {
173        lastUpdate = System.currentTimeMillis();
174    }
175
176    /* (non-Javadoc)
177     * @see HtmlMonitorMessageListener#handleMessage(HtmlClientInfos, HtmlEvent[])
178     */
179    @Override
180    public void handleMessage(HtmlClientInfos clientInfos,
181                              HtmlPageElement guiStructure,
182                              HtmlEvent[]     events)
183    {
184        if (outputWriter == null) {
185            throw new IllegalStateException("not initialized. Call init() first");
186        }
187       
188        if (guiStructure != null) {
189            dumpGuiStructure(guiStructure);
190        }
191       
192        for (HtmlEvent event : events) {
193            dumpEvent(event);
194        }
195       
196        outputWriter.flush();
197       
198        try {
199            considerLogRotate();
200        }
201        catch (IOException e) {
202            throw new IllegalStateException("could not perform log rotation: " + e, e);
203        }
204       
205        lastUpdate = System.currentTimeMillis();
206    }
207
208    /**
209     * <p>
210     * dumps the GUI structure provided by the parameter into the log file. Calls itself
211     * recursively to traverse the GUI structure.
212     * </p>
213     *
214     * @param guiStructure the GUI structure to be logged
215     */
216    private void dumpGuiStructure(HtmlPageElement guiStructure) {
217        outputWriter.print("<component path=\"");
218        outputWriter.print(guiStructure.getPath());
219        outputWriter.println("\">");
220       
221        dumpParam("class", guiStructure.getTagName());
222        dumpParam("htmlId", guiStructure.getId());
223        dumpParam("title", guiStructure.getTitle());
224        dumpParam("index", guiStructure.getIndex());
225        dumpParam("parent", guiStructure.getParentPath());
226       
227        outputWriter.println("</component>");
228       
229        if (guiStructure.getChildren() != null) {
230            for (HtmlPageElement child : guiStructure.getChildren()) {
231                dumpGuiStructure(child);
232            }
233        }
234    }
235
236    /**
237     * <p>
238     * formats a received event and writes it to the log file. One event results in one line
239     * in the log file containing all infos of the event.
240     * </p>
241     *
242     * @param event to be written to the log file
243     */
244    private void dumpEvent(HtmlEvent event) {
245        outputWriter.print("<event type=\"");
246        outputWriter.print(event.getEventType());
247        outputWriter.println("\">");
248       
249        if (event.getCoordinates() != null) {
250            dumpParam("X", event.getCoordinates()[0]);
251            dumpParam("Y", event.getCoordinates()[1]);
252        }
253
254        dumpParam("key", event.getKey());
255           
256        if (event.getScrollPosition() != null) {
257            dumpParam("scrollX", event.getScrollPosition()[0]);
258            dumpParam("scrollY", event.getScrollPosition()[1]);
259        }
260
261        dumpParam("selectedValue", event.getSelectedValue());
262        dumpParam("target", event.getPath());
263        dumpParam("timestamp", event.getTime());
264       
265        outputWriter.println("</event>");
266    }
267
268    /**
269     * <p>
270     * dumps a parameter with the given name and value to the log file. The result is a
271     * tag named param with a name attribute and a value attribute. The value is transformed
272     * to a String if it is no String already. Furthermore, an XML entity replacement is performed
273     * if required.
274     * </p>
275     *
276     * @param name  the name of the parameter to be dumped
277     * @param value the value of the parameter to be dumped
278     */
279    private void dumpParam(String name, Object value) {
280        if (value == null) {
281            return;
282        }
283       
284        String val;
285       
286        if (value instanceof String) {
287            val = (String) value;
288        }
289        else {
290            val = value.toString();
291        }
292       
293        outputWriter.print(" <param name=\"");
294        outputWriter.print(name);
295        outputWriter.print("\" value=\"");
296        outputWriter.print(StringTools.xmlEntityReplacement(val));
297        outputWriter.println("\"/>");
298    }
299
300    /**
301     * <p>
302     * checks, if the log file exeeded the {@link #MAXIMUM_LOG_FILE_SIZE}. If so, the current
303     * log file is closed, the next log file name is determined and this new file is opend for
304     * writing.
305     * </p>
306     */
307    private synchronized void considerLogRotate() throws IOException {
308        if (logFile.length() > MAXIMUM_LOG_FILE_SIZE) {
309            closeLogWriter();
310            rotateLogFile();
311            createLogWriter();
312        }
313    }
314
315    /**
316     * <p>
317     * renames the current log file to a new log file with the next available index. It further
318     * sets the current log file to the default name, i.e. without index.
319     * </p>
320     */
321    private void rotateLogFile() {
322        File clientLogDir = logFile.getParentFile();
323        File checkFile;
324
325        int logFileIndex = -1;
326        do {
327            logFileIndex++;
328           
329            checkFile = new File(clientLogDir, getLogFileName(logFileIndex));
330        }
331        while (checkFile.exists());
332   
333        if (!logFile.renameTo(checkFile)) {
334            Console.printerrln("could not rename log file " + logFile + " to " + checkFile +
335                               ". Will not perform log rotation.");
336        }
337        else {
338            logFileIndex++;
339            logFile = new File(clientLogDir, getLogFileName(-1));
340        }
341    }
342
343    /**
344     * <p>
345     * instantiates a writer to be used for writing messages into the log file.
346     * </p>
347     */
348    private void createLogWriter() throws IOException {
349        FileOutputStream fis = new FileOutputStream(logFile);
350        outputWriter = new PrintWriter(new OutputStreamWriter(fis, "UTF-8"));
351        outputWriter.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
352        outputWriter.println("<session>");
353    }
354
355    /**
356     * <p>
357     * closed the current writer if it is open.
358     * </p>
359     */
360    private void closeLogWriter() {
361        if (outputWriter != null) {
362            outputWriter.println("</session>");
363            outputWriter.flush();
364            outputWriter.close();
365            outputWriter = null;
366        }
367    }
368
369    /* (non-Javadoc)
370     * @see de.ugoe.cs.autoquest.htmlmonitor.HtmlMonitorComponent#stop()
371     */
372    @Override
373    public synchronized void stop() {
374        closeLogWriter();
375        rotateLogFile();
376
377        lastUpdate = System.currentTimeMillis();
378    }
379
380    /**
381     * <p>
382     * return the time stamp of the last activity that happened on this writer.
383     * </p>
384     *
385     * @return as described
386     */
387    public long getLastUpdate() {
388        return lastUpdate;
389    }
390}
Note: See TracBrowser for help on using the repository browser.