StreamSerializer.java 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. /* StreamSerializer.java --
  2. Copyright (C) 2004,2006 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package gnu.xml.transform;
  32. import gnu.java.lang.CPStringBuilder;
  33. import java.io.ByteArrayOutputStream;
  34. import java.io.IOException;
  35. import java.io.OutputStream;
  36. import java.nio.ByteBuffer;
  37. import java.nio.CharBuffer;
  38. import java.nio.charset.Charset;
  39. import java.nio.charset.CharsetEncoder;
  40. import java.util.Collection;
  41. import java.util.Collections;
  42. import java.util.HashMap;
  43. import java.util.HashSet;
  44. import java.util.Iterator;
  45. import java.util.LinkedList;
  46. import java.util.Map;
  47. import javax.xml.XMLConstants;
  48. import org.w3c.dom.Attr;
  49. import org.w3c.dom.Document;
  50. import org.w3c.dom.DocumentType;
  51. import org.w3c.dom.NamedNodeMap;
  52. import org.w3c.dom.Node;
  53. /**
  54. * Serializes a DOM node to an output stream.
  55. *
  56. * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a>
  57. */
  58. public class StreamSerializer
  59. {
  60. static final int SPACE = 0x20;
  61. static final int BANG = 0x21; // !
  62. static final int APOS = 0x27; // '
  63. static final int SLASH = 0x2f; // /
  64. static final int BRA = 0x3c; // <
  65. static final int KET = 0x3e; // >
  66. static final int EQ = 0x3d; // =
  67. /**
  68. * HTML 4.01 boolean attributes
  69. */
  70. static final Map HTML_BOOLEAN_ATTRIBUTES = new HashMap();
  71. static
  72. {
  73. HashSet set;
  74. set = new HashSet();
  75. set.add("nohref");
  76. HTML_BOOLEAN_ATTRIBUTES.put("area", set);
  77. set = new HashSet();
  78. set.add("ismap");
  79. HTML_BOOLEAN_ATTRIBUTES.put("img", set);
  80. set = new HashSet();
  81. set.add("declare");
  82. HTML_BOOLEAN_ATTRIBUTES.put("object", set);
  83. set = new HashSet();
  84. set.add("noshade");
  85. HTML_BOOLEAN_ATTRIBUTES.put("hr", set);
  86. set = new HashSet();
  87. set.add("compact");
  88. HTML_BOOLEAN_ATTRIBUTES.put("dl", set);
  89. HTML_BOOLEAN_ATTRIBUTES.put("ol", set);
  90. HTML_BOOLEAN_ATTRIBUTES.put("ul", set);
  91. HTML_BOOLEAN_ATTRIBUTES.put("dir", set);
  92. HTML_BOOLEAN_ATTRIBUTES.put("menu", set);
  93. set = new HashSet();
  94. set.add("checked");
  95. set.add("disabled");
  96. set.add("readonly");
  97. set.add("ismap");
  98. HTML_BOOLEAN_ATTRIBUTES.put("input", set);
  99. set = new HashSet();
  100. set.add("multiple");
  101. set.add("disabled");
  102. HTML_BOOLEAN_ATTRIBUTES.put("select", set);
  103. set = new HashSet();
  104. set.add("disabled");
  105. HTML_BOOLEAN_ATTRIBUTES.put("optgroup", set);
  106. set = new HashSet();
  107. set.add("selected");
  108. set.add("disabled");
  109. HTML_BOOLEAN_ATTRIBUTES.put("option", set);
  110. set = new HashSet();
  111. set.add("disabled");
  112. set.add("readonly");
  113. HTML_BOOLEAN_ATTRIBUTES.put("textarea", set);
  114. set = new HashSet();
  115. set.add("disabled");
  116. HTML_BOOLEAN_ATTRIBUTES.put("button", set);
  117. set = new HashSet();
  118. set.add("nowrap");
  119. HTML_BOOLEAN_ATTRIBUTES.put("th", set);
  120. HTML_BOOLEAN_ATTRIBUTES.put("td", set);
  121. set = new HashSet();
  122. set.add("noresize");
  123. HTML_BOOLEAN_ATTRIBUTES.put("frame", set);
  124. set = new HashSet();
  125. set.add("defer");
  126. HTML_BOOLEAN_ATTRIBUTES.put("script", set);
  127. }
  128. // HTML namespace URIs
  129. static final HashSet HTML_URIS = new HashSet();
  130. static {
  131. HTML_URIS.add("http://www.w3.org/1999/xhtml");
  132. }
  133. protected final String encoding;
  134. final Charset charset;
  135. final CharsetEncoder encoder;
  136. final int mode;
  137. final LinkedList namespaces;
  138. protected String eol;
  139. Collection cdataSectionElements = Collections.EMPTY_SET;
  140. protected boolean discardDefaultContent;
  141. protected boolean xmlDeclaration = true;
  142. // has a META element with the encoding been added?
  143. private boolean htmlEncoded;
  144. public StreamSerializer()
  145. {
  146. this(Stylesheet.OUTPUT_XML, null, null);
  147. }
  148. public StreamSerializer(String encoding)
  149. {
  150. this(Stylesheet.OUTPUT_XML, encoding, null);
  151. }
  152. public StreamSerializer(int mode, String encoding, String eol)
  153. {
  154. this.mode = mode;
  155. if (encoding == null)
  156. encoding = (mode == Stylesheet.OUTPUT_HTML) ? "ISO-8859-1" : "UTF-8";
  157. this.encoding = encoding.intern();
  158. charset = Charset.forName(this.encoding);
  159. encoder = charset.newEncoder();
  160. this.eol = (eol != null) ? eol : System.getProperty("line.separator");
  161. namespaces = new LinkedList();
  162. }
  163. void setCdataSectionElements(Collection c)
  164. {
  165. cdataSectionElements = c;
  166. }
  167. public void serialize(final Node node, final OutputStream out)
  168. throws IOException
  169. {
  170. serialize(node, out, false);
  171. }
  172. void serialize(Node node, final OutputStream out,
  173. boolean convertToCdata)
  174. throws IOException
  175. {
  176. while (node != null)
  177. {
  178. Node next = node.getNextSibling();
  179. doSerialize(node, out, convertToCdata);
  180. node = next;
  181. }
  182. }
  183. private void doSerialize(final Node node, final OutputStream out,
  184. boolean convertToCdata)
  185. throws IOException
  186. {
  187. if (out == null)
  188. throw new NullPointerException("no output stream");
  189. htmlEncoded = false;
  190. String value, prefix;
  191. Node children;
  192. String uri = node.getNamespaceURI();
  193. short nt = node.getNodeType();
  194. if (convertToCdata && nt == Node.TEXT_NODE)
  195. nt = Node.CDATA_SECTION_NODE;
  196. switch (nt)
  197. {
  198. case Node.ATTRIBUTE_NODE:
  199. prefix = node.getPrefix();
  200. if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(uri) ||
  201. XMLConstants.XMLNS_ATTRIBUTE.equals(prefix) ||
  202. (prefix != null && prefix.startsWith("xmlns:")))
  203. {
  204. String nsuri = node.getNodeValue();
  205. if (isDefined(nsuri, prefix))
  206. break;
  207. String name = node.getLocalName();
  208. if (name == null)
  209. {
  210. // Namespace-unaware
  211. name = node.getNodeName();
  212. int ci = name.indexOf(':');
  213. if (ci != -1)
  214. name = name.substring(ci + 1);
  215. }
  216. define(nsuri, name);
  217. }
  218. else if (uri != null && !isDefined(uri, prefix))
  219. {
  220. prefix = define(uri, prefix);
  221. String nsname = (prefix == null) ? "xmlns" : "xmlns:" + prefix;
  222. out.write(SPACE);
  223. out.write(encodeText(nsname));
  224. out.write(EQ);
  225. String nsvalue = "\"" + encode(uri, true, true) + "\"";
  226. out.write(nsvalue.getBytes(encoding));
  227. }
  228. out.write(SPACE);
  229. String a_nodeName = node.getNodeName();
  230. out.write(encodeText(a_nodeName));
  231. String a_nodeValue = node.getNodeValue();
  232. if (mode == Stylesheet.OUTPUT_HTML &&
  233. a_nodeName.equals(a_nodeValue) &&
  234. isHTMLBoolean((Attr) node, a_nodeName))
  235. break;
  236. out.write(EQ);
  237. value = "\"" + encode(a_nodeValue, true, true) + "\"";
  238. out.write(encodeText(value));
  239. break;
  240. case Node.ELEMENT_NODE:
  241. pushNamespaceContext();
  242. value = node.getNodeName();
  243. out.write(BRA);
  244. out.write(encodeText(value));
  245. prefix = node.getPrefix();
  246. if (uri != null && !isDefined(uri, prefix))
  247. {
  248. prefix = define(uri, prefix);
  249. String nsname = (prefix == null) ? "xmlns" : "xmlns:" + prefix;
  250. out.write(SPACE);
  251. out.write(encodeText(nsname));
  252. out.write(EQ);
  253. String nsvalue = "\"" + encode(uri, true, true) + "\"";
  254. out.write(encodeText(nsvalue));
  255. }
  256. NamedNodeMap attrs = node.getAttributes();
  257. if (attrs != null)
  258. {
  259. int len = attrs.getLength();
  260. for (int i = 0; i < len; i++)
  261. {
  262. Attr attr = (Attr) attrs.item(i);
  263. if (discardDefaultContent && !attr.getSpecified())
  264. {
  265. // NOOP
  266. }
  267. else
  268. serialize(attr, out, false);
  269. }
  270. }
  271. convertToCdata = cdataSectionElements.contains(value);
  272. children = node.getFirstChild();
  273. if (children == null)
  274. {
  275. out.write(SLASH);
  276. out.write(KET);
  277. }
  278. else
  279. {
  280. out.write(KET);
  281. serialize(children, out, convertToCdata);
  282. out.write(BRA);
  283. out.write(SLASH);
  284. out.write(encodeText(value));
  285. out.write(KET);
  286. }
  287. popNamespaceContext();
  288. break;
  289. case Node.TEXT_NODE:
  290. value = node.getNodeValue();
  291. if (!"yes".equals(node.getUserData("disable-output-escaping")) &&
  292. mode != Stylesheet.OUTPUT_TEXT)
  293. value = encode(value, false, false);
  294. out.write(encodeText(value));
  295. break;
  296. case Node.CDATA_SECTION_NODE:
  297. value = node.getNodeValue();
  298. // Where any instanceof of ]]> occur, split into multiple CDATA
  299. // sections
  300. int bbk = value.indexOf("]]>");
  301. while (bbk != -1)
  302. {
  303. String head = value.substring(0, bbk + 2);
  304. out.write(encodeText("<![CDATA[" + head + "]]>"));
  305. value = value.substring(bbk + 2);
  306. bbk = value.indexOf("]]>");
  307. }
  308. // Write final tail value
  309. out.write(encodeText("<![CDATA[" + value + "]]>"));
  310. break;
  311. case Node.COMMENT_NODE:
  312. value = "<!--" + node.getNodeValue() + "-->";
  313. out.write(encodeText(value));
  314. Node cp = node.getParentNode();
  315. if (cp != null && cp.getNodeType() == Node.DOCUMENT_NODE)
  316. out.write(encodeText(eol));
  317. break;
  318. case Node.DOCUMENT_NODE:
  319. case Node.DOCUMENT_FRAGMENT_NODE:
  320. if (mode == Stylesheet.OUTPUT_XML)
  321. {
  322. if ("UTF-16".equalsIgnoreCase(encoding))
  323. {
  324. out.write(0xfe);
  325. out.write(0xff);
  326. }
  327. if (!"yes".equals(node.getUserData("omit-xml-declaration")) &&
  328. xmlDeclaration)
  329. {
  330. Document doc = (node instanceof Document) ?
  331. (Document) node : null;
  332. String version = (doc != null) ? doc.getXmlVersion() : null;
  333. if (version == null)
  334. version = (String) node.getUserData("version");
  335. if (version == null)
  336. version = "1.0";
  337. out.write(BRA);
  338. out.write(0x3f);
  339. out.write("xml version=\"".getBytes("US-ASCII"));
  340. out.write(version.getBytes("US-ASCII"));
  341. out.write(0x22);
  342. if (!("UTF-8".equalsIgnoreCase(encoding)))
  343. {
  344. out.write(" encoding=\"".getBytes("US-ASCII"));
  345. out.write(encoding.getBytes("US-ASCII"));
  346. out.write(0x22);
  347. }
  348. if ((doc != null && doc.getXmlStandalone()) ||
  349. "yes".equals(node.getUserData("standalone")))
  350. out.write(" standalone=\"yes\"".getBytes("US-ASCII"));
  351. out.write(0x3f);
  352. out.write(KET);
  353. out.write(encodeText(eol));
  354. }
  355. // TODO warn if not outputting the declaration would be a
  356. // problem
  357. }
  358. else if (mode == Stylesheet.OUTPUT_HTML)
  359. {
  360. // Ensure that encoding is accessible if head element is present
  361. String mediaType = (String) node.getUserData("media-type");
  362. if (mediaType == null)
  363. mediaType = "text/html";
  364. String contentType = mediaType + "; charset=" +
  365. ((encoding.indexOf(' ') != -1) ?
  366. "\"" + encoding + "\"" :
  367. encoding);
  368. Document doc = (node instanceof Document) ? (Document) node :
  369. node.getOwnerDocument();
  370. Node html = null;
  371. for (Node ctx = node.getFirstChild(); ctx != null;
  372. ctx = ctx.getNextSibling())
  373. {
  374. if (ctx.getNodeType() == Node.ELEMENT_NODE &&
  375. isHTMLElement(ctx, "html"))
  376. {
  377. html = ctx;
  378. break;
  379. }
  380. }
  381. if (html != null)
  382. {
  383. Node head = null;
  384. for (Node ctx = html.getFirstChild(); ctx != null;
  385. ctx = ctx.getNextSibling())
  386. {
  387. if (isHTMLElement(ctx, "head"))
  388. {
  389. head = ctx;
  390. break;
  391. }
  392. }
  393. if (head != null)
  394. {
  395. Node meta = null;
  396. Node metaContent = null;
  397. for (Node ctx = head.getFirstChild(); ctx != null;
  398. ctx = ctx.getNextSibling())
  399. {
  400. if (isHTMLElement(ctx, "meta"))
  401. {
  402. NamedNodeMap metaAttrs = ctx.getAttributes();
  403. int len = metaAttrs.getLength();
  404. String httpEquiv = null;
  405. Node content = null;
  406. for (int i = 0; i < len; i++)
  407. {
  408. Node attr = metaAttrs.item(i);
  409. String attrName = attr.getNodeName();
  410. if ("http-equiv".equalsIgnoreCase(attrName))
  411. httpEquiv = attr.getNodeValue();
  412. else if ("content".equalsIgnoreCase(attrName))
  413. content = attr;
  414. }
  415. if ("Content-Type".equalsIgnoreCase(httpEquiv))
  416. {
  417. meta = ctx;
  418. metaContent = content;
  419. break;
  420. }
  421. }
  422. }
  423. if (meta == null)
  424. {
  425. meta = doc.createElement("meta");
  426. // Insert first
  427. Node first = head.getFirstChild();
  428. if (first == null)
  429. head.appendChild(meta);
  430. else
  431. head.insertBefore(meta, first);
  432. Node metaHttpEquiv = doc.createAttribute("http-equiv");
  433. meta.getAttributes().setNamedItem(metaHttpEquiv);
  434. metaHttpEquiv.setNodeValue("Content-Type");
  435. }
  436. if (metaContent == null)
  437. {
  438. metaContent = doc.createAttribute("content");
  439. meta.getAttributes().setNamedItem(metaContent);
  440. }
  441. metaContent.setNodeValue(contentType);
  442. htmlEncoded = true;
  443. }
  444. }
  445. }
  446. children = node.getFirstChild();
  447. if (children != null)
  448. serialize(children, out, convertToCdata);
  449. break;
  450. case Node.DOCUMENT_TYPE_NODE:
  451. DocumentType doctype = (DocumentType) node;
  452. out.write(BRA);
  453. out.write(BANG);
  454. out.write(encodeText("DOCTYPE "));
  455. value = doctype.getNodeName();
  456. out.write(encodeText(value));
  457. String publicId = doctype.getPublicId();
  458. if (publicId != null)
  459. {
  460. out.write(encodeText(" PUBLIC "));
  461. out.write(APOS);
  462. out.write(encodeText(publicId));
  463. out.write(APOS);
  464. }
  465. String systemId = doctype.getSystemId();
  466. if (systemId != null)
  467. {
  468. out.write(encodeText(" SYSTEM "));
  469. out.write(APOS);
  470. out.write(encodeText(systemId));
  471. out.write(APOS);
  472. }
  473. String internalSubset = doctype.getInternalSubset();
  474. if (internalSubset != null)
  475. {
  476. out.write(encodeText(internalSubset));
  477. }
  478. out.write(KET);
  479. out.write(eol.getBytes(encoding));
  480. break;
  481. case Node.ENTITY_REFERENCE_NODE:
  482. value = "&" + node.getNodeValue() + ";";
  483. out.write(encodeText(value));
  484. break;
  485. case Node.PROCESSING_INSTRUCTION_NODE:
  486. value = "<?" + node.getNodeName() + " " + node.getNodeValue() + "?>";
  487. out.write(encodeText(value));
  488. Node pp = node.getParentNode();
  489. if (pp != null && pp.getNodeType() == Node.DOCUMENT_NODE)
  490. {
  491. out.write(encodeText(eol));
  492. }
  493. break;
  494. default:
  495. System.err.println("Unhandled node type: "+nt);
  496. }
  497. }
  498. boolean isHTMLElement(Node node, String name)
  499. {
  500. if (node.getNodeType() != Node.ELEMENT_NODE)
  501. return false;
  502. String localName = node.getLocalName();
  503. if (localName == null)
  504. localName = node.getNodeName();
  505. if (!name.equalsIgnoreCase(localName))
  506. return false;
  507. String uri = node.getNamespaceURI();
  508. return (uri == null || HTML_URIS.contains(uri));
  509. }
  510. boolean isDefined(String uri, String prefix)
  511. {
  512. if (XMLConstants.XML_NS_URI.equals(uri))
  513. return "xml".equals(prefix);
  514. if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(uri))
  515. return "xmlns".equals(prefix);
  516. if (prefix == null)
  517. prefix = "";
  518. for (Iterator i = namespaces.iterator(); i.hasNext(); )
  519. {
  520. Map ctx = (Map) i.next();
  521. String val = (String) ctx.get(uri);
  522. if (val != null && val.equals(prefix))
  523. return true;
  524. }
  525. return false;
  526. }
  527. void pushNamespaceContext()
  528. {
  529. namespaces.addFirst(new HashMap());
  530. }
  531. String define(String uri, String prefix)
  532. {
  533. if (namespaces.isEmpty())
  534. return prefix;
  535. HashMap ctx = (HashMap) namespaces.getFirst();
  536. while (ctx.containsValue(prefix))
  537. {
  538. // Fabricate new prefix
  539. prefix = prefix + "_";
  540. }
  541. ctx.put(uri, prefix);
  542. return prefix;
  543. }
  544. void popNamespaceContext()
  545. {
  546. namespaces.removeFirst();
  547. }
  548. final byte[] encodeText(String text)
  549. throws IOException
  550. {
  551. encoder.reset();
  552. boolean htmlNeedingEncoding =
  553. (mode == Stylesheet.OUTPUT_HTML && !htmlEncoded);
  554. if (!encoder.canEncode(text) || htmlNeedingEncoding)
  555. {
  556. // Check each character
  557. CPStringBuilder buf = new CPStringBuilder();
  558. int len = text.length();
  559. for (int i = 0; i < len; i++)
  560. {
  561. char c = text.charAt(i);
  562. if (!encoder.canEncode(c))
  563. {
  564. // Replace with character entity reference
  565. String hex = Integer.toHexString((int) c);
  566. buf.append("&#x");
  567. buf.append(hex);
  568. buf.append(';');
  569. }
  570. else if (htmlNeedingEncoding)
  571. {
  572. String entityName = getHTMLCharacterEntity(c);
  573. if (entityName != null)
  574. {
  575. buf.append('&');
  576. buf.append(entityName);
  577. buf.append(';');
  578. }
  579. else
  580. buf.append(c);
  581. }
  582. else
  583. buf.append(c);
  584. }
  585. text = buf.toString();
  586. }
  587. ByteBuffer encoded = encoder.encode(CharBuffer.wrap(text));
  588. int len = encoded.limit() - encoded.position();
  589. if (encoded.hasArray())
  590. {
  591. byte[] ret = encoded.array();
  592. if (ret.length > len)
  593. {
  594. // Why?
  595. byte[] ret2 = new byte[len];
  596. System.arraycopy(ret, 0, ret2, 0, len);
  597. ret = ret2;
  598. }
  599. return ret;
  600. }
  601. encoded.flip();
  602. byte[] ret = new byte[len];
  603. encoded.get(ret, 0, len);
  604. return ret;
  605. }
  606. String encode(String text, boolean encodeCtl, boolean inAttr)
  607. {
  608. int len = text.length();
  609. CPStringBuilder buf = null;
  610. for (int i = 0; i < len; i++)
  611. {
  612. char c = text.charAt(i);
  613. if (c == '<')
  614. {
  615. if (buf == null)
  616. buf = new CPStringBuilder(text.substring(0, i));
  617. buf.append("&lt;");
  618. }
  619. else if (c == '>')
  620. {
  621. if (buf == null)
  622. buf = new CPStringBuilder(text.substring(0, i));
  623. buf.append("&gt;");
  624. }
  625. else if (c == '&')
  626. {
  627. if (mode == Stylesheet.OUTPUT_HTML && (i + 1) < len &&
  628. text.charAt(i + 1) == '{')
  629. {
  630. if (buf != null)
  631. buf.append(c);
  632. }
  633. else
  634. {
  635. if (buf == null)
  636. buf = new CPStringBuilder(text.substring(0, i));
  637. buf.append("&amp;");
  638. }
  639. }
  640. else if (c == '\'' && inAttr)
  641. {
  642. if (buf == null)
  643. buf = new CPStringBuilder(text.substring(0, i));
  644. if (mode == Stylesheet.OUTPUT_HTML)
  645. // HTML does not define &apos;, use character entity ref
  646. buf.append("&#x27;");
  647. else
  648. buf.append("&apos;");
  649. }
  650. else if (c == '"' && inAttr)
  651. {
  652. if (buf == null)
  653. buf = new CPStringBuilder(text.substring(0, i));
  654. buf.append("&quot;");
  655. }
  656. else if (encodeCtl)
  657. {
  658. if (c < 0x20)
  659. {
  660. if (buf == null)
  661. buf = new CPStringBuilder(text.substring(0, i));
  662. buf.append('&');
  663. buf.append('#');
  664. buf.append((int) c);
  665. buf.append(';');
  666. }
  667. else if (buf != null)
  668. buf.append(c);
  669. }
  670. else if (buf != null)
  671. buf.append(c);
  672. }
  673. return (buf == null) ? text : buf.toString();
  674. }
  675. String toString(Node node)
  676. {
  677. ByteArrayOutputStream out = new ByteArrayOutputStream();
  678. try
  679. {
  680. serialize(node, out);
  681. return new String(out.toByteArray(), encoding);
  682. }
  683. catch (IOException e)
  684. {
  685. throw new RuntimeException(e.getMessage());
  686. }
  687. }
  688. boolean isHTMLBoolean(Attr attr, String attrName)
  689. {
  690. attrName = attrName.toLowerCase();
  691. Node element = attr.getOwnerElement();
  692. String elementName = element.getLocalName();
  693. if (elementName == null)
  694. {
  695. elementName = element.getNodeName();
  696. }
  697. elementName = elementName.toLowerCase();
  698. Collection attributes =
  699. (Collection) HTML_BOOLEAN_ATTRIBUTES.get(elementName);
  700. return (attributes != null && attributes.contains(attrName));
  701. }
  702. static String getHTMLCharacterEntity(char c)
  703. {
  704. // Hardcode these here to avoid loading the HTML DTD
  705. switch (c)
  706. {
  707. case 160: return "nbsp";
  708. case 161: return "iexcl";
  709. case 162: return "cent";
  710. case 163: return "pound";
  711. case 164: return "curren";
  712. case 165: return "yen";
  713. case 166: return "brvbar";
  714. case 167: return "sect";
  715. case 168: return "uml";
  716. case 169: return "copy";
  717. case 170: return "ordf";
  718. case 171: return "laquo";
  719. case 172: return "not";
  720. case 173: return "shy";
  721. case 174: return "reg";
  722. case 175: return "macr";
  723. case 176: return "deg";
  724. case 177: return "plusmn";
  725. case 178: return "sup2";
  726. case 179: return "sup3";
  727. case 180: return "acute";
  728. case 181: return "micro";
  729. case 182: return "para";
  730. case 183: return "middot";
  731. case 184: return "cedil";
  732. case 185: return "sup1";
  733. case 186: return "ordm";
  734. case 187: return "raquo";
  735. case 188: return "frac14";
  736. case 189: return "frac12";
  737. case 190: return "frac34";
  738. case 191: return "iquest";
  739. case 192: return "Agrave";
  740. case 193: return "Aacute";
  741. case 194: return "Acirc";
  742. case 195: return "Atilde";
  743. case 196: return "Auml";
  744. case 197: return "Aring";
  745. case 198: return "AElig";
  746. case 199: return "Ccedil";
  747. case 200: return "Egrave";
  748. case 201: return "Eacute";
  749. case 202: return "Ecirc";
  750. case 203: return "Euml";
  751. case 204: return "Igrave";
  752. case 205: return "Iacute";
  753. case 206: return "Icirc";
  754. case 207: return "Iuml";
  755. case 208: return "ETH";
  756. case 209: return "Ntilde";
  757. case 210: return "Ograve";
  758. case 211: return "Oacute";
  759. case 212: return "Ocirc";
  760. case 213: return "Otilde";
  761. case 214: return "Ouml";
  762. case 215: return "times";
  763. case 216: return "Oslash";
  764. case 217: return "Ugrave";
  765. case 218: return "Uacute";
  766. case 219: return "Ucirc";
  767. case 220: return "Uuml";
  768. case 221: return "Yacute";
  769. case 222: return "THORN";
  770. case 223: return "szlig";
  771. case 224: return "agrave";
  772. case 225: return "aacute";
  773. case 226: return "acirc";
  774. case 227: return "atilde";
  775. case 228: return "auml";
  776. case 229: return "aring";
  777. case 230: return "aelig";
  778. case 231: return "ccedil";
  779. case 232: return "egrave";
  780. case 233: return "eacute";
  781. case 234: return "ecirc";
  782. case 235: return "euml";
  783. case 236: return "igrave";
  784. case 237: return "iacute";
  785. case 238: return "icirc";
  786. case 239: return "iuml";
  787. case 240: return "eth";
  788. case 241: return "ntilde";
  789. case 242: return "ograve";
  790. case 243: return "oacute";
  791. case 244: return "ocirc";
  792. case 245: return "otilde";
  793. case 246: return "ouml";
  794. case 247: return "divide";
  795. case 248: return "oslash";
  796. case 249: return "ugrave";
  797. case 250: return "uacute";
  798. case 251: return "ucirc";
  799. case 252: return "uuml";
  800. case 253: return "yacute";
  801. case 254: return "thorn";
  802. case 255: return "yuml";
  803. default: return null;
  804. }
  805. }
  806. }