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 294 for (XhtmlNode c : node.getChildNodes()) 295 writeNode(indent + " ", c, noPrettyOverride || node.isNoPretty()); 296 if (act) 297 dst.append("</" + node.getName() + ">" + (pretty && !noPrettyOverride ? "\r\n" : "")); 298 else if (node.getChildNodes().get(node.getChildNodes().size() - 1).getNodeType() == NodeType.Text) 299 dst.append((pretty && !noPrettyOverride ? "\r\n"+ indent : "") + "</" + node.getName() + ">" + (pretty && !noPrettyOverride ? "\r\n" : "")); 300 else 301 dst.append(indent + "</" + node.getName() + ">" + (pretty && !noPrettyOverride ? "\r\n" : "")); 302 } 303 } 304 305 private void writeDocument(String indent, XhtmlNode node) throws IOException { 306 indent = ""; 307 for (XhtmlNode c : node.getChildNodes()) 308 writeNode(indent, c, false); 309 } 310 311 312 public void compose(IXMLWriter xml, XhtmlNode node) throws IOException { 313 compose(xml, node, false); 314 } 315 316 public void compose(IXMLWriter xml, XhtmlNode node, boolean noPrettyOverride) throws IOException { 317 if (node.getNodeType() == NodeType.Comment) 318 xml.comment(node.getContent(), pretty && !noPrettyOverride); 319 else if (node.getNodeType() == NodeType.Element) 320 composeElement(xml, node, noPrettyOverride); 321 else if (node.getNodeType() == NodeType.Text) 322 xml.text(node.getContent()); 323 else 324 throw new Error("Unhandled node type: "+node.getNodeType().toString()); 325 } 326 327 private void composeElement(IXMLWriter xml, XhtmlNode node, boolean noPrettyOverride) throws IOException { 328 for (String n : node.getAttributes().keySet()) { 329 if (n.equals("xmlns")) 330 xml.setDefaultNamespace(node.getAttributes().get(n)); 331 else if (n.startsWith("xmlns:")) 332 xml.namespace(n.substring(6), node.getAttributes().get(n)); 333 else 334 xml.attribute(n, node.getAttributes().get(n)); 335 } 336 xml.enter(XHTML_NS, node.getName()); 337 for (XhtmlNode n : node.getChildNodes()) 338 compose(xml, n, noPrettyOverride || node.isNoPretty()); 339 xml.exit(XHTML_NS, node.getName()); 340 } 341 342 public String composePlainText(XhtmlNode x) { 343 StringBuilder b = new StringBuilder(); 344 composePlainText(x, b, false); 345 return b.toString().trim(); 346 } 347 348 private boolean composePlainText(XhtmlNode x, StringBuilder b, boolean lastWS) { 349 if (x.getNodeType() == NodeType.Text) { 350 String s = x.getContent(); 351 if (!lastWS & (s.startsWith(" ") || s.startsWith("\r") || s.startsWith("\n") || s.endsWith("\t"))) { 352 b.append(" "); 353 lastWS = true; 354 } 355 String st = s.trim().replace("\r", " ").replace("\n", " ").replace("\t", " "); 356 while (st.contains(" ")) 357 st = st.replace(" ", " "); 358 if (!Utilities.noString(st)) { 359 b.append(st); 360 lastWS = false; 361 if (!lastWS & (s.endsWith(" ") || s.endsWith("\r") || s.endsWith("\n") || s.endsWith("\t"))) { 362 b.append(" "); 363 lastWS = true; 364 } 365 } 366 return lastWS; 367 } else if (x.getNodeType() == NodeType.Element) { 368 if (x.getName().equals("li")) { 369 b.append("* "); 370 lastWS = true; 371 } 372 373 for (XhtmlNode n : x.getChildNodes()) { 374 lastWS = composePlainText(n, b, lastWS); 375 } 376 if (x.getName().equals("p")) { 377 b.append("\r\n\r\n"); 378 lastWS = true; 379 } 380 if (x.getName().equals("br") || x.getName().equals("li")) { 381 b.append("\r\n"); 382 lastWS = true; 383 } 384 return lastWS; 385 } else 386 return lastWS; 387 } 388 389 public void compose(Element div, XhtmlNode x) { 390 for (XhtmlNode child : x.getChildNodes()) { 391 appendChild(div, child); 392 } 393 } 394 395 private void appendChild(Element e, XhtmlNode node) { 396 if (node.getNodeType() == NodeType.Comment) 397 e.appendChild(e.getOwnerDocument().createComment(node.getContent())); 398 else if (node.getNodeType() == NodeType.DocType) 399 throw new Error("not done yet"); 400 else if (node.getNodeType() == NodeType.Instruction) 401 e.appendChild(e.getOwnerDocument().createProcessingInstruction("", node.getContent())); 402 else if (node.getNodeType() == NodeType.Text) 403 e.appendChild(e.getOwnerDocument().createTextNode(node.getContent())); 404 else if (node.getNodeType() == NodeType.Element) { 405 Element child = e.getOwnerDocument().createElementNS(XHTML_NS, node.getName()); 406 e.appendChild(child); 407 for (String n : node.getAttributes().keySet()) { 408 child.setAttribute(n, node.getAttribute(n)); 409 } 410 for (XhtmlNode c : node.getChildNodes()) { 411 appendChild(child, c); 412 } 413 } else 414 throw new Error("Unknown node type: "+node.getNodeType().toString()); 415 } 416 417 public void compose(OutputStream stream, XhtmlNode x) throws IOException { 418 byte[] bom = new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF }; 419 stream.write(bom); 420 dst = new OutputStreamWriter(stream, "UTF-8"); 421 dst.append("<html><head><link rel=\"stylesheet\" href=\"fhir.css\"/></head><body>\r\n"); 422 writeNode("", x, false); 423 dst.append("</body></html>\r\n"); 424 dst.flush(); 425 } 426 427 public void composeDocument(FileOutputStream f, XhtmlNode xhtml) throws IOException { 428 byte[] bom = new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF }; 429 f.write(bom); 430 dst = new OutputStreamWriter(f, "UTF-8"); 431 writeNode("", xhtml, false); 432 dst.flush(); 433 dst.close(); 434 } 435 436 public String composeEx(XhtmlNode node) { 437 try { 438 return compose(node); 439 } catch (IOException e) { 440 throw new Error(e); 441 } 442 } 443 444 public String compose(XhtmlNodeList nodes) throws IOException { 445 StringWriter sdst = new StringWriter(); 446 dst = sdst; 447 for (XhtmlNode node : nodes) { 448 writeNode("", node, false); 449 } 450 return sdst.toString(); 451 } 452 453 public boolean isAutoLinks() { 454 return autoLinks; 455 } 456 457 public XhtmlComposer setAutoLinks(boolean autoLinks) { 458 this.autoLinks = autoLinks; 459 return this; 460 } 461 462}