1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.esigate.parser.future;
17
18 import java.io.IOException;
19 import java.util.*;
20 import java.util.regex.Matcher;
21 import java.util.regex.Pattern;
22
23 import org.apache.http.HttpResponse;
24 import org.esigate.HttpErrorPage;
25 import org.esigate.impl.DriverRequest;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29
30
31
32
33
34
35
36 public class FutureParser {
37 private static final Logger LOG = LoggerFactory.getLogger(FutureParser.class);
38 private final Pattern pattern;
39 private final List<FutureElementType> elementTypes;
40 private DriverRequest httpRequest;
41 private HttpResponse httpResponse;
42 private Map<String, Object> data = null;
43
44
45
46
47
48
49
50
51
52 public FutureParser(Pattern pattern, FutureElementType... elementTypes) {
53 this.pattern = pattern;
54 this.elementTypes = new ArrayList<>(elementTypes.length + 1);
55 Collections.addAll(this.elementTypes, elementTypes);
56 this.elementTypes.add(UnknownElement.TYPE);
57 }
58
59
60
61
62
63
64
65
66
67
68
69 public void parse(CharSequence in, FutureAppendable out) throws IOException, HttpErrorPage {
70 FutureParserContextImpl ctx = new FutureParserContextImpl(out, this.httpRequest, this.httpResponse, this.data);
71 Matcher matcher = this.pattern.matcher(in);
72 int currentPosition = 0;
73 while (matcher.find()) {
74 String tag = matcher.group();
75 ctx.characters(new CharSequenceFuture(in.subSequence(currentPosition, matcher.start())));
76 currentPosition = matcher.end();
77 if (ctx.isCurrentTagEnd(tag)) {
78
79 LOG.info("Processing end tag {}", tag);
80 ctx.endElement(tag);
81 } else {
82
83 LOG.info("Processing start tag {}", tag);
84 FutureElementType type = null;
85 for (FutureElementType t : this.elementTypes) {
86 if (t.isStartTag(tag)) {
87 type = t;
88 break;
89 }
90 }
91 FutureElement element = type.newInstance();
92 ctx.startElement(type, element, tag);
93 if (type.isSelfClosing(tag)) {
94 ctx.endElement(tag);
95 }
96 }
97 }
98
99 ctx.characters(new CharSequenceFuture(in.subSequence(currentPosition, in.length())));
100 }
101
102 public void setHttpRequest(DriverRequest httpRequest) {
103 this.httpRequest = httpRequest;
104 }
105
106 public void setData(String key, Object o) {
107 if (this.data == null) {
108 this.data = new HashMap<>();
109 }
110
111 this.data.put(key, o);
112 }
113
114 }