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

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