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

Last change on this file since 1019 was 1019, checked in by pharms, 12 years ago
  • changed logfile format to XML
  • included logging of GUI structure
  • moved robot detection into monitor
File size: 11.7 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     * TODO: comment
211     * </p>
212     *
213     * @param guiStructure
214     */
215    private void dumpGuiStructure(HtmlPageElement guiStructure) {
216        outputWriter.print("<component path=\"");
217        outputWriter.print(guiStructure.getPath());
218        outputWriter.println("\">");
219       
220        dumpParam("class", guiStructure.getTagName());
221        dumpParam("htmlId", guiStructure.getId());
222        dumpParam("title", guiStructure.getTitle());
223        dumpParam("index", guiStructure.getIndex());
224        dumpParam("parent", guiStructure.getParentPath());
225       
226        outputWriter.println("</component>");
227       
228        if (guiStructure.getChildren() != null) {
229            for (HtmlPageElement child : guiStructure.getChildren()) {
230                dumpGuiStructure(child);
231            }
232        }
233    }
234
235    /**
236     * <p>
237     * formats a received event and writes it to the log file. One event results in one line
238     * in the log file containing all infos of the event.
239     * </p>
240     *
241     * @param event to be written to the log file
242     */
243    private void dumpEvent(HtmlEvent event) {
244        outputWriter.print("<event type=\"");
245        outputWriter.print(event.getEventType());
246        outputWriter.println("\">");
247       
248        if (event.getCoordinates() != null) {
249            dumpParam("X", event.getCoordinates()[0]);
250            dumpParam("Y", event.getCoordinates()[1]);
251        }
252
253        dumpParam("key", event.getKey());
254           
255        if (event.getScrollPosition() != null) {
256            dumpParam("scrollX", event.getScrollPosition()[0]);
257            dumpParam("scrollY", event.getScrollPosition()[1]);
258        }
259
260        dumpParam("selectedValue", event.getSelectedValue());
261        dumpParam("target", event.getPath());
262        dumpParam("timestamp", event.getTime());
263       
264        outputWriter.println("</event>");
265    }
266
267    /**
268     * <p>
269     * TODO: comment
270     * </p>
271     *
272     * @param string
273     * @param integer
274     */
275    private void dumpParam(String name, Object value) {
276        if (value == null) {
277            return;
278        }
279       
280        String val;
281       
282        if (value instanceof String) {
283            val = (String) value;
284        }
285        else {
286            val = value.toString();
287        }
288       
289        outputWriter.print(" <param name=\"");
290        outputWriter.print(name);
291        outputWriter.print("\" value=\"");
292        outputWriter.print(StringTools.xmlEntityReplacement(val));
293        outputWriter.println("\"/>");
294    }
295
296    /**
297     * <p>
298     * checks, if the log file exeeded the {@link #MAXIMUM_LOG_FILE_SIZE}. If so, the current
299     * log file is closed, the next log file name is determined and this new file is opend for
300     * writing.
301     * </p>
302     */
303    private synchronized void considerLogRotate() throws IOException {
304        if (logFile.length() > MAXIMUM_LOG_FILE_SIZE) {
305            closeLogWriter();
306            rotateLogFile();
307            createLogWriter();
308        }
309    }
310
311    /**
312     * <p>
313     * renames the current log file to a new log file with the next available index. It further
314     * sets the current log file to the default name, i.e. without index.
315     * </p>
316     */
317    private void rotateLogFile() {
318        File clientLogDir = logFile.getParentFile();
319        File checkFile;
320
321        int logFileIndex = -1;
322        do {
323            logFileIndex++;
324           
325            checkFile = new File(clientLogDir, getLogFileName(logFileIndex));
326        }
327        while (checkFile.exists());
328   
329        if (!logFile.renameTo(checkFile)) {
330            Console.printerrln("could not rename log file " + logFile + " to " + checkFile +
331                               ". Will not perform log rotation.");
332        }
333        else {
334            logFileIndex++;
335            logFile = new File(clientLogDir, getLogFileName(-1));
336        }
337    }
338
339    /**
340     * <p>
341     * instantiates a writer to be used for writing messages into the log file.
342     * </p>
343     */
344    private void createLogWriter() throws IOException {
345        FileOutputStream fis = new FileOutputStream(logFile);
346        outputWriter = new PrintWriter(new OutputStreamWriter(fis, "UTF-8"));
347        outputWriter.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
348        outputWriter.println("<session>");
349    }
350
351    /**
352     * <p>
353     * closed the current writer if it is open.
354     * </p>
355     */
356    private void closeLogWriter() {
357        if (outputWriter != null) {
358            outputWriter.println("</session>");
359            outputWriter.flush();
360            outputWriter.close();
361            outputWriter = null;
362        }
363    }
364
365    /* (non-Javadoc)
366     * @see de.ugoe.cs.autoquest.htmlmonitor.HtmlMonitorComponent#stop()
367     */
368    @Override
369    public synchronized void stop() {
370        closeLogWriter();
371        rotateLogFile();
372
373        lastUpdate = System.currentTimeMillis();
374    }
375
376    /**
377     * <p>
378     * return the time stamp of the last activity that happened on this writer.
379     * </p>
380     *
381     * @return as described
382     */
383    public long getLastUpdate() {
384        return lastUpdate;
385    }
386}
Note: See TracBrowser for help on using the repository browser.