Path: blob/master/src/java.desktop/share/classes/java/beans/Encoder.java
41152 views
/*1* Copyright (c) 2000, 2020, 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 com.sun.beans.finder.PersistenceDelegateFinder;2728import java.util.HashMap;29import java.util.IdentityHashMap;30import java.util.Map;3132/**33* An {@code Encoder} is a class which can be used to create34* files or streams that encode the state of a collection of35* JavaBeans in terms of their public APIs. The {@code Encoder},36* in conjunction with its persistence delegates, is responsible for37* breaking the object graph down into a series of {@code Statement}s38* and {@code Expression}s which can be used to create it.39* A subclass typically provides a syntax for these expressions40* using some human readable form - like Java source code or XML.41*42* @since 1.443*44* @author Philip Milne45*/4647public class Encoder {48private final PersistenceDelegateFinder finder = new PersistenceDelegateFinder();49private Map<Object, Expression> bindings = new IdentityHashMap<>();50private ExceptionListener exceptionListener;51boolean executeStatements = true;52private Map<Object, Object> attributes;5354/**55* Constructs an {@code Encoder}.56*/57public Encoder() {}5859/**60* Write the specified object to the output stream.61* The serialized form will denote a series of62* expressions, the combined effect of which will create63* an equivalent object when the input stream is read.64* By default, the object is assumed to be a <em>JavaBean</em>65* with a nullary constructor, whose state is defined by66* the matching pairs of "setter" and "getter" methods67* returned by the Introspector.68*69* @param o The object to be written to the stream.70*71* @see XMLDecoder#readObject72*/73protected void writeObject(Object o) {74if (o == this) {75return;76}77PersistenceDelegate info = getPersistenceDelegate(o == null ? null : o.getClass());78info.writeObject(o, this);79}8081/**82* Sets the exception handler for this stream to {@code exceptionListener}.83* The exception handler is notified when this stream catches recoverable84* exceptions.85*86* @param exceptionListener The exception handler for this stream;87* if {@code null} the default exception listener will be used.88*89* @see #getExceptionListener90*/91public void setExceptionListener(ExceptionListener exceptionListener) {92this.exceptionListener = exceptionListener;93}9495/**96* Gets the exception handler for this stream.97*98* @return The exception handler for this stream;99* Will return the default exception listener if this has not explicitly been set.100*101* @see #setExceptionListener102*/103public ExceptionListener getExceptionListener() {104return (exceptionListener != null) ? exceptionListener : Statement.defaultExceptionListener;105}106107Object getValue(Expression exp) {108try {109return (exp == null) ? null : exp.getValue();110}111catch (Exception e) {112getExceptionListener().exceptionThrown(e);113throw new RuntimeException("failed to evaluate: " + exp.toString());114}115}116117/**118* Returns the persistence delegate for the given type.119* The persistence delegate is calculated by applying120* the following rules in order:121* <ol>122* <li>123* If a persistence delegate is associated with the given type124* by using the {@link #setPersistenceDelegate} method125* it is returned.126* <li>127* A persistence delegate is then looked up by the name128* composed of the fully qualified name of the given type129* and the "PersistenceDelegate" postfix.130* For example, a persistence delegate for the {@code Bean} class131* should be named {@code BeanPersistenceDelegate}132* and located in the same package.133* <pre>134* public class Bean { ... }135* public class BeanPersistenceDelegate { ... }</pre>136* The instance of the {@code BeanPersistenceDelegate} class137* is returned for the {@code Bean} class.138* <li>139* If the type is {@code null},140* a shared internal persistence delegate is returned141* that encodes {@code null} value.142* <li>143* If the type is an {@code enum} declaration,144* a shared internal persistence delegate is returned145* that encodes constants of this enumeration146* by their names.147* <li>148* If the type is a primitive type or the corresponding wrapper,149* a shared internal persistence delegate is returned150* that encodes values of the given type.151* <li>152* If the type is an array,153* a shared internal persistence delegate is returned154* that encodes an array of the appropriate type and length,155* and each of its elements as if they are properties.156* <li>157* If the type is a proxy,158* a shared internal persistence delegate is returned159* that encodes a proxy instance by using160* the {@link java.lang.reflect.Proxy#newProxyInstance} method.161* <li>162* If the {@link BeanInfo} for this type has a {@link BeanDescriptor}163* which defined a "persistenceDelegate" attribute,164* the value of this named attribute is returned.165* <li>166* In all other cases the default persistence delegate is returned.167* The default persistence delegate assumes the type is a <em>JavaBean</em>,168* implying that it has a default constructor and that its state169* may be characterized by the matching pairs of "setter" and "getter"170* methods returned by the {@link Introspector} class.171* The default constructor is the constructor with the greatest number172* of parameters that has the {@link ConstructorProperties} annotation.173* If none of the constructors has the {@code ConstructorProperties} annotation,174* then the nullary constructor (constructor with no parameters) will be used.175* For example, in the following code fragment, the nullary constructor176* for the {@code Foo} class will be used,177* while the two-parameter constructor178* for the {@code Bar} class will be used.179* <pre>180* public class Foo {181* public Foo() { ... }182* public Foo(int x) { ... }183* }184* public class Bar {185* public Bar() { ... }186* @ConstructorProperties({"x"})187* public Bar(int x) { ... }188* @ConstructorProperties({"x", "y"})189* public Bar(int x, int y) { ... }190* }</pre>191* </ol>192*193* @param type the class of the objects194* @return the persistence delegate for the given type195*196* @see #setPersistenceDelegate197* @see java.beans.Introspector#getBeanInfo198* @see java.beans.BeanInfo#getBeanDescriptor199*/200public PersistenceDelegate getPersistenceDelegate(Class<?> type) {201PersistenceDelegate pd = this.finder.find(type);202if (pd == null) {203pd = MetaData.getPersistenceDelegate(type);204if (pd != null) {205this.finder.register(type, pd);206}207}208return pd;209}210211/**212* Associates the specified persistence delegate with the given type.213*214* @param type the class of objects that the specified persistence delegate applies to215* @param delegate the persistence delegate for instances of the given type216*217* @see #getPersistenceDelegate218* @see java.beans.Introspector#getBeanInfo219* @see java.beans.BeanInfo#getBeanDescriptor220*/221public void setPersistenceDelegate(Class<?> type, PersistenceDelegate delegate) {222this.finder.register(type, delegate);223}224225/**226* Removes the entry for this instance, returning the old entry.227*228* @param oldInstance The entry that should be removed.229* @return The entry that was removed.230*231* @see #get232*/233public Object remove(Object oldInstance) {234Expression exp = bindings.remove(oldInstance);235return getValue(exp);236}237238/**239* Returns a tentative value for {@code oldInstance} in240* the environment created by this stream. A persistence241* delegate can use its {@code mutatesTo} method to242* determine whether this value may be initialized to243* form the equivalent object at the output or whether244* a new object must be instantiated afresh. If the245* stream has not yet seen this value, null is returned.246*247* @param oldInstance The instance to be looked up.248* @return The object, null if the object has not been seen before.249*/250public Object get(Object oldInstance) {251if (oldInstance == null || oldInstance == this ||252oldInstance.getClass() == String.class) {253return oldInstance;254}255Expression exp = bindings.get(oldInstance);256return getValue(exp);257}258259private Object writeObject1(Object oldInstance) {260Object o = get(oldInstance);261if (o == null) {262writeObject(oldInstance);263o = get(oldInstance);264}265return o;266}267268private Statement cloneStatement(Statement oldExp) {269Object oldTarget = oldExp.getTarget();270Object newTarget = writeObject1(oldTarget);271272Object[] oldArgs = oldExp.getArguments();273Object[] newArgs = new Object[oldArgs.length];274for (int i = 0; i < oldArgs.length; i++) {275newArgs[i] = writeObject1(oldArgs[i]);276}277Statement newExp = Statement.class.equals(oldExp.getClass())278? new Statement(newTarget, oldExp.getMethodName(), newArgs)279: new Expression(newTarget, oldExp.getMethodName(), newArgs);280newExp.loader = oldExp.loader;281return newExp;282}283284/**285* Writes statement {@code oldStm} to the stream.286* The {@code oldStm} should be written entirely287* in terms of the callers environment, i.e. the288* target and all arguments should be part of the289* object graph being written. These expressions290* represent a series of "what happened" expressions291* which tell the output stream how to produce an292* object graph like the original.293* <p>294* The implementation of this method will produce295* a second expression to represent the same expression in296* an environment that will exist when the stream is read.297* This is achieved simply by calling {@code writeObject}298* on the target and all the arguments and building a new299* expression with the results.300*301* @param oldStm The expression to be written to the stream.302*/303public void writeStatement(Statement oldStm) {304// System.out.println("writeStatement: " + oldExp);305Statement newStm = cloneStatement(oldStm);306if (oldStm.getTarget() != this && executeStatements) {307try {308newStm.execute();309} catch (Exception e) {310getExceptionListener().exceptionThrown(new Exception("Encoder: discarding statement "311+ newStm, e));312}313}314}315316/**317* The implementation first checks to see if an318* expression with this value has already been written.319* If not, the expression is cloned, using320* the same procedure as {@code writeStatement},321* and the value of this expression is reconciled322* with the value of the cloned expression323* by calling {@code writeObject}.324*325* @param oldExp The expression to be written to the stream.326*/327public void writeExpression(Expression oldExp) {328// System.out.println("Encoder::writeExpression: " + oldExp);329Object oldValue = getValue(oldExp);330if (get(oldValue) != null) {331return;332}333bindings.put(oldValue, (Expression)cloneStatement(oldExp));334writeObject(oldValue);335}336337void clear() {338bindings.clear();339}340341// Package private method for setting an attributes table for the encoder342void setAttribute(Object key, Object value) {343if (attributes == null) {344attributes = new HashMap<>();345}346attributes.put(key, value);347}348349Object getAttribute(Object key) {350if (attributes == null) {351return null;352}353return attributes.get(key);354}355}356357358