Debian Codegraph @

native/jpype_module/src/main/java/org/jpype/html/HtmlTreeHandler.java

raw symbols SCIP
1 /* ****************************************************************************
2 Licensed under the Apache License, Version 2.0 (the "License");
3 you may not use this file except in compliance with the License.
4 You may obtain a copy of the License at
5
6 http://www.apache.org/licenses/LICENSE-2.0
7
8 Unless required by applicable law or agreed to in writing, software
9 distributed under the License is distributed on an "AS IS" BASIS,
10 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 See the License for the specific language governing permissions and
12 limitations under the License.
13
14 See NOTICE file for details.
15 **************************************************************************** */
16 package org.jpype.html;
17
18 import java.util.LinkedList;
19 import java.util.ListIterator;
20 import javax.xml.parsers.DocumentBuilder;
21 import javax.xml.parsers.DocumentBuilderFactory;
22 import javax.xml.parsers.ParserConfigurationException;
23 import org.w3c.dom.Attr;
24 import org.w3c.dom.Document;
25 import org.w3c.dom.Element;
26 import org.w3c.dom.NamedNodeMap;
27 import org.w3c.dom.Node;
28
29 /**
30 * HTML document handler which creates an HTML tree.
31 */
32 public class HtmlTreeHandler implements HtmlHandler
33 {
34
35 final Document root;
36 LinkedList<Element> elementStack = new LinkedList<>();
37 AttrParser attrParser;
38 Node current;
39 int errors = 0;
40
41 public HtmlTreeHandler()
42 {
43 try
44 {
45 DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
46 root = db.newDocument();
47 current = root;
48 attrParser = new AttrParser(root);
49 } catch (ParserConfigurationException ex)
50 {
51 throw new RuntimeException(ex);
52 }
53 }
54
55 private String lastNodeName()
56 {
57 if (this.elementStack.isEmpty())
58 return "";
59 return this.elementStack.getLast().getNodeName();
60 }
61
62 @Override
63 public void startElement(String name, String attr)
64 {
65 name = name.toLowerCase().trim();
66 String attr0 = attr;
67
68 // Html has irregular end rules.
69 while (Html.OPTIONAL_ELEMENTS.contains(name))
70 {
71 String close = lastNodeName() + ":" + name;
72 if (Html.OPTIONAL_CLOSE.contains(close))
73 {
74 // System.out.print("AUTO ");
75 this.endElement(lastNodeName());
76 } else
77 break;
78 }
79
80 // System.out.println(this.elementStack.size() + " " + name + " : " + attr);
81 Element elem;
82 try
83 {
84 elem = root.createElement(name);
85 } catch (Exception ex)
86 {
87 throw new RuntimeException("Fail to create node '" + name + "'", ex);
88 }
89 if (attr != null)
90 {
91 for (Attr a : attrParser.parse(attr))
92 elem.setAttributeNode(a);
93 }
94 current.appendChild(elem);
95 if (Html.VOID_ELEMENTS.contains(name))
96 return;
97 current = elem;
98 elementStack.add(elem);
99 }
100
101 public String getPath()
102 {
103 StringBuilder path = new StringBuilder();
104 for (Element s : this.elementStack)
105 {
106 path.append("/");
107 path.append(s.getNodeName());
108 NamedNodeMap attrs = s.getAttributes();
109 if (attrs.getLength() > 0)
110 {
111 path.append('[');
112 for (int i = 0; i < attrs.getLength(); ++i)
113 {
114 Attr item = (Attr) attrs.item(i);
115 path.append(item.getName());
116 path.append('=');
117 path.append(item.getValue());
118 path.append(' ');
119 }
120 path.append(']');
121 }
122 }
123 return path.toString();
124 }
125
126 @Override
127 public void endElement(String name)
128 {
129 name = name.toLowerCase().trim();
130 if (elementStack.isEmpty())
131 throw new RuntimeException("Empty stack");
132 Element last = elementStack.getLast();
133 // Handle auto class tags
134 while (!last.getNodeName().equals(name) && Html.OPTIONAL_ELEMENTS.contains(last.getNodeName()))
135 {
136 // System.out.print("AUTO2 ");
137 endElement(last.getNodeName());
138 last = elementStack.getLast();
139 }
140 // System.out.println(this.elementStack.size() - 1 + " ~" + name);
141 if (!last.getNodeName().equals(name))
142 {
143 errors++;
144
145 // Try to deal with unclosed tags gracefully.
146 ListIterator<Element> iter = this.elementStack.listIterator(this.elementStack.size() - 1);
147 int i = 0;
148 while (iter.hasNext())
149 {
150 Element prev = iter.previous();
151 if (prev.getNodeName().equals(name))
152 break;
153 i++;
154 }
155 if (iter.hasPrevious())
156 {
157 for (int j = 0; j < i; j++)
158 {
159 System.err.println("Ignoring missing close tag " + last.getNodeName() + ", got " + name + " at " + getPath());
160 this.endElement(last.getNodeName());
161 }
162 } else if (errors > 3)
163 throw new RuntimeException("mismatch element " + name
164 + " " + last.getNodeName() + " at " + getPath());
165 else
166 {
167 System.err.println("Ignoring mismatched element " + name
168 + " " + last.getNodeName() + " at " + getPath());
169 return;
170 }
171 }
172 elementStack.removeLast();
173 if (elementStack.isEmpty())
174 current = root;
175 else
176 current = elementStack.getLast();
177 }
178
179 @Override
180 public void comment(String contents)
181 {
182 if (contents.equals(">"))
183 throw new RuntimeException();
184 current.appendChild(root.createComment(contents));
185 }
186
187 @Override
188 public void text(String text)
189 {
190 // System.out.println(" TEXT " + text);
191 if (text.length() == 0)
192 return;
193 if (text.contains("<"))
194 throw new RuntimeException("bad text `" + text + "` at " + getPath());
195 if (current == root)
196 return;
197 current.appendChild(root.createTextNode(text));
198 }
199
200 @Override
201 public void cdata(String text)
202 {
203 current.appendChild(root.createCDATASection(text));
204 }
205
206 @Override
207 public void startDocument()
208 {
209 }
210
211 @Override
212 public void endDocument()
213 {
214 }
215
216 @Override
217 public Object getResult()
218 {
219 return root;
220 }
221
222 @Override
223 public void directive(String content)
224 {
225 int i = content.indexOf(" ");
226 current.appendChild(root.createProcessingInstruction(content.substring(0, i),
227 content.substring(i).trim()));
228 }
229
230 }