001package org.hl7.fhir.utilities.xhtml; 002 003/* 004 Copyright (c) 2011+, HL7, Inc. 005 All rights reserved. 006 007 Redistribution and use in source and binary forms, with or without modification, 008 are permitted provided that the following conditions are met: 009 010 * Redistributions of source code must retain the above copyright notice, this 011 list of conditions and the following disclaimer. 012 * Redistributions in binary form must reproduce the above copyright notice, 013 this list of conditions and the following disclaimer in the documentation 014 and/or other materials provided with the distribution. 015 * Neither the name of HL7 nor the names of its contributors may be used to 016 endorse or promote products derived from this software without specific 017 prior written permission. 018 019 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 020 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 021 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 022 IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 023 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 024 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 025 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 026 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 027 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 028 POSSIBILITY OF SUCH DAMAGE. 029 030 */ 031 032 033 034import java.io.FileOutputStream; 035import java.io.IOException; 036import java.io.OutputStream; 037import java.io.OutputStreamWriter; 038import java.io.StringWriter; 039import java.io.Writer; 040import java.util.List; 041import java.util.Set; 042 043import org.hl7.fhir.utilities.Utilities; 044import org.hl7.fhir.utilities.xml.IXMLWriter; 045import org.w3c.dom.Element; 046 047public class XhtmlComposer { 048 049 protected static Set<String> BLOCK_NAMES = Set.of("li", "ul", "ol", "tr", "td", "th", "div", "table"); 050 public static final String XHTML_NS = "http://www.w3.org/1999/xhtml"; 051 private boolean pretty; 052 private boolean xml; 053 private boolean autoLinks; 054 055 public static final boolean XML = true; 056 public static final boolean HTML = false; 057 058 public XhtmlComposer(boolean xml, boolean pretty) { 059 super(); 060 this.pretty = pretty; 061 this.xml = xml; 062 } 063 064 public XhtmlComposer(boolean xml) { 065 super(); 066 this.pretty = false; 067 this.xml = xml; 068 } 069 070 private Writer dst; 071 072 public String compose(XhtmlDocument doc) throws IOException { 073 if (!xml && !pretty) { 074 breakBlocksWithLines(doc); 075 } 076 StringWriter sdst = new StringWriter(); 077 dst = sdst; 078 composeDoc(doc); 079 return sdst.toString(); 080 } 081 082 private void breakBlocksWithLines(XhtmlNode node) { 083 if (node.hasChildren()) { 084 breakBlocksWithLines(node.getChildNodes()); 085 } 086 } 087 088 private void breakBlocksWithLines(List<XhtmlNode> list) { 089 for (int i = list.size() -1; i > 0; i--) { 090 XhtmlNode node = list.get(i); 091 if (node.getNodeType() == NodeType.Element && BLOCK_NAMES.contains(node.getName())) { 092 XhtmlNode prev = list.get(i-1); 093 if (prev.getNodeType() != NodeType.Text || prev.getContent() == null || !(prev.getContent().endsWith("\r") || prev.getValue().endsWith("\n"))) { 094 list.add(i, new XhtmlNode(NodeType.Text).setContent("\r\n")); 095 } 096 } 097 breakBlocksWithLines(node); 098 } 099 } 100 101 public String compose(XhtmlNode node) throws IOException { 102 if (!xml && !pretty) { 103 breakBlocksWithLines(node); 104 } 105 StringWriter sdst = new StringWriter(); 106 dst = sdst; 107 writeNode("", node, false); 108 return sdst.toString(); 109 } 110 111 public String compose(List<XhtmlNode> nodes) throws IOException { 112 if (!xml && !pretty) { 113 breakBlocksWithLines(nodes); 114 } 115 StringWriter sdst = new StringWriter(); 116 dst = sdst; 117 for (XhtmlNode node : nodes) { 118 writeNode("", node, false); 119 } 120 return sdst.toString(); 121 } 122 123 public void compose(OutputStream stream, XhtmlDocument doc) throws IOException { 124 byte[] bom = new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF }; 125 stream.write(bom); 126 dst = new OutputStreamWriter(stream, "UTF-8"); 127 composeDoc(doc); 128 dst.flush(); 129 } 130 131 private void composeDoc(XhtmlDocument doc) throws IOException { 132 if (!xml) { 133 breakBlocksWithLines(doc); 134 } 135 // headers.... 136 // dst.append("<html>" + (pretty ? "\r\n" : "")); 137 for (XhtmlNode c : doc.getChildNodes()) { 138 writeNode(" ", c, false); 139 } 140 // dst.append("</html>" + (pretty ? "\r\n" : "")); 141 } 142 143 private void writeNode(String indent, XhtmlNode node, boolean noPrettyOverride) throws IOException { 144 if (node.getNodeType() == NodeType.Comment) { 145 writeComment(indent, node, noPrettyOverride); 146 } else if (node.getNodeType() == NodeType.DocType) { 147 writeDocType(node); 148 } else if (node.getNodeType() == NodeType.Instruction) { 149 writeInstruction(node); 150 } else if (node.getNodeType() == NodeType.Element) { 151 writeElement(indent, node, noPrettyOverride); 152 } else if (node.getNodeType() == NodeType.Document) { 153 writeDocument(indent, node); 154 } else if (node.getNodeType() == NodeType.Text) { 155 writeText(node); 156 } else if (node.getNodeType() == null) { 157 throw new IOException("Null node type"); 158 } else { 159 throw new IOException("Unknown node type: "+node.getNodeType().toString()); 160 } 161 } 162 163 private boolean isValidUrlChar(char c) { 164 return Character.isAlphabetic(c) || Character.isDigit(c) || Utilities.existsInList(c, ';', ',', '/', '?', ':', '@', '&', '=', '+', '$', '-', '_', '.', '!', '~', '*', '\'', '(', ')'); 165 } 166 167 private void writeText(XhtmlNode node) throws IOException { 168 String src = node.getContent(); 169 int i = 0; 170 while (i < src.length()) { 171 int ci = src.codePointAt(i); 172 if (ci > 65535) { 173 dst.append("&#x"); 174 dst.append(Integer.toHexString(ci).toUpperCase()); 175 dst.append(";"); 176 i += Character.charCount(ci); 177 } else { 178 char c = (char) ci; 179 if (autoLinks && c == 'h' && Utilities.startsWithInList(src.substring(i), "http://", "https://")) { 180 int j = i; 181 while (i < src.length() && isValidUrlChar(src.charAt(i))) { 182 i++; 183 } 184 String url = src.substring(j, i); 185 if (url.endsWith(".") || url.endsWith(",")) { 186 i--; 187 url = url.substring(0, url.length()-1); 188 } 189 url = Utilities.escapeXml(url); 190 dst.append("<a href=\""+url+"\">"+ url +"</a>"); 191 } else { 192 i++; 193 if (c == '&') { 194 dst.append("&"); 195 } else if (c == '<') { 196 dst.append("<"); 197 } else if (c == '>') { 198 dst.append(">"); 199 } else if (xml) { 200 if (c == '"') 201 dst.append("""); 202 else 203 dst.append(c); 204 } else { 205 if (c == XhtmlNode.NBSP.charAt(0)) 206 dst.append(" "); 207 else if (c == (char) 0xA7) 208 dst.append("§"); 209 else if (c == (char) 169) 210 dst.append("©"); 211 else if (c == (char) 8482) 212 dst.append("™"); 213 else if (c == (char) 956) 214 dst.append("μ"); 215 else if (c == (char) 174) 216 dst.append("®"); 217 else 218 dst.append(c); 219 } 220 } 221 } 222 } 223 } 224 225 boolean isTwoCharUnicodeCodePoint(char c1, char c2) { 226 return false; 227 } 228 229 private void writeComment(String indent, XhtmlNode node, boolean noPrettyOverride) throws IOException { 230 dst.append(indent + "<!-- " + node.getContent().trim() + " -->" + (pretty && !noPrettyOverride ? "\r\n" : "")); 231 } 232 233 private void writeDocType(XhtmlNode node) throws IOException { 234 dst.append("<!" + node.getContent() + ">\r\n"); 235 } 236 237 private void writeInstruction(XhtmlNode node) throws IOException { 238 dst.append("<?" + node.getContent() + "?>\r\n"); 239 } 240 241 private String escapeHtml(String s) { 242 if (s == null || s.equals("")) 243 return null; 244 StringBuilder b = new StringBuilder(); 245 for (char c : s.toCharArray()) 246 if (c == '<') 247 b.append("<"); 248 else if (c == '>') 249 b.append(">"); 250 else if (c == '"') 251 b.append("""); 252 else if (c == '&') 253 b.append("&"); 254 else 255 b.append(c); 256 return b.toString(); 257 } 258 259 private String attributes(XhtmlNode node) { 260 StringBuilder s = new StringBuilder(); 261 for (String n : node.getAttributes().keySet()) 262 s.append(" " + n + "=\"" + escapeHtml(node.getAttributes().get(n)) + "\""); 263 return s.toString(); 264 } 265 266 private void writeElement(String indent, XhtmlNode node, boolean noPrettyOverride) throws IOException { 267 if (!pretty || noPrettyOverride) 268 indent = ""; 269 270 boolean concise = false; 271 if (!node.hasChildren()) { 272 if (this.xml) { 273 concise = true; 274 } else if (!(node.hasEmptyExpanded() && node.getEmptyExpanded()) && 275 Utilities.existsInList(node.getName(), "area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr")) { 276 // In HTML5, only these elements can self-close 277 // https://developer.mozilla.org/en-US/docs/Glossary/Void_element 278 concise = true; 279 } 280 } 281 282 if (concise) 283 dst.append(indent + "<" + node.getName() + attributes(node) + "/>" + (pretty && !noPrettyOverride ? "\r\n" : "")); 284 else { 285 boolean act = node.allChildrenAreText(); 286 if (act || !pretty || noPrettyOverride) 287 dst.append(indent + "<" + node.getName() + attributes(node)+">"); 288 else 289 dst.append(indent + "<" + node.getName() + attributes(node) + ">\r\n"); 290 if (node.getName() == "head" && node.getElement("meta") == null) 291 dst.append(indent + " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>" + (pretty && !noPrettyOverride ? "\r\n" : "")); 292 293 if (act && "script".equals(node.getName())) { 294 dst.append(node.allText()); 295 } else { 296 for (XhtmlNode c : node.getChildNodes()) 297 writeNode(indent + " ", c, noPrettyOverride || node.isNoPretty()); 298 } 299 if (act) 300 dst.append("</" + node.getName() + ">" + (pretty && !noPrettyOverride ? "\r\n" : "")); 301 else if (node.getChildNodes().get(node.getChildNodes().size() - 1).getNodeType() == NodeType.Text) 302 dst.append((pretty && !noPrettyOverride ? "\r\n"+ indent : "") + "</" + node.getName() + ">" + (pretty && !noPrettyOverride ? "\r\n" : "")); 303 else 304 dst.append(indent + "</" + node.getName() + ">" + (pretty && !noPrettyOverride ? "\r\n" : "")); 305 } 306 } 307 308 private void writeDocument(String indent, XhtmlNode node) throws IOException { 309 indent = ""; 310 for (XhtmlNode c : node.getChildNodes()) 311 writeNode(indent, c, false); 312 } 313 314 315 public void compose(IXMLWriter xml, XhtmlNode node) throws IOException { 316 compose(xml, node, false); 317 } 318 319 public void compose(IXMLWriter xml, XhtmlNode node, boolean noPrettyOverride) throws IOException { 320 if (node.getNodeType() == NodeType.Comment) 321 xml.comment(node.getContent(), pretty && !noPrettyOverride); 322 else if (node.getNodeType() == NodeType.Element) 323 composeElement(xml, node, noPrettyOverride); 324 else if (node.getNodeType() == NodeType.Text) 325 xml.text(node.getContent()); 326 else 327 throw new Error("Unhandled node type: "+node.getNodeType().toString()); 328 } 329 330 private void composeElement(IXMLWriter xml, XhtmlNode node, boolean noPrettyOverride) throws IOException { 331 for (String n : node.getAttributes().keySet()) { 332 if (n.equals("xmlns")) 333 xml.setDefaultNamespace(node.getAttributes().get(n)); 334 else if (n.startsWith("xmlns:")) 335 xml.namespace(n.substring(6), node.getAttributes().get(n)); 336 else 337 xml.attribute(n, node.getAttributes().get(n)); 338 } 339 xml.enter(XHTML_NS, node.getName()); 340 for (XhtmlNode n : node.getChildNodes()) 341 compose(xml, n, noPrettyOverride || node.isNoPretty()); 342 xml.exit(XHTML_NS, node.getName()); 343 } 344 345 public String composePlainText(XhtmlNode x) { 346 StringBuilder b = new StringBuilder(); 347 composePlainText(x, b, false); 348 return b.toString().trim(); 349 } 350 351 private boolean composePlainText(XhtmlNode x, StringBuilder b, boolean lastWS) { 352 if (x.getNodeType() == NodeType.Text) { 353 String s = x.getContent(); 354 if (!lastWS & (s.startsWith(" ") || s.startsWith("\r") || s.startsWith("\n") || s.endsWith("\t"))) { 355 b.append(" "); 356 lastWS = true; 357 } 358 String st = s.trim().replace("\r", " ").replace("\n", " ").replace("\t", " "); 359 while (st.contains(" ")) 360 st = st.replace(" ", " "); 361 if (!Utilities.noString(st)) { 362 b.append(st); 363 lastWS = false; 364 if (!lastWS & (s.endsWith(" ") || s.endsWith("\r") || s.endsWith("\n") || s.endsWith("\t"))) { 365 b.append(" "); 366 lastWS = true; 367 } 368 } 369 return lastWS; 370 } else if (x.getNodeType() == NodeType.Element) { 371 if (x.getName().equals("li")) { 372 b.append("* "); 373 lastWS = true; 374 } 375 376 for (XhtmlNode n : x.getChildNodes()) { 377 lastWS = composePlainText(n, b, lastWS); 378 } 379 if (x.getName().equals("p")) { 380 b.append("\r\n\r\n"); 381 lastWS = true; 382 } 383 if (x.getName().equals("br") || x.getName().equals("li")) { 384 b.append("\r\n"); 385 lastWS = true; 386 } 387 return lastWS; 388 } else 389 return lastWS; 390 } 391 392 public void compose(Element div, XhtmlNode x) { 393 for (XhtmlNode child : x.getChildNodes()) { 394 appendChild(div, child); 395 } 396 } 397 398 private void appendChild(Element e, XhtmlNode node) { 399 if (node.getNodeType() == NodeType.Comment) 400 e.appendChild(e.getOwnerDocument().createComment(node.getContent())); 401 else if (node.getNodeType() == NodeType.DocType) 402 throw new Error("not done yet"); 403 else if (node.getNodeType() == NodeType.Instruction) 404 e.appendChild(e.getOwnerDocument().createProcessingInstruction("", node.getContent())); 405 else if (node.getNodeType() == NodeType.Text) 406 e.appendChild(e.getOwnerDocument().createTextNode(node.getContent())); 407 else if (node.getNodeType() == NodeType.Element) { 408 Element child = e.getOwnerDocument().createElementNS(XHTML_NS, node.getName()); 409 e.appendChild(child); 410 for (String n : node.getAttributes().keySet()) { 411 child.setAttribute(n, node.getAttribute(n)); 412 } 413 for (XhtmlNode c : node.getChildNodes()) { 414 appendChild(child, c); 415 } 416 } else 417 throw new Error("Unknown node type: "+node.getNodeType().toString()); 418 } 419 420 public void compose(OutputStream stream, XhtmlNode x) throws IOException { 421 byte[] bom = new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF }; 422 stream.write(bom); 423 dst = new OutputStreamWriter(stream, "UTF-8"); 424 dst.append("<html><head><link rel=\"stylesheet\" href=\"fhir.css\"/></head><body>\r\n"); 425 writeNode("", x, false); 426 dst.append("</body></html>\r\n"); 427 dst.flush(); 428 } 429 430 public void composeDocument(FileOutputStream f, XhtmlNode xhtml) throws IOException { 431 byte[] bom = new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF }; 432 f.write(bom); 433 dst = new OutputStreamWriter(f, "UTF-8"); 434 writeNode("", xhtml, false); 435 dst.flush(); 436 dst.close(); 437 } 438 439 public String composeEx(XhtmlNode node) { 440 try { 441 return compose(node); 442 } catch (IOException e) { 443 throw new Error(e); 444 } 445 } 446 447 public String compose(XhtmlNodeList nodes) throws IOException { 448 StringWriter sdst = new StringWriter(); 449 dst = sdst; 450 for (XhtmlNode node : nodes) { 451 writeNode("", node, false); 452 } 453 return sdst.toString(); 454 } 455 456 public boolean isAutoLinks() { 457 return autoLinks; 458 } 459 460 public XhtmlComposer setAutoLinks(boolean autoLinks) { 461 this.autoLinks = autoLinks; 462 return this; 463 } 464 465}