Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/beans/Encoder.java
38829 views
/*1* Copyright (c) 2000, 2011, 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</code> 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</code>,36* in conjunction with its persistence delegates, is responsible for37* breaking the object graph down into a series of <code>Statements</code>s38* and <code>Expression</code>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* Write the specified object to the output stream.56* The serialized form will denote a series of57* expressions, the combined effect of which will create58* an equivalent object when the input stream is read.59* By default, the object is assumed to be a <em>JavaBean</em>60* with a nullary constructor, whose state is defined by61* the matching pairs of "setter" and "getter" methods62* returned by the Introspector.63*64* @param o The object to be written to the stream.65*66* @see XMLDecoder#readObject67*/68protected void writeObject(Object o) {69if (o == this) {70return;71}72PersistenceDelegate info = getPersistenceDelegate(o == null ? null : o.getClass());73info.writeObject(o, this);74}7576/**77* Sets the exception handler for this stream to <code>exceptionListener</code>.78* The exception handler is notified when this stream catches recoverable79* exceptions.80*81* @param exceptionListener The exception handler for this stream;82* if <code>null</code> the default exception listener will be used.83*84* @see #getExceptionListener85*/86public void setExceptionListener(ExceptionListener exceptionListener) {87this.exceptionListener = exceptionListener;88}8990/**91* Gets the exception handler for this stream.92*93* @return The exception handler for this stream;94* Will return the default exception listener if this has not explicitly been set.95*96* @see #setExceptionListener97*/98public ExceptionListener getExceptionListener() {99return (exceptionListener != null) ? exceptionListener : Statement.defaultExceptionListener;100}101102Object getValue(Expression exp) {103try {104return (exp == null) ? null : exp.getValue();105}106catch (Exception e) {107getExceptionListener().exceptionThrown(e);108throw new RuntimeException("failed to evaluate: " + exp.toString());109}110}111112/**113* Returns the persistence delegate for the given type.114* The persistence delegate is calculated by applying115* the following rules in order:116* <ol>117* <li>118* If a persistence delegate is associated with the given type119* by using the {@link #setPersistenceDelegate} method120* it is returned.121* <li>122* A persistence delegate is then looked up by the name123* composed of the the fully qualified name of the given type124* and the "PersistenceDelegate" postfix.125* For example, a persistence delegate for the {@code Bean} class126* should be named {@code BeanPersistenceDelegate}127* and located in the same package.128* <pre>129* public class Bean { ... }130* public class BeanPersistenceDelegate { ... }</pre>131* The instance of the {@code BeanPersistenceDelegate} class132* is returned for the {@code Bean} class.133* <li>134* If the type is {@code null},135* a shared internal persistence delegate is returned136* that encodes {@code null} value.137* <li>138* If the type is a {@code enum} declaration,139* a shared internal persistence delegate is returned140* that encodes constants of this enumeration141* by their names.142* <li>143* If the type is a primitive type or the corresponding wrapper,144* a shared internal persistence delegate is returned145* that encodes values of the given type.146* <li>147* If the type is an array,148* a shared internal persistence delegate is returned149* that encodes an array of the appropriate type and length,150* and each of its elements as if they are properties.151* <li>152* If the type is a proxy,153* a shared internal persistence delegate is returned154* that encodes a proxy instance by using155* the {@link java.lang.reflect.Proxy#newProxyInstance} method.156* <li>157* If the {@link BeanInfo} for this type has a {@link BeanDescriptor}158* which defined a "persistenceDelegate" attribute,159* the value of this named attribute is returned.160* <li>161* In all other cases the default persistence delegate is returned.162* The default persistence delegate assumes the type is a <em>JavaBean</em>,163* implying that it has a default constructor and that its state164* may be characterized by the matching pairs of "setter" and "getter"165* methods returned by the {@link Introspector} class.166* The default constructor is the constructor with the greatest number167* of parameters that has the {@link ConstructorProperties} annotation.168* If none of the constructors has the {@code ConstructorProperties} annotation,169* then the nullary constructor (constructor with no parameters) will be used.170* For example, in the following code fragment, the nullary constructor171* for the {@code Foo} class will be used,172* while the two-parameter constructor173* for the {@code Bar} class will be used.174* <pre>175* public class Foo {176* public Foo() { ... }177* public Foo(int x) { ... }178* }179* public class Bar {180* public Bar() { ... }181* @ConstructorProperties({"x"})182* public Bar(int x) { ... }183* @ConstructorProperties({"x", "y"})184* public Bar(int x, int y) { ... }185* }</pre>186* </ol>187*188* @param type the class of the objects189* @return the persistence delegate for the given type190*191* @see #setPersistenceDelegate192* @see java.beans.Introspector#getBeanInfo193* @see java.beans.BeanInfo#getBeanDescriptor194*/195public PersistenceDelegate getPersistenceDelegate(Class<?> type) {196PersistenceDelegate pd = this.finder.find(type);197if (pd == null) {198pd = MetaData.getPersistenceDelegate(type);199if (pd != null) {200this.finder.register(type, pd);201}202}203return pd;204}205206/**207* Associates the specified persistence delegate with the given type.208*209* @param type the class of objects that the specified persistence delegate applies to210* @param delegate the persistence delegate for instances of the given type211*212* @see #getPersistenceDelegate213* @see java.beans.Introspector#getBeanInfo214* @see java.beans.BeanInfo#getBeanDescriptor215*/216public void setPersistenceDelegate(Class<?> type, PersistenceDelegate delegate) {217this.finder.register(type, delegate);218}219220/**221* Removes the entry for this instance, returning the old entry.222*223* @param oldInstance The entry that should be removed.224* @return The entry that was removed.225*226* @see #get227*/228public Object remove(Object oldInstance) {229Expression exp = bindings.remove(oldInstance);230return getValue(exp);231}232233/**234* Returns a tentative value for <code>oldInstance</code> in235* the environment created by this stream. A persistence236* delegate can use its <code>mutatesTo</code> method to237* determine whether this value may be initialized to238* form the equivalent object at the output or whether239* a new object must be instantiated afresh. If the240* stream has not yet seen this value, null is returned.241*242* @param oldInstance The instance to be looked up.243* @return The object, null if the object has not been seen before.244*/245public Object get(Object oldInstance) {246if (oldInstance == null || oldInstance == this ||247oldInstance.getClass() == String.class) {248return oldInstance;249}250Expression exp = bindings.get(oldInstance);251return getValue(exp);252}253254private Object writeObject1(Object oldInstance) {255Object o = get(oldInstance);256if (o == null) {257writeObject(oldInstance);258o = get(oldInstance);259}260return o;261}262263private Statement cloneStatement(Statement oldExp) {264Object oldTarget = oldExp.getTarget();265Object newTarget = writeObject1(oldTarget);266267Object[] oldArgs = oldExp.getArguments();268Object[] newArgs = new Object[oldArgs.length];269for (int i = 0; i < oldArgs.length; i++) {270newArgs[i] = writeObject1(oldArgs[i]);271}272Statement newExp = Statement.class.equals(oldExp.getClass())273? new Statement(newTarget, oldExp.getMethodName(), newArgs)274: new Expression(newTarget, oldExp.getMethodName(), newArgs);275newExp.loader = oldExp.loader;276return newExp;277}278279/**280* Writes statement <code>oldStm</code> to the stream.281* The <code>oldStm</code> should be written entirely282* in terms of the callers environment, i.e. the283* target and all arguments should be part of the284* object graph being written. These expressions285* represent a series of "what happened" expressions286* which tell the output stream how to produce an287* object graph like the original.288* <p>289* The implementation of this method will produce290* a second expression to represent the same expression in291* an environment that will exist when the stream is read.292* This is achieved simply by calling <code>writeObject</code>293* on the target and all the arguments and building a new294* expression with the results.295*296* @param oldStm The expression to be written to the stream.297*/298public void writeStatement(Statement oldStm) {299// System.out.println("writeStatement: " + oldExp);300Statement newStm = cloneStatement(oldStm);301if (oldStm.getTarget() != this && executeStatements) {302try {303newStm.execute();304} catch (Exception e) {305getExceptionListener().exceptionThrown(new Exception("Encoder: discarding statement "306+ newStm, e));307}308}309}310311/**312* The implementation first checks to see if an313* expression with this value has already been written.314* If not, the expression is cloned, using315* the same procedure as <code>writeStatement</code>,316* and the value of this expression is reconciled317* with the value of the cloned expression318* by calling <code>writeObject</code>.319*320* @param oldExp The expression to be written to the stream.321*/322public void writeExpression(Expression oldExp) {323// System.out.println("Encoder::writeExpression: " + oldExp);324Object oldValue = getValue(oldExp);325if (get(oldValue) != null) {326return;327}328bindings.put(oldValue, (Expression)cloneStatement(oldExp));329writeObject(oldValue);330}331332void clear() {333bindings.clear();334}335336// Package private method for setting an attributes table for the encoder337void setAttribute(Object key, Object value) {338if (attributes == null) {339attributes = new HashMap<>();340}341attributes.put(key, value);342}343344Object getAttribute(Object key) {345if (attributes == null) {346return null;347}348return attributes.get(key);349}350}351352353