Path: blob/master/src/java.desktop/share/classes/java/beans/XMLEncoder.java
41152 views
/*1* Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/24package java.beans;2526import java.io.*;27import java.util.*;28import java.lang.reflect.*;29import java.nio.charset.Charset;30import java.nio.charset.CharsetEncoder;31import java.nio.charset.IllegalCharsetNameException;32import java.nio.charset.UnsupportedCharsetException;3334/**35* The {@code XMLEncoder} class is a complementary alternative to36* the {@code ObjectOutputStream} and can used to generate37* a textual representation of a <em>JavaBean</em> in the same38* way that the {@code ObjectOutputStream} can39* be used to create binary representation of {@code Serializable}40* objects. For example, the following fragment can be used to create41* a textual representation the supplied <em>JavaBean</em>42* and all its properties:43* <pre>44* XMLEncoder e = new XMLEncoder(45* new BufferedOutputStream(46* new FileOutputStream("Test.xml")));47* e.writeObject(new JButton("Hello, world"));48* e.close();49* </pre>50* Despite the similarity of their APIs, the {@code XMLEncoder}51* class is exclusively designed for the purpose of archiving graphs52* of <em>JavaBean</em>s as textual representations of their public53* properties. Like Java source files, documents written this way54* have a natural immunity to changes in the implementations of the classes55* involved. The {@code ObjectOutputStream} continues to be recommended56* for interprocess communication and general purpose serialization.57* <p>58* The {@code XMLEncoder} class provides a default denotation for59* <em>JavaBean</em>s in which they are represented as XML documents60* complying with version 1.0 of the XML specification and the61* UTF-8 character encoding of the Unicode/ISO 10646 character set.62* The XML documents produced by the {@code XMLEncoder} class are:63* <ul>64* <li>65* <em>Portable and version resilient</em>: they have no dependencies66* on the private implementation of any class and so, like Java source67* files, they may be exchanged between environments which may have68* different versions of some of the classes and between VMs from69* different vendors.70* <li>71* <em>Structurally compact</em>: The {@code XMLEncoder} class72* uses a <em>redundancy elimination</em> algorithm internally so that the73* default values of a Bean's properties are not written to the stream.74* <li>75* <em>Fault tolerant</em>: Non-structural errors in the file,76* caused either by damage to the file or by API changes77* made to classes in an archive remain localized78* so that a reader can report the error and continue to load the parts79* of the document which were not affected by the error.80* </ul>81* <p>82* Below is an example of an XML archive containing83* some user interface components from the <em>swing</em> toolkit:84* <pre>85* <?xml version="1.0" encoding="UTF-8"?>86* <java version="1.0" class="java.beans.XMLDecoder">87* <object class="javax.swing.JFrame">88* <void property="name">89* <string>frame1</string>90* </void>91* <void property="bounds">92* <object class="java.awt.Rectangle">93* <int>0</int>94* <int>0</int>95* <int>200</int>96* <int>200</int>97* </object>98* </void>99* <void property="contentPane">100* <void method="add">101* <object class="javax.swing.JButton">102* <void property="label">103* <string>Hello</string>104* </void>105* </object>106* </void>107* </void>108* <void property="visible">109* <boolean>true</boolean>110* </void>111* </object>112* </java>113* </pre>114* The XML syntax uses the following conventions:115* <ul>116* <li>117* Each element represents a method call.118* <li>119* The "object" tag denotes an <em>expression</em> whose value is120* to be used as the argument to the enclosing element.121* <li>122* The "void" tag denotes a <em>statement</em> which will123* be executed, but whose result will not be used as an124* argument to the enclosing method.125* <li>126* Elements which contain elements use those elements as arguments,127* unless they have the tag: "void".128* <li>129* The name of the method is denoted by the "method" attribute.130* <li>131* XML's standard "id" and "idref" attributes are used to make132* references to previous expressions - so as to deal with133* circularities in the object graph.134* <li>135* The "class" attribute is used to specify the target of a static136* method or constructor explicitly; its value being the fully137* qualified name of the class.138* <li>139* Elements with the "void" tag are executed using140* the outer context as the target if no target is defined141* by a "class" attribute.142* <li>143* Java's String class is treated specially and is144* written <string>Hello, world</string> where145* the characters of the string are converted to bytes146* using the UTF-8 character encoding.147* </ul>148* <p>149* Although all object graphs may be written using just these three150* tags, the following definitions are included so that common151* data structures can be expressed more concisely:152* <ul>153* <li>154* The default method name is "new".155* <li>156* A reference to a java class is written in the form157* <class>javax.swing.JButton</class>.158* <li>159* Instances of the wrapper classes for Java's primitive types are written160* using the name of the primitive type as the tag. For example, an161* instance of the {@code Integer} class could be written:162* <int>123</int>. Note that the {@code XMLEncoder} class163* uses Java's reflection package in which the conversion between164* Java's primitive types and their associated "wrapper classes"165* is handled internally. The API for the {@code XMLEncoder} class166* itself deals only with {@code Object}s.167* <li>168* In an element representing a nullary method whose name169* starts with "get", the "method" attribute is replaced170* with a "property" attribute whose value is given by removing171* the "get" prefix and decapitalizing the result.172* <li>173* In an element representing a monadic method whose name174* starts with "set", the "method" attribute is replaced175* with a "property" attribute whose value is given by removing176* the "set" prefix and decapitalizing the result.177* <li>178* In an element representing a method named "get" taking one179* integer argument, the "method" attribute is replaced180* with an "index" attribute whose value the value of the181* first argument.182* <li>183* In an element representing a method named "set" taking two arguments,184* the first of which is an integer, the "method" attribute is replaced185* with an "index" attribute whose value the value of the186* first argument.187* <li>188* A reference to an array is written using the "array"189* tag. The "class" and "length" attributes specify the190* sub-type of the array and its length respectively.191* </ul>192*193*<p>194* For more information you might also want to check out195* <a href="http://www.oracle.com/technetwork/java/persistence4-140124.html">196* Using XMLEncoder</a>,197* an article in <em>The Swing Connection.</em>198* @see XMLDecoder199* @see java.io.ObjectOutputStream200*201* @since 1.4202*203* @author Philip Milne204*/205public class XMLEncoder extends Encoder implements AutoCloseable {206207private final CharsetEncoder encoder;208private final String charset;209private final boolean declaration;210211private OutputStreamWriter out;212private Object owner;213private int indentation = 0;214private boolean internal = false;215private Map<Object, ValueData> valueToExpression;216private Map<Object, List<Statement>> targetToStatementList;217private boolean preambleWritten = false;218private NameGenerator nameGenerator;219220private class ValueData {221public int refs = 0;222public boolean marked = false; // Marked -> refs > 0 unless ref was a target.223public String name = null;224public Expression exp = null;225}226227/**228* Creates a new XML encoder to write out <em>JavaBeans</em>229* to the stream {@code out} using an XML encoding.230*231* @param out the stream to which the XML representation of232* the objects will be written233*234* @throws IllegalArgumentException235* if {@code out} is {@code null}236*237* @see XMLDecoder#XMLDecoder(InputStream)238*/239public XMLEncoder(OutputStream out) {240this(out, "UTF-8", true, 0);241}242243/**244* Creates a new XML encoder to write out <em>JavaBeans</em>245* to the stream {@code out} using the given {@code charset}246* starting from the given {@code indentation}.247*248* @param out the stream to which the XML representation of249* the objects will be written250* @param charset the name of the requested charset;251* may be either a canonical name or an alias252* @param declaration whether the XML declaration should be generated;253* set this to {@code false}254* when embedding the contents in another XML document255* @param indentation the number of space characters to indent the entire XML document by256*257* @throws IllegalArgumentException258* if {@code out} or {@code charset} is {@code null},259* or if {@code indentation} is less than 0260*261* @throws IllegalCharsetNameException262* if {@code charset} name is illegal263*264* @throws UnsupportedCharsetException265* if no support for the named charset is available266* in this instance of the Java virtual machine267*268* @throws UnsupportedOperationException269* if loaded charset does not support encoding270*271* @see Charset#forName(String)272*273* @since 1.7274*/275public XMLEncoder(OutputStream out, String charset, boolean declaration, int indentation) {276if (out == null) {277throw new IllegalArgumentException("the output stream cannot be null");278}279if (indentation < 0) {280throw new IllegalArgumentException("the indentation must be >= 0");281}282Charset cs = Charset.forName(charset);283this.encoder = cs.newEncoder();284this.charset = charset;285this.declaration = declaration;286this.indentation = indentation;287this.out = new OutputStreamWriter(out, cs.newEncoder());288valueToExpression = new IdentityHashMap<>();289targetToStatementList = new IdentityHashMap<>();290nameGenerator = new NameGenerator();291}292293/**294* Sets the owner of this encoder to {@code owner}.295*296* @param owner The owner of this encoder.297*298* @see #getOwner299*/300public void setOwner(Object owner) {301this.owner = owner;302writeExpression(new Expression(this, "getOwner", new Object[0]));303}304305/**306* Gets the owner of this encoder.307*308* @return The owner of this encoder.309*310* @see #setOwner311*/312public Object getOwner() {313return owner;314}315316/**317* Write an XML representation of the specified object to the output.318*319* @param o The object to be written to the stream.320*321* @see XMLDecoder#readObject322*/323public void writeObject(Object o) {324if (internal) {325super.writeObject(o);326}327else {328writeStatement(new Statement(this, "writeObject", new Object[]{o}));329}330}331332private List<Statement> statementList(Object target) {333List<Statement> list = targetToStatementList.get(target);334if (list == null) {335list = new ArrayList<>();336targetToStatementList.put(target, list);337}338return list;339}340341342private void mark(Object o, boolean isArgument) {343if (o == null || o == this) {344return;345}346ValueData d = getValueData(o);347Expression exp = d.exp;348// Do not mark liternal strings. Other strings, which might,349// for example, come from resource bundles should still be marked.350if (o.getClass() == String.class && exp == null) {351return;352}353354// Bump the reference counts of all arguments355if (isArgument) {356d.refs++;357}358if (d.marked) {359return;360}361d.marked = true;362Object target = exp.getTarget();363mark(exp);364if (!(target instanceof Class)) {365statementList(target).add(exp);366// Pending: Why does the reference count need to367// be incremented here?368d.refs++;369}370}371372private void mark(Statement stm) {373Object[] args = stm.getArguments();374for (int i = 0; i < args.length; i++) {375Object arg = args[i];376mark(arg, true);377}378mark(stm.getTarget(), stm instanceof Expression);379}380381382/**383* Records the Statement so that the Encoder will384* produce the actual output when the stream is flushed.385* <P>386* This method should only be invoked within the context387* of initializing a persistence delegate.388*389* @param oldStm The statement that will be written390* to the stream.391* @see java.beans.PersistenceDelegate#initialize392*/393public void writeStatement(Statement oldStm) {394// System.out.println("XMLEncoder::writeStatement: " + oldStm);395boolean internal = this.internal;396this.internal = true;397try {398super.writeStatement(oldStm);399/*400Note we must do the mark first as we may401require the results of previous values in402this context for this statement.403Test case is:404os.setOwner(this);405os.writeObject(this);406*/407mark(oldStm);408Object target = oldStm.getTarget();409if (target instanceof Field) {410String method = oldStm.getMethodName();411Object[] args = oldStm.getArguments();412if ((method == null) || (args == null)) {413}414else if (method.equals("get") && (args.length == 1)) {415target = args[0];416}417else if (method.equals("set") && (args.length == 2)) {418target = args[0];419}420}421statementList(target).add(oldStm);422}423catch (Exception e) {424getExceptionListener().exceptionThrown(new Exception("XMLEncoder: discarding statement " + oldStm, e));425}426this.internal = internal;427}428429430/**431* Records the Expression so that the Encoder will432* produce the actual output when the stream is flushed.433* <P>434* This method should only be invoked within the context of435* initializing a persistence delegate or setting up an encoder to436* read from a resource bundle.437* <P>438* For more information about using resource bundles with the439* XMLEncoder, see440* <a href="http://www.oracle.com/technetwork/java/persistence4-140124.html#i18n">441* Creating Internationalized Applications</a>,442*443* @param oldExp The expression that will be written444* to the stream.445* @see java.beans.PersistenceDelegate#initialize446*/447public void writeExpression(Expression oldExp) {448boolean internal = this.internal;449this.internal = true;450Object oldValue = getValue(oldExp);451if (get(oldValue) == null || (oldValue instanceof String && !internal)) {452getValueData(oldValue).exp = oldExp;453super.writeExpression(oldExp);454}455this.internal = internal;456}457458/**459* This method writes out the preamble associated with the460* XML encoding if it has not been written already and461* then writes out all of the values that been462* written to the stream since the last time {@code flush}463* was called. After flushing, all internal references to the464* values that were written to this stream are cleared.465*/466public void flush() {467if (!preambleWritten) { // Don't do this in constructor - it throws ... pending.468if (this.declaration) {469writeln("<?xml version=" + quote("1.0") +470" encoding=" + quote(this.charset) + "?>");471}472writeln("<java version=" + quote(System.getProperty("java.version")) +473" class=" + quote(XMLDecoder.class.getName()) + ">");474preambleWritten = true;475}476indentation++;477List<Statement> statements = statementList(this);478while (!statements.isEmpty()) {479Statement s = statements.remove(0);480if ("writeObject".equals(s.getMethodName())) {481outputValue(s.getArguments()[0], this, true);482}483else {484outputStatement(s, this, false);485}486}487indentation--;488489Statement statement = getMissedStatement();490while (statement != null) {491outputStatement(statement, this, false);492statement = getMissedStatement();493}494495try {496out.flush();497}498catch (IOException e) {499getExceptionListener().exceptionThrown(e);500}501clear();502}503504void clear() {505super.clear();506nameGenerator.clear();507valueToExpression.clear();508targetToStatementList.clear();509}510511Statement getMissedStatement() {512for (List<Statement> statements : this.targetToStatementList.values()) {513for (int i = 0; i < statements.size(); i++) {514if (Statement.class == statements.get(i).getClass()) {515return statements.remove(i);516}517}518}519return null;520}521522523/**524* This method calls {@code flush}, writes the closing525* postamble and then closes the output stream associated526* with this stream.527*/528public void close() {529flush();530writeln("</java>");531try {532out.close();533}534catch (IOException e) {535getExceptionListener().exceptionThrown(e);536}537}538539private String quote(String s) {540return "\"" + s + "\"";541}542543private ValueData getValueData(Object o) {544ValueData d = valueToExpression.get(o);545if (d == null) {546d = new ValueData();547valueToExpression.put(o, d);548}549return d;550}551552/**553* Returns {@code true} if the argument,554* a Unicode code point, is valid in XML documents.555* Unicode characters fit into the low sixteen bits of a Unicode code point,556* and pairs of Unicode <em>surrogate characters</em> can be combined557* to encode Unicode code point in documents containing only Unicode.558* (The {@code char} datatype in the Java Programming Language559* represents Unicode characters, including unpaired surrogates.)560* <par>561* [2] Char ::= #x0009 | #x000A | #x000D562* | [#x0020-#xD7FF]563* | [#xE000-#xFFFD]564* | [#x10000-#x10ffff]565* </par>566*567* @param code the 32-bit Unicode code point being tested568* @return {@code true} if the Unicode code point is valid,569* {@code false} otherwise570*/571private static boolean isValidCharCode(int code) {572return (0x0020 <= code && code <= 0xD7FF)573|| (0x000A == code)574|| (0x0009 == code)575|| (0x000D == code)576|| (0xE000 <= code && code <= 0xFFFD)577|| (0x10000 <= code && code <= 0x10ffff);578}579580private void writeln(String exp) {581try {582StringBuilder sb = new StringBuilder();583for(int i = 0; i < indentation; i++) {584sb.append(' ');585}586sb.append(exp);587sb.append('\n');588this.out.write(sb.toString());589}590catch (IOException e) {591getExceptionListener().exceptionThrown(e);592}593}594595private void outputValue(Object value, Object outer, boolean isArgument) {596if (value == null) {597writeln("<null/>");598return;599}600601if (value instanceof Class) {602writeln("<class>" + ((Class)value).getName() + "</class>");603return;604}605606ValueData d = getValueData(value);607if (d.exp != null) {608Object target = d.exp.getTarget();609String methodName = d.exp.getMethodName();610611if (target == null || methodName == null) {612throw new NullPointerException((target == null ? "target" :613"methodName") + " should not be null");614}615616if (isArgument && target instanceof Field && methodName.equals("get")) {617Field f = (Field) target;618if (Modifier.isStatic(f.getModifiers())) {619writeln("<object class=" + quote(f.getDeclaringClass().getName()) +620" field=" + quote(f.getName()) + "/>");621return;622}623}624625Class<?> primitiveType = primitiveTypeFor(value.getClass());626if (primitiveType != null && target == value.getClass() &&627methodName.equals("new")) {628String primitiveTypeName = primitiveType.getName();629// Make sure that character types are quoted correctly.630if (primitiveType == Character.TYPE) {631char code = ((Character) value).charValue();632if (!isValidCharCode(code)) {633writeln(createString(code));634return;635}636value = quoteCharCode(code);637if (value == null) {638value = Character.valueOf(code);639}640}641writeln("<" + primitiveTypeName + ">" + value + "</" +642primitiveTypeName + ">");643return;644}645646} else if (value instanceof String) {647writeln(createString((String) value));648return;649}650651if (d.name != null) {652if (isArgument) {653writeln("<object idref=" + quote(d.name) + "/>");654}655else {656outputXML("void", " idref=" + quote(d.name), value);657}658}659else if (d.exp != null) {660outputStatement(d.exp, outer, isArgument);661}662}663664private static String quoteCharCode(int code) {665switch(code) {666case '&': return "&";667case '<': return "<";668case '>': return ">";669case '"': return """;670case '\'': return "'";671case '\r': return " ";672default: return null;673}674}675676private static String createString(int code) {677return "<char code=\"#" + Integer.toString(code, 16) + "\"/>";678}679680private String createString(String string) {681StringBuilder sb = new StringBuilder();682sb.append("<string>");683int index = 0;684while (index < string.length()) {685int point = string.codePointAt(index);686int count = Character.charCount(point);687688if (isValidCharCode(point) && this.encoder.canEncode(string.substring(index, index + count))) {689String value = quoteCharCode(point);690if (value != null) {691sb.append(value);692} else {693sb.appendCodePoint(point);694}695index += count;696} else {697sb.append(createString(string.charAt(index)));698index++;699}700}701sb.append("</string>");702return sb.toString();703}704705private void outputStatement(Statement exp, Object outer, boolean isArgument) {706Object target = exp.getTarget();707String methodName = exp.getMethodName();708709if (target == null || methodName == null) {710throw new NullPointerException((target == null ? "target" :711"methodName") + " should not be null");712}713714Object[] args = exp.getArguments();715boolean expression = exp.getClass() == Expression.class;716Object value = (expression) ? getValue((Expression)exp) : null;717718String tag = (expression && isArgument) ? "object" : "void";719String attributes = "";720ValueData d = getValueData(value);721722// Special cases for targets.723if (target == outer) {724}725else if (target == Array.class && methodName.equals("newInstance")) {726tag = "array";727attributes = attributes + " class=" + quote(((Class)args[0]).getName());728attributes = attributes + " length=" + quote(args[1].toString());729args = new Object[]{};730}731else if (target.getClass() == Class.class) {732attributes = attributes + " class=" + quote(((Class)target).getName());733}734else {735d.refs = 2;736if (d.name == null) {737getValueData(target).refs++;738List<Statement> statements = statementList(target);739if (!statements.contains(exp)) {740statements.add(exp);741}742outputValue(target, outer, false);743}744if (expression) {745outputValue(value, outer, isArgument);746}747return;748}749if (expression && (d.refs > 1)) {750String instanceName = nameGenerator.instanceName(value);751d.name = instanceName;752attributes = attributes + " id=" + quote(instanceName);753}754755// Special cases for methods.756if ((!expression && methodName.equals("set") && args.length == 2 &&757args[0] instanceof Integer) ||758(expression && methodName.equals("get") && args.length == 1 &&759args[0] instanceof Integer)) {760attributes = attributes + " index=" + quote(args[0].toString());761args = (args.length == 1) ? new Object[]{} : new Object[]{args[1]};762}763else if ((!expression && methodName.startsWith("set") && args.length == 1) ||764(expression && methodName.startsWith("get") && args.length == 0)) {765if (3 < methodName.length()) {766attributes = attributes + " property=" +767quote(Introspector.decapitalize(methodName.substring(3)));768}769}770else if (!methodName.equals("new") && !methodName.equals("newInstance")) {771attributes = attributes + " method=" + quote(methodName);772}773outputXML(tag, attributes, value, args);774}775776private void outputXML(String tag, String attributes, Object value, Object... args) {777List<Statement> statements = statementList(value);778// Use XML's short form when there is no body.779if (args.length == 0 && statements.size() == 0) {780writeln("<" + tag + attributes + "/>");781return;782}783784writeln("<" + tag + attributes + ">");785indentation++;786787for(int i = 0; i < args.length; i++) {788outputValue(args[i], null, true);789}790791while (!statements.isEmpty()) {792Statement s = statements.remove(0);793outputStatement(s, value, false);794}795796indentation--;797writeln("</" + tag + ">");798}799800@SuppressWarnings("rawtypes")801static Class primitiveTypeFor(Class wrapper) {802if (wrapper == Boolean.class) return Boolean.TYPE;803if (wrapper == Byte.class) return Byte.TYPE;804if (wrapper == Character.class) return Character.TYPE;805if (wrapper == Short.class) return Short.TYPE;806if (wrapper == Integer.class) return Integer.TYPE;807if (wrapper == Long.class) return Long.TYPE;808if (wrapper == Float.class) return Float.TYPE;809if (wrapper == Double.class) return Double.TYPE;810if (wrapper == Void.class) return Void.TYPE;811return null;812}813}814815816