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

Last change on this file since 1315 was 1315, checked in by pharms, 11 years ago
  • corrected HTML monitor to log only those GUI elements effectively used by the events including their parent hierarchy
File size: 14.8 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;
23import java.util.HashSet;
24import java.util.Set;
25
26import de.ugoe.cs.util.StringTools;
27import de.ugoe.cs.util.console.Console;
28
29/**
30 * <p>
31 * dumps messages to a log file belonging to a specific client id. In the provided base log
32 * directory, it creates a subdirectory with the client id. In this directory it creates
33 * appropriate log files. The name of each finished log file starts with the "htmlmonitor_"
34 * followed by the client id and an index of the log file. An unfinished log file has no index yet.
35 * A log file is finished if
36 * <ul>
37 *   <li>the client session is closed by a timeout</li>
38 *   <li>the HTML monitor is normally shut down</li>
39 *   <li>on startup an unfinished log file is detected.</li>
40 *   <li>the {@link #MAXIMUM_LOG_FILE_SIZE} is reached</li>
41 * </ul>
42 * </p>
43 *
44 * @author Patrick Harms
45 * @version 1.0
46 *
47 */
48public class HtmlMonitorOutputWriter implements HtmlMonitorComponent, HtmlMonitorMessageListener {
49   
50    /**
51     * the maximum size of an individual log file
52     */
53    private static final int MAXIMUM_LOG_FILE_SIZE = 50000000;
54
55    /**
56     * the default log base directory if none is provided through the constructor
57     */
58    private static final String DEFAULT_LOG_FILE_BASE_DIR = "logs";
59
60    /**
61     * the currently used log file base directory
62     */
63    private File logFileBaseDir;
64
65    /**
66     * the id of the web application used by the client
67     */
68    private String webAppId;
69
70    /**
71     * the id of the client of which all messages are logged through this writer
72     */
73    private String clientId;
74
75    /**
76     * the log file into which all messages are currently written
77     */
78    private File logFile;
79
80    /**
81     * an output writer to be used for writing into the log file
82     */
83    private PrintWriter outputWriter;
84
85    /**
86     * the time stamp of the last action taken on this writer (such as logging a message)
87     */
88    private long lastUpdate;
89   
90    /**
91     * the GUI elements, that were already logged and need therefore not be logged again into
92     * the same file
93     */
94    private Set<HtmlGUIElement> loggedGUIElements = new HashSet<HtmlGUIElement>();
95
96    /**
97     * <p>
98     * initializes the writer with the log file base directory and the id of the client for which
99     * this writer logs the messages.
100     * </p>
101     *
102     * @param logFileBaseDir the log file base directory, or null if the default directory shall
103     *                       be taken
104     * @param webAppId       the ID of the web application used by the client
105     * @param clientId       the ID of the client, for which this writer logs
106     */
107    public HtmlMonitorOutputWriter(String logFileBaseDir, String webAppId, String clientId) {
108        if (logFileBaseDir == null) {
109            this.logFileBaseDir = new File(DEFAULT_LOG_FILE_BASE_DIR);
110        }
111        else {
112            this.logFileBaseDir = new File(logFileBaseDir);
113        }
114       
115        this.webAppId = webAppId;
116        this.clientId = clientId;
117       
118        lastUpdate = System.currentTimeMillis();
119    }
120
121    /* (non-Javadoc)
122     * @see de.ugoe.cs.autoquest.htmlmonitor.HtmlMonitorComponent#init()
123     */
124    @Override
125    public synchronized void init() throws HtmlMonitorException {
126        if (outputWriter != null) {
127            throw new IllegalStateException("already initialized. Call close() first");
128        }
129       
130        synchronized (HtmlMonitorOutputWriter.class) {
131            try {
132                File clientLogDir = new File(logFileBaseDir, webAppId);
133                clientLogDir = new File(clientLogDir, clientId);
134               
135                if (!clientLogDir.exists()) {
136                    if (!clientLogDir.mkdirs()) {
137                        throw new HtmlMonitorException("client log file directory " + clientLogDir +
138                                                       " can not be created");
139                    }
140                }
141                else if (!clientLogDir.isDirectory()) {
142                    throw new HtmlMonitorException("client log file directory " + clientLogDir +
143                                                   " already exists as a file");
144                }
145               
146                handleOldLogFiles(new File(logFileBaseDir, clientId), clientLogDir);
147               
148                logFile = new File(clientLogDir, getLogFileName(-1));
149               
150                if (logFile.exists()) {
151                    rotateLogFile();
152                }
153           
154                createLogWriter();
155            }
156            catch (IOException e) {
157                throw new HtmlMonitorException("could not open logfile " + logFile, e);
158            }
159        }
160       
161        lastUpdate = System.currentTimeMillis();
162    }
163
164    /**
165     * <p>
166     * used to calculate a log file name. If the provided index is smaller 0, then no index
167     * is added to the file name. A filename is e.g. "htmlmonitor_12345_001.log".
168     * </p>
169     *
170     * @param index the index of the log file or -1 one, if no index shall be added
171     *
172     * @return the file name as described
173     */
174    private String getLogFileName(int index) {
175        String result = "htmlmonitor_" + clientId;
176       
177        if (index >= 0) {
178            result += "_" + new DecimalFormat("000" ).format(index);
179        }
180       
181        result += ".log";
182       
183        return result;
184    }
185
186    /* (non-Javadoc)
187     * @see de.ugoe.cs.autoquest.htmlmonitor.HtmlMonitorComponent#start()
188     */
189    @Override
190    public synchronized void start() throws IllegalStateException, HtmlMonitorException {
191        lastUpdate = System.currentTimeMillis();
192    }
193
194    /* (non-Javadoc)
195     * @see HtmlMonitorMessageListener#handleMessage(HtmlClientInfos, HtmlEvent[])
196     */
197    @Override
198    public synchronized void handleMessage(HtmlClientInfos clientInfos,
199                                           HtmlGUIElement  guiStructure,
200                                           HtmlEvent[]     events)
201    {
202        if (outputWriter == null) {
203            throw new IllegalStateException("not initialized. Call init() first");
204        }
205       
206        for (HtmlEvent event : events) {
207            dumpEvent(event);
208        }
209       
210        outputWriter.flush();
211       
212        try {
213            considerLogRotate();
214        }
215        catch (IOException e) {
216            throw new IllegalStateException("could not perform log rotation: " + e, e);
217        }
218       
219        lastUpdate = System.currentTimeMillis();
220    }
221
222    /**
223     * <p>
224     * formats a received event and writes it to the log file. One event results in one line
225     * in the log file containing all infos of the event.
226     * </p>
227     *
228     * @param event to be written to the log file
229     */
230    private void dumpEvent(HtmlEvent event) {
231        if (event.getTarget() != null) {
232            ensureGuiElementDumped(event.getTarget());
233        }
234       
235        outputWriter.print("<event type=\"");
236        outputWriter.print(event.getEventType());
237        outputWriter.println("\">");
238       
239        if (event.getCoordinates() != null) {
240            dumpParam("X", event.getCoordinates()[0]);
241            dumpParam("Y", event.getCoordinates()[1]);
242        }
243
244        dumpParam("key", event.getKey());
245           
246        if (event.getScrollPosition() != null) {
247            dumpParam("scrollX", event.getScrollPosition()[0]);
248            dumpParam("scrollY", event.getScrollPosition()[1]);
249        }
250
251        dumpParam("selectedValue", event.getSelectedValue());
252       
253        if (event.getTarget() != null) {
254            dumpParam("target", event.getTarget().getId());
255        }
256        else {
257            dumpParam("targetDocument", event.getTargetDocument().getId());
258            dumpParam("targetDOMPath", event.getTargetDOMPath());
259        }
260        dumpParam("timestamp", event.getTime());
261       
262        outputWriter.println("</event>");
263    }
264
265    /**
266     * <p>
267     * dumps a GUI element starting with its parent GUI elements into the log file. Calls itself
268     * recursively to traverse for dumping the parents first.
269     * </p>
270     *
271     * @param guiStructure the GUI structure to be logged
272     */
273    private void ensureGuiElementDumped(HtmlGUIElement guiElement) {
274        if (!loggedGUIElements.contains(guiElement)) {
275           
276            HtmlGUIElement parent = guiElement.getParent();
277            String parentId = null;
278           
279            if (parent != null) {
280                ensureGuiElementDumped(parent);
281                parentId = parent.getId();
282            }
283           
284            outputWriter.print("<component id=\"");
285            outputWriter.print(guiElement.getId());
286            outputWriter.println("\">");
287       
288            if (guiElement instanceof HtmlServer) {
289                dumpParam("host", ((HtmlServer) guiElement).getName());
290                dumpParam("port", ((HtmlServer) guiElement).getPort());
291            }
292            else if (guiElement instanceof HtmlDocument) {
293                dumpParam("path", ((HtmlDocument) guiElement).getPath());
294                dumpParam("query", ((HtmlDocument) guiElement).getQuery());
295                dumpParam("title", ((HtmlDocument) guiElement).getTitle());
296            }
297            else if (guiElement instanceof HtmlPageElement) {
298                dumpParam("tagname", ((HtmlPageElement) guiElement).getTagName());
299                dumpParam("htmlid", ((HtmlPageElement) guiElement).getHtmlId());
300                dumpParam("index", ((HtmlPageElement) guiElement).getIndex());
301            }
302           
303            dumpParam("parent", parentId);
304       
305            outputWriter.println("</component>");
306       
307            loggedGUIElements.add(guiElement);
308        }
309    }
310
311    /**
312     * <p>
313     * dumps a parameter with the given name and value to the log file. The result is a
314     * tag named param with a name attribute and a value attribute. The value is transformed
315     * to a String if it is no String already. Furthermore, an XML entity replacement is performed
316     * if required.
317     * </p>
318     *
319     * @param name  the name of the parameter to be dumped
320     * @param value the value of the parameter to be dumped
321     */
322    private void dumpParam(String name, Object value) {
323        if (value == null) {
324            return;
325        }
326       
327        String val;
328       
329        if (value instanceof String) {
330            val = (String) value;
331        }
332        else {
333            val = String.valueOf(value);
334        }
335       
336        outputWriter.print(" <param name=\"");
337        outputWriter.print(name);
338        outputWriter.print("\" value=\"");
339        outputWriter.print(StringTools.xmlEntityReplacement(val));
340        outputWriter.println("\"/>");
341    }
342
343    /**
344     * <p>
345     * checks, if the log file exeeded the {@link #MAXIMUM_LOG_FILE_SIZE}. If so, the current
346     * log file is closed, the next log file name is determined and this new file is opend for
347     * writing.
348     * </p>
349     */
350    private synchronized void considerLogRotate() throws IOException {
351        if (logFile.length() > MAXIMUM_LOG_FILE_SIZE) {
352            closeLogWriter();
353            rotateLogFile();
354            createLogWriter();
355        }
356    }
357
358    /**
359     * <p>
360     * renames the current log file to a new log file with the next available index. It further
361     * sets the current log file to the default name, i.e. without index.
362     * </p>
363     */
364    private void rotateLogFile() {
365        File clientLogDir = logFile.getParentFile();
366        File checkFile;
367
368        int logFileIndex = -1;
369        do {
370            logFileIndex++;
371           
372            checkFile = new File(clientLogDir, getLogFileName(logFileIndex));
373        }
374        while (checkFile.exists());
375   
376        if (!logFile.renameTo(checkFile)) {
377            Console.printerrln("could not rename log file " + logFile + " to " + checkFile +
378                               ". Will not perform log rotation.");
379        }
380        else {
381            logFileIndex++;
382            logFile = new File(clientLogDir, getLogFileName(-1));
383        }
384    }
385
386    /**
387     * <p>
388     * instantiates a writer to be used for writing messages into the log file.
389     * </p>
390     */
391    private void createLogWriter() throws IOException {
392        FileOutputStream fis = new FileOutputStream(logFile);
393        outputWriter = new PrintWriter(new OutputStreamWriter(fis, "UTF-8"));
394        outputWriter.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
395        outputWriter.println("<session>");
396       
397        loggedGUIElements.clear();
398    }
399
400    /**
401     * <p>
402     * closed the current writer if it is open.
403     * </p>
404     */
405    private void closeLogWriter() {
406        if (outputWriter != null) {
407            outputWriter.println("</session>");
408            outputWriter.flush();
409            outputWriter.close();
410            outputWriter = null;
411        }
412    }
413
414    /**
415     * <p>
416     * this method moves old logfiles of the same client resisting in the wrong old directory
417     * structure to the new one.
418     * </p>
419     *
420     * @param oldLogDir the old log directory
421     * @param newLogDir the new log directory
422     */
423    private void handleOldLogFiles(File oldLogDir, File newLogDir) {
424        if (oldLogDir.exists() && oldLogDir.isDirectory()) {
425            boolean allFilesRenamed = true;
426            for (File oldLogFile : oldLogDir.listFiles()) {
427                allFilesRenamed &= oldLogFile.renameTo(new File(newLogDir, oldLogFile.getName()));
428            }
429           
430            if (allFilesRenamed) {
431                if (!oldLogDir.delete()) {
432                    Console.printerrln("could not move old file directory structure to new one");
433                }
434            }
435        }
436    }
437
438    /* (non-Javadoc)
439     * @see de.ugoe.cs.autoquest.htmlmonitor.HtmlMonitorComponent#stop()
440     */
441    @Override
442    public synchronized void stop() {
443        closeLogWriter();
444        rotateLogFile();
445
446        lastUpdate = System.currentTimeMillis();
447    }
448
449    /**
450     * <p>
451     * return the time stamp of the last activity that happened on this writer.
452     * </p>
453     *
454     * @return as described
455     */
456    public long getLastUpdate() {
457        return lastUpdate;
458    }
459}
Note: See TracBrowser for help on using the repository browser.