source: trunk/autoquest-plugin-html/src/main/java/de/ugoe/cs/autoquest/plugin/html/HTMLLogParser.java @ 1354

Last change on this file since 1354 was 1354, checked in by pharms, 10 years ago
  • added support for id replacements
  • Property svn:mime-type set to text/plain
File size: 20.4 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.plugin.html;
16
17import java.io.File;
18import java.io.FileInputStream;
19import java.io.FileNotFoundException;
20import java.io.IOException;
21import java.util.Arrays;
22import java.util.HashMap;
23import java.util.List;
24import java.util.Map;
25import java.util.Properties;
26import java.util.regex.Matcher;
27import java.util.regex.Pattern;
28
29import org.xml.sax.SAXException;
30
31import de.ugoe.cs.autoquest.eventcore.Event;
32import de.ugoe.cs.autoquest.eventcore.IEventType;
33import de.ugoe.cs.autoquest.eventcore.guimodel.GUIModel;
34import de.ugoe.cs.autoquest.eventcore.guimodel.GUIModelException;
35import de.ugoe.cs.autoquest.eventcore.guimodel.IGUIElement;
36import de.ugoe.cs.autoquest.plugin.html.eventcore.HTMLEventTypeFactory;
37import de.ugoe.cs.autoquest.plugin.html.guimodel.HTMLDocumentSpec;
38import de.ugoe.cs.autoquest.plugin.html.guimodel.HTMLGUIElement;
39import de.ugoe.cs.autoquest.plugin.html.guimodel.HTMLGUIElementSpec;
40import de.ugoe.cs.autoquest.plugin.html.guimodel.HTMLPageElement;
41import de.ugoe.cs.autoquest.plugin.html.guimodel.HTMLPageElementSpec;
42import de.ugoe.cs.autoquest.plugin.html.guimodel.HTMLServerSpec;
43
44/**
45 * <p>
46 * This class provides the functionality to parse XML log files generated by the HTMLMonitor of
47 * AutoQUEST. The result of parsing a file is a collection of event sequences and a GUI model
48 * </p>
49 *
50 * @author Fabian Glaser, Patrick Harms
51 * @version 1.0
52 *
53 */
54public class HTMLLogParser extends AbstractDefaultLogParser {
55   
56    /**
57     * <p>
58     * the pattern used for parsing HTML GUI element paths
59     * </p>
60     */
61    private Pattern htmlElementPattern =
62        Pattern.compile("(\\w+)(\\[(\\d+)\\]|\\(htmlId=([\\w-]+)\\))");
63   
64    /**
65     * <p>
66     * the pattern used for parsing parsing parameters
67     * </p>
68     */
69    private Pattern htmlElementSpecPattern =
70        Pattern.compile("(\\w+)(\\[(\\d+)\\]|\\(htmlId=([\\w-#]+)\\))?");
71   
72    /**
73     * <p>
74     * parameters to influence parsing
75     * </p>
76     */
77    private Map<String, List<String>> parseParams;
78
79    /**
80     * <p>
81     * a map containing replacement specifications for ids of GUI elements
82     * </p>
83     */
84    private Map<String, String> idReplacements;
85
86    /**
87     * <p>
88     * TODO: comment
89     * </p>
90     *
91     * @param parseParams
92     */
93    public HTMLLogParser(Map<String, List<String>> parseParams) {
94        this.parseParams = parseParams;
95       
96        for (String paramKey : parseParams.keySet()) {
97            if (!"clearId".equals(paramKey) && !"clearIndex".equals(paramKey) &&
98                !"idReplacements".equals(paramKey))
99            {
100                throw new IllegalArgumentException("unknown parse parameter key " + paramKey);
101            }
102        }
103    }
104
105    /* (non-Javadoc)
106     * @see de.ugoe.cs.autoquest.plugin.html.AbstractDefaultLogParser#handleGUIElement(String, Map)
107     */
108    @Override
109    protected boolean handleGUIElement(String id, Map<String, String> parameters)
110        throws SAXException
111    {
112        HTMLGUIElementSpec specification = null;
113       
114        String parentId = parameters.get("parent");
115        HTMLGUIElement parent = (HTMLGUIElement) super.getGUIElementTree().find(parentId);
116
117        if (parameters.containsKey("host")) {
118            // this is a server specification
119            int port = 80;
120            String portStr = parameters.get("port");
121           
122            if (portStr != null) {
123                port = Integer.parseInt(portStr);
124            }
125           
126            specification = new HTMLServerSpec(parameters.get("host"), port);
127        }
128        else if (parameters.containsKey("path")) {
129            // this is a document specification
130           
131            if (parent != null) {
132                if (!(parent.getSpecification() instanceof HTMLServerSpec)) {
133                    throw new SAXException
134                        ("invalid log: parent GUI element of a document is not of type server");
135                }
136               
137                specification = new HTMLDocumentSpec
138                    ((HTMLServerSpec) parent.getSpecification(), parameters.get("path"),
139                     parameters.get("query"), parameters.get("title"));
140            }
141            else if (parentId == null) {
142                throw new SAXException("invalid log: a document has no parent id");
143            }
144        }
145        else if (parameters.containsKey("tagname")) {
146            String tagName = parameters.get("tagname");
147           
148            if (!tagNameMustBeConsidered(tagName)) {
149                return true;
150            }
151
152            if (parent != null) {
153                IGUIElement document = parent;
154               
155                while ((document != null) &&
156                       (!(document.getSpecification() instanceof HTMLDocumentSpec)))
157                {
158                    document = document.getParent();
159                }
160               
161                if (document == null) {
162                    throw new SAXException
163                        ("invalid log: parent hierarchy of a page element does not contain a " +
164                         "document");
165                }
166               
167                int index = -1;
168                String indexStr = parameters.get("index");
169
170                if ((indexStr != null) && (!"".equals(indexStr))) {
171                    index = Integer.parseInt(indexStr);
172                }
173               
174                String htmlId = parameters.get("htmlid");
175               
176                if (clearIndex(tagName, index, htmlId, parent)) {
177                    index = -1;
178                }
179               
180                String idReplacement = replaceHTMLId(tagName, index, htmlId, parent);
181                if (idReplacement != null) {
182                    htmlId = idReplacement;
183                }
184                else if (clearHTMLId(tagName, index, htmlId, parent)) {
185                    htmlId = null;
186                }
187               
188                if ((htmlId == null) && (index == -1)) {
189                    // set at least a default index, if all is to be ignored.
190                    index = 0;
191                }
192
193                specification = new HTMLPageElementSpec
194                    ((HTMLDocumentSpec) document.getSpecification(), tagName, htmlId, index);
195               
196            }
197            else if (parentId == null) {
198                throw new SAXException("invalid log: a page element has no parent id");
199            }
200        }
201        else {
202            throw new SAXException("invalid log: unknown GUI element");
203        }
204
205        if (specification != null) {
206            try {
207                super.getGUIElementTree().add(id, parentId, specification);
208            }
209            catch (GUIModelException e) {
210                throw new SAXException("could not handle GUI element with id " +
211                                       id + ": " + e.getMessage(), e);
212            }
213            return true;
214        }
215        else {
216            return false;
217        }
218    }
219
220    /**
221     * <p>
222     * TODO: comment
223     * </p>
224     *
225     * @param tagName
226     * @param parent
227     * @return
228     */
229    private boolean clearIndex(String tagName, int index, String id, HTMLGUIElement parent) {
230        return clearSomething("clearIndex", tagName, index, id, parent);
231    }
232
233    /**
234     * <p>
235     * TODO: comment
236     * </p>
237     *
238     * @param tagName
239     * @param index
240     * @param htmlId
241     * @param parent
242     * @return
243     */
244    private String replaceHTMLId(String tagName, int index, String htmlId, HTMLGUIElement parent)
245        throws SAXException
246    {
247        if ((idReplacements == null) && (parseParams.containsKey("idReplacements"))) {
248            idReplacements = new HashMap<String, String>();
249            for (String fileName : parseParams.get("idReplacements")) {
250                Properties props = new Properties();
251                try {
252                    props.load(new FileInputStream(new File(fileName)));
253                }
254                catch (FileNotFoundException e) {
255                    throw new SAXException("could not find file " + fileName, e);
256                }
257                catch (IOException e) {
258                    throw new SAXException("error reading file " + fileName, e);
259                }
260               
261                for (Map.Entry<Object, Object> entry : props.entrySet()) {
262                    idReplacements.put((String) entry.getKey(), (String) entry.getValue());
263                }
264            }
265        }
266       
267        if (idReplacements != null) {
268            for (Map.Entry<String, String> replacementSpec : idReplacements.entrySet()) {
269                String tagSpec = replacementSpec.getKey();
270
271                if (tagSpec.startsWith("/")) {
272                    throw new IllegalArgumentException("can not handle absolute specifications");
273                }
274                else if (tagSpec.endsWith("/")) {
275                    throw new IllegalArgumentException("specifications may not end with a /");
276                }
277
278                String[] tagSpecs = tagSpec.split("/");
279
280                if (tagMatchesTagSpec(tagName, index, htmlId, parent, tagSpecs)) {
281                    return replacementSpec.getValue();
282                }
283            }
284        }
285       
286        return null;
287    }
288
289    /**
290     * <p>
291     * TODO: comment
292     * </p>
293     *
294     * @param tagName
295     * @param parent
296     * @return
297     */
298    private boolean clearHTMLId(String tagName, int index, String id, HTMLGUIElement parent) {
299        return clearSomething("clearId", tagName, index, id, parent);
300    }
301   
302    /**
303     * <p>
304     * TODO: comment
305     * </p>
306     *
307     * @param tagName
308     * @param parent
309     * @return
310     */
311    private boolean clearSomething(String         parseParamId,
312                                   String         tagName,
313                                   int            index,
314                                   String         id,
315                                   HTMLGUIElement parent)
316    {
317        if (parseParams.containsKey(parseParamId)) {
318            for (String spec : parseParams.get(parseParamId)) {
319                // determine the specification parts
320                if (spec.startsWith("/")) {
321                    throw new IllegalArgumentException("can not handle absolute specifications");
322                }
323                else if (spec.endsWith("/")) {
324                    throw new IllegalArgumentException("specifications may not end with a /");
325                }
326               
327                String[] tagSpecs = spec.split("/");
328               
329                if (tagMatchesTagSpec(tagName, index, id, parent, tagSpecs)) {
330                    return true;
331                }
332            }
333        }
334       
335        return false;
336    }
337
338    /**
339     * <p>
340     * TODO: comment
341     * </p>
342     *
343     * @param tagName
344     * @param parent
345     * @param spec
346     * @return
347     */
348    private boolean tagMatchesTagSpec(String         tagName,
349                                      int            index,
350                                      String         id,
351                                      HTMLGUIElement parent,
352                                      String[]       tagSpecs)
353    {
354       
355        if (tagSpecs.length > 0) {
356            Matcher matcher = htmlElementSpecPattern.matcher(tagSpecs[tagSpecs.length - 1]);
357           
358            if (!matcher.matches()) {
359                throw new IllegalArgumentException
360                    ("illegal tag specification " + tagSpecs[tagSpecs.length - 1]);
361            }
362           
363            if (!tagName.equals(matcher.group(1))) {
364                return false;
365            }
366           
367            String idCondition = matcher.group(4);
368           
369            if (idCondition != null) {
370                if (!idCondition.equals(id)) {
371                    // check if the id condition would match with ignoring specific characters
372                    if ((id != null) && (idCondition.indexOf('#') > -1)) {
373                        // first of all, the length must match
374                        if (idCondition.length() != id.length()) {
375                            return false;
376                        }
377                       
378                        for (int i = 0; i < idCondition.length(); i++) {
379                            if ((idCondition.charAt(i) != '#') &&
380                                (idCondition.charAt(i) != id.charAt(i)))
381                            {
382                                // if there is a character that is neither ignored not matches
383                                // the condition at a specific position, return "no match"
384                                return false;
385                            }
386                        }
387                       
388                    }
389                    else {
390                        // no condition ignoring specific characters
391                        return false;
392                    }
393                }
394            }
395           
396            String indexCondition = matcher.group(3);
397           
398            if (indexCondition != null) {
399                try {
400                    if (index != Integer.parseInt(indexCondition)) {
401                        return false;
402                    }
403                }
404                catch (NumberFormatException e) {
405                    throw new IllegalArgumentException
406                        ("illegal tag index specification " + indexCondition, e);
407                }
408            }
409           
410            if (tagSpecs.length > 1) {
411                if (parent instanceof HTMLPageElement) {
412                    return tagMatchesTagSpec(((HTMLPageElement) parent).getTagName(),
413                                             ((HTMLPageElement) parent).getIndex(),
414                                             ((HTMLPageElement) parent).getHtmlId(),
415                                             (HTMLGUIElement) parent.getParent(),
416                                             Arrays.copyOfRange(tagSpecs, 0, tagSpecs.length - 1));
417                }
418                else {
419                    throw new IllegalArgumentException
420                        ("specification matches documents or servers. This is not supported yet.");
421                }
422            }
423            else {
424                return true;
425            }
426        }
427        else {
428            return true;
429        }
430    }
431
432    /* (non-Javadoc)
433     * @see de.ugoe.cs.autoquest.plugin.html.AbstractDefaultLogParser#handleEvent(String, Map)
434     */
435    @Override
436    protected boolean handleEvent(String type, Map<String, String> parameters) throws SAXException {
437        String targetId = parameters.get("target");
438       
439        if (targetId == null) {
440            if (parseParams.size() != 0) {
441                throw new SAXException
442                    ("old log file versions can not be parsed with parse parameters");
443            }
444           
445            String targetDocument = parameters.get("targetDocument");
446            String targetDOMPath = parameters.get("targetDOMPath");
447           
448            if ((targetDocument == null) || (targetDOMPath == null)) {
449                throw new SAXException("event has no target defined");
450            }
451           
452            targetId = determineTargetId(targetDocument, targetDOMPath);
453           
454            if (targetId == null) {
455                // the target id can not be determined yet
456                return false;
457            }
458        }
459       
460        IGUIElement target = super.getGUIElementTree().find(targetId);
461       
462        if (target == null) {
463            // event not processible yet
464            return false;
465        }
466
467        IEventType eventType =
468            HTMLEventTypeFactory.getInstance().getEventType(type, parameters, target);
469       
470        if (eventType != null) {
471            Event event = new Event(eventType, target);
472
473            String timestampStr = parameters.get("timestamp");
474       
475            if (timestampStr != null) {
476                event.setTimestamp(Long.parseLong(timestampStr));
477            }
478
479            ((HTMLGUIElement) event.getTarget()).markUsed();
480       
481            super.addToSequence(event);
482        }
483        // else ignore unknown event type
484
485        return true;
486    }
487
488    /**
489     * <p>
490     * used to determine the id of a target denoted by an event. This is only required for older
491     * document formats. The new formats use concrete ids.
492     * </p>
493     */
494    private String determineTargetId(String targetDocument, String targetDOMPath)
495        throws SAXException
496    {
497        IGUIElement document = super.getGUIElementTree().find(targetDocument);
498       
499        if (document == null) {
500            return null;
501        }
502       
503        if (!(document.getSpecification() instanceof HTMLDocumentSpec)) {
504            throw new SAXException("an id that should refer to an HTML document refers to" +
505                                   "something else");
506        }
507       
508        GUIModel model = super.getGUIElementTree().getGUIModel();
509        IGUIElement child = document;
510        String[] pathElements = targetDOMPath.split("/");
511        int pathIndex = 0;
512       
513        HTMLPageElementSpec compareSpec;
514        String tagName;
515        int index;
516        String htmlId;
517       
518        while ((pathIndex < pathElements.length) && (child != null)) {
519            if ((pathElements[pathIndex] != null) && (!"".equals(pathElements[pathIndex]))) {           
520                Matcher matcher = htmlElementPattern.matcher(pathElements[pathIndex]);
521                if (!matcher.matches()) {
522                    throw new SAXException
523                        ("could not parse target DOM path element " + pathElements[pathIndex]);
524                }
525
526                tagName = matcher.group(1);
527                String indexStr = matcher.group(3);
528                htmlId = matcher.group(4);
529
530                index = -1;
531                if ((indexStr != null) && (!"".equals(indexStr))) {
532                    index = Integer.parseInt(indexStr);
533                }
534
535                compareSpec = new HTMLPageElementSpec
536                    ((HTMLDocumentSpec) document.getSpecification(), tagName, htmlId, index);
537
538                List<IGUIElement> children = model.getChildren(child);
539                child = null;
540
541                for (IGUIElement candidate : children) {
542                    if (compareSpec.getSimilarity(candidate.getSpecification())) {
543                        child = candidate;
544                        break;
545                    }
546                }
547            }
548           
549            pathIndex++;
550        }
551       
552        if (child != null) {
553            return super.getGUIElementTree().find(child);
554        }
555        else {
556            return null;
557        }
558    }
559
560    /**
561     * <p>
562     * checks if tags with the provided name must be handled in the GUI model. As an example,
563     * it is not necessary to handle "head" tags and anything included in them.
564     * </p>
565     *
566     * @param tagName the tag name to check
567     *
568     * @return true, if the tag must be considered, false else
569     */
570    private boolean tagNameMustBeConsidered(String tagName) {
571        if (!tagName.startsWith("input_")) {
572            for (int i = 0; i < tagName.length(); i++) {
573                // all known HTML tags are either letters or digits, but nothing else. Any GUI model
574                // containing something different is proprietary and, therefore, ignored.
575                if (!Character.isLetterOrDigit(tagName.charAt(i))) {
576                    return false;
577                }
578            }
579        }
580       
581        return
582            !"head".equals(tagName) && !"title".equals(tagName) && !"script".equals(tagName) &&
583            !"style".equals(tagName) && !"link".equals(tagName) && !"meta".equals(tagName) &&
584            !"iframe".equals(tagName) && !"input_hidden".equals(tagName) &&
585            !"option".equals(tagName) && !"tt".equals(tagName) && !"br".equals(tagName) &&
586            !"colgroup".equals(tagName) && !"col".equals(tagName) && !"hr".equals(tagName) &&
587            !"param".equals(tagName) && !"sfmsg".equals(tagName);
588
589    }
590
591}
Note: See TracBrowser for help on using the repository browser.