1. /*
  2. * @(#)XMLEncoder.java 1.33 03/12/19
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.beans;
  8. import java.io.*;
  9. import java.util.*;
  10. import java.lang.reflect.*;
  11. /**
  12. * The <code>XMLEncoder</code> class is a complementary alternative to
  13. * the <code>ObjectOutputStream</code> and can used to generate
  14. * a textual representation of a <em>JavaBean</em> in the same
  15. * way that the <code>ObjectOutputStream</code> can
  16. * be used to create binary representation of <code>Serializable</code>
  17. * objects. For example, the following fragment can be used to create
  18. * a textual representation the supplied <em>JavaBean</em>
  19. * and all its properties:
  20. * <pre>
  21. * XMLEncoder e = new XMLEncoder(
  22. * new BufferedOutputStream(
  23. * new FileOutputStream("Test.xml")));
  24. * e.writeObject(new JButton("Hello, world"));
  25. * e.close();
  26. * </pre>
  27. * Despite the similarity of their APIs, the <code>XMLEncoder</code>
  28. * class is exclusively designed for the purpose of archiving graphs
  29. * of <em>JavaBean</em>s as textual representations of their public
  30. * properties. Like Java source files, documents written this way
  31. * have a natural immunity to changes in the implementations of the classes
  32. * involved. The <code>ObjectOutputStream</code> continues to be recommended
  33. * for interprocess communication and general purpose serialization.
  34. * <p>
  35. * The <code>XMLEncoder</code> class provides a default denotation for
  36. * <em>JavaBean</em>s in which they are represented as XML documents
  37. * complying with version 1.0 of the XML specification and the
  38. * UTF-8 character encoding of the Unicode/ISO 10646 character set.
  39. * The XML documents produced by the <code>XMLEncoder</code> class are:
  40. * <ul>
  41. * <li>
  42. * <em>Portable and version resilient</em>: they have no dependencies
  43. * on the private implementation of any class and so, like Java source
  44. * files, they may be exchanged between environments which may have
  45. * different versions of some of the classes and between VMs from
  46. * different vendors.
  47. * <li>
  48. * <em>Structurally compact</em>: The <code>XMLEncoder</code> class
  49. * uses a <em>redundancy elimination</em> algorithm internally so that the
  50. * default values of a Bean's properties are not written to the stream.
  51. * <li>
  52. * <em>Fault tolerant</em>: Non-structural errors in the file,
  53. * caused either by damage to the file or by API changes
  54. * made to classes in an archive remain localized
  55. * so that a reader can report the error and continue to load the parts
  56. * of the document which were not affected by the error.
  57. * </ul>
  58. * <p>
  59. * Below is an example of an XML archive containing
  60. * some user interface components from the <em>swing</em> toolkit:
  61. * <pre>
  62. * <?xml version="1.0" encoding="UTF-8"?>
  63. * <java version="1.0" class="java.beans.XMLDecoder">
  64. * <object class="javax.swing.JFrame">
  65. * <void property="name">
  66. * <string>frame1</string>
  67. * </void>
  68. * <void property="bounds">
  69. * <object class="java.awt.Rectangle">
  70. * <int>0</int>
  71. * <int>0</int>
  72. * <int>200</int>
  73. * <int>200</int>
  74. * </object>
  75. * </void>
  76. * <void property="contentPane">
  77. * <void method="add">
  78. * <object class="javax.swing.JButton">
  79. * <void property="label">
  80. * <string>Hello</string>
  81. * </void>
  82. * </object>
  83. * </void>
  84. * </void>
  85. * <void property="visible">
  86. * <boolean>true</boolean>
  87. * </void>
  88. * </object>
  89. * </java>
  90. * </pre>
  91. * The XML syntax uses the following conventions:
  92. * <ul>
  93. * <li>
  94. * Each element represents a method call.
  95. * <li>
  96. * The "object" tag denotes an <em>expression</em> whose value is
  97. * to be used as the argument to the enclosing element.
  98. * <li>
  99. * The "void" tag denotes a <em>statement</em> which will
  100. * be executed, but whose result will not be used as an
  101. * argument to the enclosing method.
  102. * <li>
  103. * Elements which contain elements use those elements as arguments,
  104. * unless they have the tag: "void".
  105. * <li>
  106. * The name of the method is denoted by the "method" attribute.
  107. * <li>
  108. * XML's standard "id" and "idref" attributes are used to make
  109. * references to previous expressions - so as to deal with
  110. * circularities in the object graph.
  111. * <li>
  112. * The "class" attribute is used to specify the target of a static
  113. * method or constructor explicitly; its value being the fully
  114. * qualified name of the class.
  115. * <li>
  116. * Elements with the "void" tag are executed using
  117. * the outer context as the target if no target is defined
  118. * by a "class" attribute.
  119. * <li>
  120. * Java's String class is treated specially and is
  121. * written <string>Hello, world</string> where
  122. * the characters of the string are converted to bytes
  123. * using the UTF-8 character encoding.
  124. * </ul>
  125. * <p>
  126. * Although all object graphs may be written using just these three
  127. * tags, the following definitions are included so that common
  128. * data structures can be expressed more concisely:
  129. * <p>
  130. * <ul>
  131. * <li>
  132. * The default method name is "new".
  133. * <li>
  134. * A reference to a java class is written in the form
  135. * <class>javax.swing.JButton</class>.
  136. * <li>
  137. * Instances of the wrapper classes for Java's primitive types are written
  138. * using the name of the primitive type as the tag. For example, an
  139. * instance of the <code>Integer</code> class could be written:
  140. * <int>123</int>. Note that the <code>XMLEncoder</code> class
  141. * uses Java's reflection package in which the conversion between
  142. * Java's primitive types and their associated "wrapper classes"
  143. * is handled internally. The API for the <code>XMLEncoder</code> class
  144. * itself deals only with <code>Object</code>s.
  145. * <li>
  146. * In an element representing a nullary method whose name
  147. * starts with "get", the "method" attribute is replaced
  148. * with a "property" attribute whose value is given by removing
  149. * the "get" prefix and decapitalizing the result.
  150. * <li>
  151. * In an element representing a monadic method whose name
  152. * starts with "set", the "method" attribute is replaced
  153. * with a "property" attribute whose value is given by removing
  154. * the "set" prefix and decapitalizing the result.
  155. * <li>
  156. * In an element representing a method named "get" taking one
  157. * integer argument, the "method" attribute is replaced
  158. * with an "index" attribute whose value the value of the
  159. * first argument.
  160. * <li>
  161. * In an element representing a method named "set" taking two arguments,
  162. * the first of which is an integer, the "method" attribute is replaced
  163. * with an "index" attribute whose value the value of the
  164. * first argument.
  165. * <li>
  166. * A reference to an array is written using the "array"
  167. * tag. The "class" and "length" attributes specify the
  168. * sub-type of the array and its length respectively.
  169. * </ul>
  170. *
  171. *<p>
  172. * For more information you might also want to check out
  173. * <a
  174. href="http://java.sun.com/products/jfc/tsc/articles/persistence4">Using XMLEncoder</a>,
  175. * an article in <em>The Swing Connection.</em>
  176. * @see XMLDecoder
  177. * @see java.io.ObjectOutputStream
  178. *
  179. * @since 1.4
  180. *
  181. * @version 1.33 12/19/03
  182. * @author Philip Milne
  183. */
  184. public class XMLEncoder extends Encoder {
  185. private static String encoding = "UTF-8";
  186. private OutputStream out;
  187. private Object owner;
  188. private int indentation = 0;
  189. private boolean internal = false;
  190. private Map valueToExpression;
  191. private Map targetToStatementList;
  192. private boolean preambleWritten = false;
  193. private NameGenerator nameGenerator;
  194. private class ValueData {
  195. public int refs = 0;
  196. public boolean marked = false; // Marked -> refs > 0 unless ref was a target.
  197. public String name = null;
  198. public Expression exp = null;
  199. }
  200. /**
  201. * Creates a new output stream for sending <em>JavaBeans</em>
  202. * to the stream <code>out</code> using an XML encoding.
  203. *
  204. * @param out The stream to which the XML representation of
  205. * the objects will be sent.
  206. *
  207. * @see XMLDecoder#XMLDecoder(InputStream)
  208. */
  209. public XMLEncoder(OutputStream out) {
  210. this.out = out;
  211. valueToExpression = new IdentityHashMap();
  212. targetToStatementList = new IdentityHashMap();
  213. nameGenerator = new NameGenerator();
  214. }
  215. /**
  216. * Sets the owner of this encoder to <code>owner</code>.
  217. *
  218. * @param owner The owner of this encoder.
  219. *
  220. * @see #getOwner
  221. */
  222. public void setOwner(Object owner) {
  223. this.owner = owner;
  224. writeExpression(new Expression(this, "getOwner", new Object[0]));
  225. }
  226. /**
  227. * Gets the owner of this encoder.
  228. *
  229. * @return The owner of this encoder.
  230. *
  231. * @see #setOwner
  232. */
  233. public Object getOwner() {
  234. return owner;
  235. }
  236. /**
  237. * Write an XML representation of the specified object to the output.
  238. *
  239. * @param o The object to be written to the stream.
  240. *
  241. * @see XMLDecoder#readObject
  242. */
  243. public void writeObject(Object o) {
  244. if (internal) {
  245. super.writeObject(o);
  246. }
  247. else {
  248. writeStatement(new Statement(this, "writeObject", new Object[]{o}));
  249. }
  250. }
  251. private Vector statementList(Object target) {
  252. Vector list = (Vector)targetToStatementList.get(target);
  253. if (list != null) {
  254. return list;
  255. }
  256. list = new Vector();
  257. targetToStatementList.put(target, list);
  258. return list;
  259. }
  260. private void mark(Object o, boolean isArgument) {
  261. if (o == null || o == this) {
  262. return;
  263. }
  264. ValueData d = getValueData(o);
  265. Expression exp = d.exp;
  266. // Do not mark liternal strings. Other strings, which might,
  267. // for example, come from resource bundles should still be marked.
  268. if (o.getClass() == String.class && exp == null) {
  269. return;
  270. }
  271. // Bump the reference counts of all arguments
  272. if (isArgument) {
  273. d.refs++;
  274. }
  275. if (d.marked) {
  276. return;
  277. }
  278. d.marked = true;
  279. Object target = exp.getTarget();
  280. if (!(target instanceof Class)) {
  281. statementList(target).add(exp);
  282. // Pending: Why does the reference count need to
  283. // be incremented here?
  284. d.refs++;
  285. }
  286. mark(exp);
  287. }
  288. private void mark(Statement stm) {
  289. Object[] args = stm.getArguments();
  290. for (int i = 0; i < args.length; i++) {
  291. Object arg = args[i];
  292. mark(arg, true);
  293. }
  294. mark(stm.getTarget(), false);
  295. }
  296. /**
  297. * Records the Statement so that the Encoder will
  298. * produce the actual output when the stream is flushed.
  299. * <P>
  300. * This method should only be invoked within the context
  301. * of initializing a persistence delegate.
  302. *
  303. * @param oldStm The statement that will be written
  304. * to the stream.
  305. * @see java.beans.PersistenceDelegate#initialize
  306. */
  307. public void writeStatement(Statement oldStm) {
  308. // System.out.println("XMLEncoder::writeStatement: " + oldStm);
  309. boolean internal = this.internal;
  310. this.internal = true;
  311. try {
  312. super.writeStatement(oldStm);
  313. /*
  314. Note we must do the mark first as we may
  315. require the results of previous values in
  316. this context for this statement.
  317. Test case is:
  318. os.setOwner(this);
  319. os.writeObject(this);
  320. */
  321. mark(oldStm);
  322. statementList(oldStm.getTarget()).add(oldStm);
  323. }
  324. catch (Exception e) {
  325. getExceptionListener().exceptionThrown(new Exception("XMLEncoder: discarding statement " + oldStm, e));
  326. }
  327. this.internal = internal;
  328. }
  329. /**
  330. * Records the Expression so that the Encoder will
  331. * produce the actual output when the stream is flushed.
  332. * <P>
  333. * This method should only be invoked within the context of
  334. * initializing a persistence delegate or setting up an encoder to
  335. * read from a resource bundle.
  336. * <P>
  337. * For more information about using resource bundles with the
  338. * XMLEncoder, see
  339. * http://java.sun.com/products/jfc/tsc/articles/persistence4/#i18n
  340. *
  341. * @param oldExp The expression that will be written
  342. * to the stream.
  343. * @see java.beans.PersistenceDelegate#initialize
  344. */
  345. public void writeExpression(Expression oldExp) {
  346. boolean internal = this.internal;
  347. this.internal = true;
  348. Object oldValue = getValue(oldExp);
  349. if (get(oldValue) == null || (oldValue instanceof String && !internal)) {
  350. getValueData(oldValue).exp = oldExp;
  351. super.writeExpression(oldExp);
  352. }
  353. this.internal = internal;
  354. }
  355. /**
  356. * This method writes out the preamble associated with the
  357. * XML encoding if it has not been written already and
  358. * then writes out all of the values that been
  359. * written to the stream since the last time <code>flush</code>
  360. * was called. After flushing, all internal references to the
  361. * values that were written to this stream are cleared.
  362. */
  363. public void flush() {
  364. if (!preambleWritten) { // Don't do this in constructor - it throws ... pending.
  365. writeln("<?xml version=" + quote("1.0") +
  366. " encoding=" + quote(encoding) + "?>");
  367. writeln("<java version=" + quote(System.getProperty("java.version")) +
  368. " class=" + quote(XMLDecoder.class.getName()) + ">");
  369. preambleWritten = true;
  370. }
  371. indentation++;
  372. Vector roots = statementList(this);
  373. for(int i = 0; i < roots.size(); i++) {
  374. Statement s = (Statement)roots.get(i);
  375. if ("writeObject".equals(s.getMethodName())) {
  376. outputValue(s.getArguments()[0], this, true);
  377. }
  378. else {
  379. outputStatement(s, this, false);
  380. }
  381. }
  382. indentation--;
  383. try {
  384. out.flush();
  385. }
  386. catch (IOException e) {
  387. getExceptionListener().exceptionThrown(e);
  388. }
  389. clear();
  390. }
  391. void clear() {
  392. super.clear();
  393. nameGenerator.clear();
  394. valueToExpression.clear();
  395. targetToStatementList.clear();
  396. }
  397. /**
  398. * This method calls <code>flush</code>, writes the closing
  399. * postamble and then closes the output stream associated
  400. * with this stream.
  401. */
  402. public void close() {
  403. flush();
  404. writeln("</java>");
  405. try {
  406. out.close();
  407. }
  408. catch (IOException e) {
  409. getExceptionListener().exceptionThrown(e);
  410. }
  411. }
  412. private String quote(String s) {
  413. return "\"" + s + "\"";
  414. }
  415. private ValueData getValueData(Object o) {
  416. ValueData d = (ValueData)valueToExpression.get(o);
  417. if (d == null) {
  418. d = new ValueData();
  419. valueToExpression.put(o, d);
  420. }
  421. return d;
  422. }
  423. private static String quoteCharacters(String s) {
  424. StringBuffer result = null;
  425. for(int i = 0, max = s.length(), delta = 0; i < max; i++) {
  426. char c = s.charAt(i);
  427. String replacement = null;
  428. if (c == '&') {
  429. replacement = "&";
  430. } else if (c == '<') {
  431. replacement = "<";
  432. } else if (c == '\r') {
  433. replacement = " ";
  434. } else if (c == '>') {
  435. replacement = ">";
  436. } else if (c == '"') {
  437. replacement = """;
  438. } else if (c == '\'') {
  439. replacement = "'";
  440. }
  441. if (replacement != null) {
  442. if (result == null) {
  443. result = new StringBuffer(s);
  444. }
  445. result.replace(i + delta, i + delta + 1, replacement);
  446. delta += (replacement.length() - 1);
  447. }
  448. }
  449. if (result == null) {
  450. return s;
  451. }
  452. return result.toString();
  453. }
  454. private void writeln(String exp) {
  455. try {
  456. for(int i = 0; i < indentation; i++) {
  457. out.write(' ');
  458. }
  459. out.write(exp.getBytes(encoding));
  460. out.write(" \n".getBytes(encoding));
  461. }
  462. catch (IOException e) {
  463. getExceptionListener().exceptionThrown(e);
  464. }
  465. }
  466. private void outputValue(Object value, Object outer, boolean isArgument) {
  467. if (value == null) {
  468. writeln("<null/>");
  469. return;
  470. }
  471. if (value instanceof Class) {
  472. writeln("<class>" + ((Class)value).getName() + "</class>");
  473. return;
  474. }
  475. ValueData d = getValueData(value);
  476. if (d.exp != null) {
  477. Object target = d.exp.getTarget();
  478. String methodName = d.exp.getMethodName();
  479. if (target == null || methodName == null) {
  480. throw new NullPointerException((target == null ? "target" :
  481. "methodName") + " should not be null");
  482. }
  483. if (target instanceof Field && methodName.equals("get")) {
  484. Field f = (Field)target;
  485. writeln("<object class=" + quote(f.getDeclaringClass().getName()) +
  486. " field=" + quote(f.getName()) + "/>");
  487. return;
  488. }
  489. Class primitiveType = ReflectionUtils.primitiveTypeFor(value.getClass());
  490. if (primitiveType != null && target == value.getClass() &&
  491. methodName.equals("new")) {
  492. String primitiveTypeName = primitiveType.getName();
  493. // Make sure that character types are quoted correctly.
  494. if (primitiveType == Character.TYPE) {
  495. value = quoteCharacters(((Character)value).toString());
  496. }
  497. writeln("<" + primitiveTypeName + ">" + value + "</" +
  498. primitiveTypeName + ">");
  499. return;
  500. }
  501. } else if (value instanceof String) {
  502. writeln("<string>" + quoteCharacters((String)value) + "</string>");
  503. return;
  504. }
  505. if (d.name != null) {
  506. writeln("<object idref=" + quote(d.name) + "/>");
  507. return;
  508. }
  509. outputStatement(d.exp, outer, isArgument);
  510. }
  511. private void outputStatement(Statement exp, Object outer, boolean isArgument) {
  512. Object target = exp.getTarget();
  513. String methodName = exp.getMethodName();
  514. if (target == null || methodName == null) {
  515. throw new NullPointerException((target == null ? "target" :
  516. "methodName") + " should not be null");
  517. }
  518. Object[] args = exp.getArguments();
  519. boolean expression = exp.getClass() == Expression.class;
  520. Object value = (expression) ? getValue((Expression)exp) : null;
  521. String tag = (expression && isArgument) ? "object" : "void";
  522. String attributes = "";
  523. ValueData d = getValueData(value);
  524. if (expression) {
  525. if (d.refs > 1) {
  526. String instanceName = nameGenerator.instanceName(value);
  527. d.name = instanceName;
  528. attributes = attributes + " id=" + quote(instanceName);
  529. }
  530. }
  531. // Special cases for targets.
  532. if (target == outer) {
  533. }
  534. else if (target == Array.class && methodName.equals("newInstance")) {
  535. tag = "array";
  536. attributes = attributes + " class=" + quote(((Class)args[0]).getName());
  537. attributes = attributes + " length=" + quote(args[1].toString());
  538. args = new Object[]{};
  539. }
  540. else if (target.getClass() == Class.class) {
  541. attributes = attributes + " class=" + quote(((Class)target).getName());
  542. }
  543. else {
  544. d.refs = 2;
  545. outputValue(target, outer, false);
  546. outputValue(value, outer, false);
  547. return;
  548. }
  549. // Special cases for methods.
  550. if ((!expression && methodName.equals("set") && args.length == 2 &&
  551. args[0] instanceof Integer) ||
  552. (expression && methodName.equals("get") && args.length == 1 &&
  553. args[0] instanceof Integer)) {
  554. attributes = attributes + " index=" + quote(args[0].toString());
  555. args = (args.length == 1) ? new Object[]{} : new Object[]{args[1]};
  556. }
  557. else if ((!expression && methodName.startsWith("set") && args.length == 1) ||
  558. (expression && methodName.startsWith("get") && args.length == 0)) {
  559. attributes = attributes + " property=" +
  560. quote(Introspector.decapitalize(methodName.substring(3)));
  561. }
  562. else if (!methodName.equals("new") && !methodName.equals("newInstance")) {
  563. attributes = attributes + " method=" + quote(methodName);
  564. }
  565. Vector statements = statementList(value);
  566. // Use XML's short form when there is no body.
  567. if (args.length == 0 && statements.size() == 0) {
  568. writeln("<" + tag + attributes + "/>");
  569. return;
  570. }
  571. writeln("<" + tag + attributes + ">");
  572. indentation++;
  573. for(int i = 0; i < args.length; i++) {
  574. outputValue(args[i], null, true);
  575. }
  576. for(int i = 0; i < statements.size(); i++) {
  577. Statement s = (Statement)statements.get(i);
  578. outputStatement(s, value, false);
  579. }
  580. indentation--;
  581. writeln("</" + tag + ">");
  582. }
  583. }