jaroslav@601: /* jaroslav@601: * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved. jaroslav@601: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jaroslav@601: * jaroslav@601: * This code is free software; you can redistribute it and/or modify it jaroslav@601: * under the terms of the GNU General Public License version 2 only, as jaroslav@601: * published by the Free Software Foundation. Oracle designates this jaroslav@601: * particular file as subject to the "Classpath" exception as provided jaroslav@601: * by Oracle in the LICENSE file that accompanied this code. jaroslav@601: * jaroslav@601: * This code is distributed in the hope that it will be useful, but WITHOUT jaroslav@601: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jaroslav@601: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jaroslav@601: * version 2 for more details (a copy is included in the LICENSE file that jaroslav@601: * accompanied this code). jaroslav@601: * jaroslav@601: * You should have received a copy of the GNU General Public License version jaroslav@601: * 2 along with this work; if not, write to the Free Software Foundation, jaroslav@601: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jaroslav@601: * jaroslav@601: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jaroslav@601: * or visit www.oracle.com if you need additional information or have any jaroslav@601: * questions. jaroslav@601: */ jaroslav@601: jaroslav@601: package java.io; jaroslav@601: jaroslav@601: import java.util.ArrayList; jaroslav@601: import java.util.Arrays; jaroslav@601: import java.util.List; jaroslav@604: import org.apidesign.bck2brwsr.emul.lang.System; jaroslav@601: jaroslav@601: /** jaroslav@601: * An ObjectOutputStream writes primitive data types and graphs of Java objects jaroslav@601: * to an OutputStream. The objects can be read (reconstituted) using an jaroslav@601: * ObjectInputStream. Persistent storage of objects can be accomplished by jaroslav@601: * using a file for the stream. If the stream is a network socket stream, the jaroslav@601: * objects can be reconstituted on another host or in another process. jaroslav@601: * jaroslav@601: *

Only objects that support the java.io.Serializable interface can be jaroslav@601: * written to streams. The class of each serializable object is encoded jaroslav@601: * including the class name and signature of the class, the values of the jaroslav@601: * object's fields and arrays, and the closure of any other objects referenced jaroslav@601: * from the initial objects. jaroslav@601: * jaroslav@601: *

The method writeObject is used to write an object to the stream. Any jaroslav@601: * object, including Strings and arrays, is written with writeObject. Multiple jaroslav@601: * objects or primitives can be written to the stream. The objects must be jaroslav@601: * read back from the corresponding ObjectInputstream with the same types and jaroslav@601: * in the same order as they were written. jaroslav@601: * jaroslav@601: *

Primitive data types can also be written to the stream using the jaroslav@601: * appropriate methods from DataOutput. Strings can also be written using the jaroslav@601: * writeUTF method. jaroslav@601: * jaroslav@601: *

The default serialization mechanism for an object writes the class of the jaroslav@601: * object, the class signature, and the values of all non-transient and jaroslav@601: * non-static fields. References to other objects (except in transient or jaroslav@601: * static fields) cause those objects to be written also. Multiple references jaroslav@601: * to a single object are encoded using a reference sharing mechanism so that jaroslav@601: * graphs of objects can be restored to the same shape as when the original was jaroslav@601: * written. jaroslav@601: * jaroslav@601: *

For example to write an object that can be read by the example in jaroslav@601: * ObjectInputStream: jaroslav@601: *
jaroslav@601: *

jaroslav@601:  *      FileOutputStream fos = new FileOutputStream("t.tmp");
jaroslav@601:  *      ObjectOutputStream oos = new ObjectOutputStream(fos);
jaroslav@601:  *
jaroslav@601:  *      oos.writeInt(12345);
jaroslav@601:  *      oos.writeObject("Today");
jaroslav@601:  *      oos.writeObject(new Date());
jaroslav@601:  *
jaroslav@601:  *      oos.close();
jaroslav@601:  * 
jaroslav@601: * jaroslav@601: *

Classes that require special handling during the serialization and jaroslav@601: * deserialization process must implement special methods with these exact jaroslav@601: * signatures: jaroslav@601: *
jaroslav@601: *

jaroslav@601:  * private void readObject(java.io.ObjectInputStream stream)
jaroslav@601:  *     throws IOException, ClassNotFoundException;
jaroslav@601:  * private void writeObject(java.io.ObjectOutputStream stream)
jaroslav@601:  *     throws IOException
jaroslav@601:  * private void readObjectNoData()
jaroslav@601:  *     throws ObjectStreamException;
jaroslav@601:  * 
jaroslav@601: * jaroslav@601: *

The writeObject method is responsible for writing the state of the object jaroslav@601: * for its particular class so that the corresponding readObject method can jaroslav@601: * restore it. The method does not need to concern itself with the state jaroslav@601: * belonging to the object's superclasses or subclasses. State is saved by jaroslav@601: * writing the individual fields to the ObjectOutputStream using the jaroslav@601: * writeObject method or by using the methods for primitive data types jaroslav@601: * supported by DataOutput. jaroslav@601: * jaroslav@601: *

Serialization does not write out the fields of any object that does not jaroslav@601: * implement the java.io.Serializable interface. Subclasses of Objects that jaroslav@601: * are not serializable can be serializable. In this case the non-serializable jaroslav@601: * class must have a no-arg constructor to allow its fields to be initialized. jaroslav@601: * In this case it is the responsibility of the subclass to save and restore jaroslav@601: * the state of the non-serializable class. It is frequently the case that the jaroslav@601: * fields of that class are accessible (public, package, or protected) or that jaroslav@601: * there are get and set methods that can be used to restore the state. jaroslav@601: * jaroslav@601: *

Serialization of an object can be prevented by implementing writeObject jaroslav@601: * and readObject methods that throw the NotSerializableException. The jaroslav@601: * exception will be caught by the ObjectOutputStream and abort the jaroslav@601: * serialization process. jaroslav@601: * jaroslav@601: *

Implementing the Externalizable interface allows the object to assume jaroslav@601: * complete control over the contents and format of the object's serialized jaroslav@601: * form. The methods of the Externalizable interface, writeExternal and jaroslav@601: * readExternal, are called to save and restore the objects state. When jaroslav@601: * implemented by a class they can write and read their own state using all of jaroslav@601: * the methods of ObjectOutput and ObjectInput. It is the responsibility of jaroslav@601: * the objects to handle any versioning that occurs. jaroslav@601: * jaroslav@601: *

Enum constants are serialized differently than ordinary serializable or jaroslav@601: * externalizable objects. The serialized form of an enum constant consists jaroslav@601: * solely of its name; field values of the constant are not transmitted. To jaroslav@601: * serialize an enum constant, ObjectOutputStream writes the string returned by jaroslav@601: * the constant's name method. Like other serializable or externalizable jaroslav@601: * objects, enum constants can function as the targets of back references jaroslav@601: * appearing subsequently in the serialization stream. The process by which jaroslav@601: * enum constants are serialized cannot be customized; any class-specific jaroslav@601: * writeObject and writeReplace methods defined by enum types are ignored jaroslav@601: * during serialization. Similarly, any serialPersistentFields or jaroslav@601: * serialVersionUID field declarations are also ignored--all enum types have a jaroslav@601: * fixed serialVersionUID of 0L. jaroslav@601: * jaroslav@601: *

Primitive data, excluding serializable fields and externalizable data, is jaroslav@601: * written to the ObjectOutputStream in block-data records. A block data record jaroslav@601: * is composed of a header and data. The block data header consists of a marker jaroslav@601: * and the number of bytes to follow the header. Consecutive primitive data jaroslav@601: * writes are merged into one block-data record. The blocking factor used for jaroslav@601: * a block-data record will be 1024 bytes. Each block-data record will be jaroslav@601: * filled up to 1024 bytes, or be written whenever there is a termination of jaroslav@601: * block-data mode. Calls to the ObjectOutputStream methods writeObject, jaroslav@601: * defaultWriteObject and writeFields initially terminate any existing jaroslav@601: * block-data record. jaroslav@601: * jaroslav@601: * @author Mike Warres jaroslav@601: * @author Roger Riggs jaroslav@601: * @see java.io.DataOutput jaroslav@601: * @see java.io.ObjectInputStream jaroslav@601: * @see java.io.Serializable jaroslav@601: * @see java.io.Externalizable jaroslav@601: * @see Object Serialization Specification, Section 2, Object Output Classes jaroslav@601: * @since JDK1.1 jaroslav@601: */ jaroslav@601: public class ObjectOutputStream jaroslav@601: extends OutputStream implements ObjectOutput, ObjectStreamConstants jaroslav@601: { jaroslav@601: /** filter stream for handling block data conversion */ jaroslav@601: private final BlockDataOutputStream bout; jaroslav@601: /** obj -> wire handle map */ jaroslav@601: private final HandleTable handles; jaroslav@601: /** obj -> replacement obj map */ jaroslav@601: private final ReplaceTable subs; jaroslav@601: /** stream protocol version */ jaroslav@601: private int protocol = PROTOCOL_VERSION_2; jaroslav@601: /** recursion depth */ jaroslav@601: private int depth; jaroslav@601: jaroslav@601: /** buffer for writing primitive field values */ jaroslav@601: private byte[] primVals; jaroslav@601: jaroslav@601: /** if true, invoke writeObjectOverride() instead of writeObject() */ jaroslav@601: private final boolean enableOverride; jaroslav@601: /** if true, invoke replaceObject() */ jaroslav@601: private boolean enableReplace; jaroslav@601: jaroslav@601: // values below valid only during upcalls to writeObject()/writeExternal() jaroslav@601: /** jaroslav@601: * Context during upcalls to class-defined writeObject methods; holds jaroslav@601: * object currently being serialized and descriptor for current class. jaroslav@601: * Null when not during writeObject upcall. jaroslav@601: */ jaroslav@604: private Object curContext; jaroslav@601: /** current PutField object */ jaroslav@601: private PutFieldImpl curPut; jaroslav@601: jaroslav@601: /** custom storage for debug trace info */ jaroslav@601: private final DebugTraceInfoStack debugInfoStack; jaroslav@601: jaroslav@601: /** jaroslav@601: * value of "sun.io.serialization.extendedDebugInfo" property, jaroslav@601: * as true or false for extended information about exception's place jaroslav@601: */ jaroslav@604: private static final boolean extendedDebugInfo = false; jaroslav@601: jaroslav@601: /** jaroslav@601: * Creates an ObjectOutputStream that writes to the specified OutputStream. jaroslav@601: * This constructor writes the serialization stream header to the jaroslav@601: * underlying stream; callers may wish to flush the stream immediately to jaroslav@601: * ensure that constructors for receiving ObjectInputStreams will not block jaroslav@601: * when reading the header. jaroslav@601: * jaroslav@601: *

If a security manager is installed, this constructor will check for jaroslav@601: * the "enableSubclassImplementation" SerializablePermission when invoked jaroslav@601: * directly or indirectly by the constructor of a subclass which overrides jaroslav@601: * the ObjectOutputStream.putFields or ObjectOutputStream.writeUnshared jaroslav@601: * methods. jaroslav@601: * jaroslav@601: * @param out output stream to write to jaroslav@601: * @throws IOException if an I/O error occurs while writing stream header jaroslav@601: * @throws SecurityException if untrusted subclass illegally overrides jaroslav@601: * security-sensitive methods jaroslav@601: * @throws NullPointerException if out is null jaroslav@601: * @since 1.4 jaroslav@601: * @see ObjectOutputStream#ObjectOutputStream() jaroslav@601: * @see ObjectOutputStream#putFields() jaroslav@601: * @see ObjectInputStream#ObjectInputStream(InputStream) jaroslav@601: */ jaroslav@601: public ObjectOutputStream(OutputStream out) throws IOException { jaroslav@601: verifySubclass(); jaroslav@601: bout = new BlockDataOutputStream(out); jaroslav@601: handles = new HandleTable(10, (float) 3.00); jaroslav@601: subs = new ReplaceTable(10, (float) 3.00); jaroslav@601: enableOverride = false; jaroslav@601: writeStreamHeader(); jaroslav@601: bout.setBlockDataMode(true); jaroslav@601: if (extendedDebugInfo) { jaroslav@601: debugInfoStack = new DebugTraceInfoStack(); jaroslav@601: } else { jaroslav@601: debugInfoStack = null; jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Provide a way for subclasses that are completely reimplementing jaroslav@601: * ObjectOutputStream to not have to allocate private data just used by jaroslav@601: * this implementation of ObjectOutputStream. jaroslav@601: * jaroslav@601: *

If there is a security manager installed, this method first calls the jaroslav@601: * security manager's checkPermission method with a jaroslav@601: * SerializablePermission("enableSubclassImplementation") jaroslav@601: * permission to ensure it's ok to enable subclassing. jaroslav@601: * jaroslav@601: * @throws SecurityException if a security manager exists and its jaroslav@601: * checkPermission method denies enabling jaroslav@601: * subclassing. jaroslav@601: * @see SecurityManager#checkPermission jaroslav@601: * @see java.io.SerializablePermission jaroslav@601: */ jaroslav@601: protected ObjectOutputStream() throws IOException, SecurityException { jaroslav@604: throw new SecurityException(); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Specify stream protocol version to use when writing the stream. jaroslav@601: * jaroslav@601: *

This routine provides a hook to enable the current version of jaroslav@601: * Serialization to write in a format that is backwards compatible to a jaroslav@601: * previous version of the stream format. jaroslav@601: * jaroslav@601: *

Every effort will be made to avoid introducing additional jaroslav@601: * backwards incompatibilities; however, sometimes there is no jaroslav@601: * other alternative. jaroslav@601: * jaroslav@601: * @param version use ProtocolVersion from java.io.ObjectStreamConstants. jaroslav@601: * @throws IllegalStateException if called after any objects jaroslav@601: * have been serialized. jaroslav@601: * @throws IllegalArgumentException if invalid version is passed in. jaroslav@601: * @throws IOException if I/O errors occur jaroslav@601: * @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_1 jaroslav@601: * @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_2 jaroslav@601: * @since 1.2 jaroslav@601: */ jaroslav@601: public void useProtocolVersion(int version) throws IOException { jaroslav@601: if (handles.size() != 0) { jaroslav@601: // REMIND: implement better check for pristine stream? jaroslav@601: throw new IllegalStateException("stream non-empty"); jaroslav@601: } jaroslav@601: switch (version) { jaroslav@601: case PROTOCOL_VERSION_1: jaroslav@601: case PROTOCOL_VERSION_2: jaroslav@601: protocol = version; jaroslav@601: break; jaroslav@601: jaroslav@601: default: jaroslav@601: throw new IllegalArgumentException( jaroslav@601: "unknown version: " + version); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Write the specified object to the ObjectOutputStream. The class of the jaroslav@601: * object, the signature of the class, and the values of the non-transient jaroslav@601: * and non-static fields of the class and all of its supertypes are jaroslav@601: * written. Default serialization for a class can be overridden using the jaroslav@601: * writeObject and the readObject methods. Objects referenced by this jaroslav@601: * object are written transitively so that a complete equivalent graph of jaroslav@601: * objects can be reconstructed by an ObjectInputStream. jaroslav@601: * jaroslav@601: *

Exceptions are thrown for problems with the OutputStream and for jaroslav@601: * classes that should not be serialized. All exceptions are fatal to the jaroslav@601: * OutputStream, which is left in an indeterminate state, and it is up to jaroslav@601: * the caller to ignore or recover the stream state. jaroslav@601: * jaroslav@601: * @throws InvalidClassException Something is wrong with a class used by jaroslav@601: * serialization. jaroslav@601: * @throws NotSerializableException Some object to be serialized does not jaroslav@601: * implement the java.io.Serializable interface. jaroslav@601: * @throws IOException Any exception thrown by the underlying jaroslav@601: * OutputStream. jaroslav@601: */ jaroslav@601: public final void writeObject(Object obj) throws IOException { jaroslav@601: if (enableOverride) { jaroslav@601: writeObjectOverride(obj); jaroslav@601: return; jaroslav@601: } jaroslav@601: try { jaroslav@601: writeObject0(obj, false); jaroslav@601: } catch (IOException ex) { jaroslav@601: if (depth == 0) { jaroslav@601: writeFatalException(ex); jaroslav@601: } jaroslav@601: throw ex; jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Method used by subclasses to override the default writeObject method. jaroslav@601: * This method is called by trusted subclasses of ObjectInputStream that jaroslav@601: * constructed ObjectInputStream using the protected no-arg constructor. jaroslav@601: * The subclass is expected to provide an override method with the modifier jaroslav@601: * "final". jaroslav@601: * jaroslav@601: * @param obj object to be written to the underlying stream jaroslav@601: * @throws IOException if there are I/O errors while writing to the jaroslav@601: * underlying stream jaroslav@601: * @see #ObjectOutputStream() jaroslav@601: * @see #writeObject(Object) jaroslav@601: * @since 1.2 jaroslav@601: */ jaroslav@601: protected void writeObjectOverride(Object obj) throws IOException { jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes an "unshared" object to the ObjectOutputStream. This method is jaroslav@601: * identical to writeObject, except that it always writes the given object jaroslav@601: * as a new, unique object in the stream (as opposed to a back-reference jaroslav@601: * pointing to a previously serialized instance). Specifically: jaroslav@601: *

jaroslav@601: * While writing an object via writeUnshared does not in itself guarantee a jaroslav@601: * unique reference to the object when it is deserialized, it allows a jaroslav@601: * single object to be defined multiple times in a stream, so that multiple jaroslav@601: * calls to readUnshared by the receiver will not conflict. Note that the jaroslav@601: * rules described above only apply to the base-level object written with jaroslav@601: * writeUnshared, and not to any transitively referenced sub-objects in the jaroslav@601: * object graph to be serialized. jaroslav@601: * jaroslav@601: *

ObjectOutputStream subclasses which override this method can only be jaroslav@601: * constructed in security contexts possessing the jaroslav@601: * "enableSubclassImplementation" SerializablePermission; any attempt to jaroslav@601: * instantiate such a subclass without this permission will cause a jaroslav@601: * SecurityException to be thrown. jaroslav@601: * jaroslav@601: * @param obj object to write to stream jaroslav@601: * @throws NotSerializableException if an object in the graph to be jaroslav@601: * serialized does not implement the Serializable interface jaroslav@601: * @throws InvalidClassException if a problem exists with the class of an jaroslav@601: * object to be serialized jaroslav@601: * @throws IOException if an I/O error occurs during serialization jaroslav@601: * @since 1.4 jaroslav@601: */ jaroslav@601: public void writeUnshared(Object obj) throws IOException { jaroslav@601: try { jaroslav@601: writeObject0(obj, true); jaroslav@601: } catch (IOException ex) { jaroslav@601: if (depth == 0) { jaroslav@601: writeFatalException(ex); jaroslav@601: } jaroslav@601: throw ex; jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Write the non-static and non-transient fields of the current class to jaroslav@601: * this stream. This may only be called from the writeObject method of the jaroslav@601: * class being serialized. It will throw the NotActiveException if it is jaroslav@601: * called otherwise. jaroslav@601: * jaroslav@601: * @throws IOException if I/O errors occur while writing to the underlying jaroslav@601: * OutputStream jaroslav@601: */ jaroslav@601: public void defaultWriteObject() throws IOException { jaroslav@601: if ( curContext == null ) { jaroslav@601: throw new NotActiveException("not in call to writeObject"); jaroslav@601: } jaroslav@604: Object curObj = null; // curContext.getObj(); jaroslav@604: ObjectStreamClass curDesc = null; // curContext.getDesc(); jaroslav@601: bout.setBlockDataMode(false); jaroslav@601: defaultWriteFields(curObj, curDesc); jaroslav@601: bout.setBlockDataMode(true); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Retrieve the object used to buffer persistent fields to be written to jaroslav@601: * the stream. The fields will be written to the stream when writeFields jaroslav@601: * method is called. jaroslav@601: * jaroslav@601: * @return an instance of the class Putfield that holds the serializable jaroslav@601: * fields jaroslav@601: * @throws IOException if I/O errors occur jaroslav@601: * @since 1.2 jaroslav@601: */ jaroslav@601: public ObjectOutputStream.PutField putFields() throws IOException { jaroslav@601: if (curPut == null) { jaroslav@601: if (curContext == null) { jaroslav@601: throw new NotActiveException("not in call to writeObject"); jaroslav@601: } jaroslav@604: Object curObj = null; // curContext.getObj(); jaroslav@604: ObjectStreamClass curDesc = null; // curContext.getDesc(); jaroslav@601: curPut = new PutFieldImpl(curDesc); jaroslav@601: } jaroslav@601: return curPut; jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Write the buffered fields to the stream. jaroslav@601: * jaroslav@601: * @throws IOException if I/O errors occur while writing to the underlying jaroslav@601: * stream jaroslav@601: * @throws NotActiveException Called when a classes writeObject method was jaroslav@601: * not called to write the state of the object. jaroslav@601: * @since 1.2 jaroslav@601: */ jaroslav@601: public void writeFields() throws IOException { jaroslav@601: if (curPut == null) { jaroslav@601: throw new NotActiveException("no current PutField object"); jaroslav@601: } jaroslav@601: bout.setBlockDataMode(false); jaroslav@601: curPut.writeFields(); jaroslav@601: bout.setBlockDataMode(true); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Reset will disregard the state of any objects already written to the jaroslav@601: * stream. The state is reset to be the same as a new ObjectOutputStream. jaroslav@601: * The current point in the stream is marked as reset so the corresponding jaroslav@601: * ObjectInputStream will be reset at the same point. Objects previously jaroslav@601: * written to the stream will not be refered to as already being in the jaroslav@601: * stream. They will be written to the stream again. jaroslav@601: * jaroslav@601: * @throws IOException if reset() is invoked while serializing an object. jaroslav@601: */ jaroslav@601: public void reset() throws IOException { jaroslav@601: if (depth != 0) { jaroslav@601: throw new IOException("stream active"); jaroslav@601: } jaroslav@601: bout.setBlockDataMode(false); jaroslav@601: bout.writeByte(TC_RESET); jaroslav@601: clear(); jaroslav@601: bout.setBlockDataMode(true); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Subclasses may implement this method to allow class data to be stored in jaroslav@601: * the stream. By default this method does nothing. The corresponding jaroslav@601: * method in ObjectInputStream is resolveClass. This method is called jaroslav@601: * exactly once for each unique class in the stream. The class name and jaroslav@601: * signature will have already been written to the stream. This method may jaroslav@601: * make free use of the ObjectOutputStream to save any representation of jaroslav@601: * the class it deems suitable (for example, the bytes of the class file). jaroslav@601: * The resolveClass method in the corresponding subclass of jaroslav@601: * ObjectInputStream must read and use any data or objects written by jaroslav@601: * annotateClass. jaroslav@601: * jaroslav@601: * @param cl the class to annotate custom data for jaroslav@601: * @throws IOException Any exception thrown by the underlying jaroslav@601: * OutputStream. jaroslav@601: */ jaroslav@601: protected void annotateClass(Class cl) throws IOException { jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Subclasses may implement this method to store custom data in the stream jaroslav@601: * along with descriptors for dynamic proxy classes. jaroslav@601: * jaroslav@601: *

This method is called exactly once for each unique proxy class jaroslav@601: * descriptor in the stream. The default implementation of this method in jaroslav@601: * ObjectOutputStream does nothing. jaroslav@601: * jaroslav@601: *

The corresponding method in ObjectInputStream is jaroslav@601: * resolveProxyClass. For a given subclass of jaroslav@601: * ObjectOutputStream that overrides this method, the jaroslav@601: * resolveProxyClass method in the corresponding subclass of jaroslav@601: * ObjectInputStream must read any data or objects written by jaroslav@601: * annotateProxyClass. jaroslav@601: * jaroslav@601: * @param cl the proxy class to annotate custom data for jaroslav@601: * @throws IOException any exception thrown by the underlying jaroslav@601: * OutputStream jaroslav@601: * @see ObjectInputStream#resolveProxyClass(String[]) jaroslav@601: * @since 1.3 jaroslav@601: */ jaroslav@601: protected void annotateProxyClass(Class cl) throws IOException { jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * This method will allow trusted subclasses of ObjectOutputStream to jaroslav@601: * substitute one object for another during serialization. Replacing jaroslav@601: * objects is disabled until enableReplaceObject is called. The jaroslav@601: * enableReplaceObject method checks that the stream requesting to do jaroslav@601: * replacement can be trusted. The first occurrence of each object written jaroslav@601: * into the serialization stream is passed to replaceObject. Subsequent jaroslav@601: * references to the object are replaced by the object returned by the jaroslav@601: * original call to replaceObject. To ensure that the private state of jaroslav@601: * objects is not unintentionally exposed, only trusted streams may use jaroslav@601: * replaceObject. jaroslav@601: * jaroslav@601: *

The ObjectOutputStream.writeObject method takes a parameter of type jaroslav@601: * Object (as opposed to type Serializable) to allow for cases where jaroslav@601: * non-serializable objects are replaced by serializable ones. jaroslav@601: * jaroslav@601: *

When a subclass is replacing objects it must insure that either a jaroslav@601: * complementary substitution must be made during deserialization or that jaroslav@601: * the substituted object is compatible with every field where the jaroslav@601: * reference will be stored. Objects whose type is not a subclass of the jaroslav@601: * type of the field or array element abort the serialization by raising an jaroslav@601: * exception and the object is not be stored. jaroslav@601: * jaroslav@601: *

This method is called only once when each object is first jaroslav@601: * encountered. All subsequent references to the object will be redirected jaroslav@601: * to the new object. This method should return the object to be jaroslav@601: * substituted or the original object. jaroslav@601: * jaroslav@601: *

Null can be returned as the object to be substituted, but may cause jaroslav@601: * NullReferenceException in classes that contain references to the jaroslav@601: * original object since they may be expecting an object instead of jaroslav@601: * null. jaroslav@601: * jaroslav@601: * @param obj the object to be replaced jaroslav@601: * @return the alternate object that replaced the specified one jaroslav@601: * @throws IOException Any exception thrown by the underlying jaroslav@601: * OutputStream. jaroslav@601: */ jaroslav@601: protected Object replaceObject(Object obj) throws IOException { jaroslav@601: return obj; jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Enable the stream to do replacement of objects in the stream. When jaroslav@601: * enabled, the replaceObject method is called for every object being jaroslav@601: * serialized. jaroslav@601: * jaroslav@601: *

If enable is true, and there is a security manager jaroslav@601: * installed, this method first calls the security manager's jaroslav@601: * checkPermission method with a jaroslav@601: * SerializablePermission("enableSubstitution") permission to jaroslav@601: * ensure it's ok to enable the stream to do replacement of objects in the jaroslav@601: * stream. jaroslav@601: * jaroslav@601: * @param enable boolean parameter to enable replacement of objects jaroslav@601: * @return the previous setting before this method was invoked jaroslav@601: * @throws SecurityException if a security manager exists and its jaroslav@601: * checkPermission method denies enabling the stream jaroslav@601: * to do replacement of objects in the stream. jaroslav@601: * @see SecurityManager#checkPermission jaroslav@601: * @see java.io.SerializablePermission jaroslav@601: */ jaroslav@601: protected boolean enableReplaceObject(boolean enable) jaroslav@601: throws SecurityException jaroslav@601: { jaroslav@604: throw new SecurityException(); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * The writeStreamHeader method is provided so subclasses can append or jaroslav@601: * prepend their own header to the stream. It writes the magic number and jaroslav@601: * version to the stream. jaroslav@601: * jaroslav@601: * @throws IOException if I/O errors occur while writing to the underlying jaroslav@601: * stream jaroslav@601: */ jaroslav@601: protected void writeStreamHeader() throws IOException { jaroslav@601: bout.writeShort(STREAM_MAGIC); jaroslav@601: bout.writeShort(STREAM_VERSION); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Write the specified class descriptor to the ObjectOutputStream. Class jaroslav@601: * descriptors are used to identify the classes of objects written to the jaroslav@601: * stream. Subclasses of ObjectOutputStream may override this method to jaroslav@601: * customize the way in which class descriptors are written to the jaroslav@601: * serialization stream. The corresponding method in ObjectInputStream, jaroslav@601: * readClassDescriptor, should then be overridden to jaroslav@601: * reconstitute the class descriptor from its custom stream representation. jaroslav@601: * By default, this method writes class descriptors according to the format jaroslav@601: * defined in the Object Serialization specification. jaroslav@601: * jaroslav@601: *

Note that this method will only be called if the ObjectOutputStream jaroslav@601: * is not using the old serialization stream format (set by calling jaroslav@601: * ObjectOutputStream's useProtocolVersion method). If this jaroslav@601: * serialization stream is using the old format jaroslav@601: * (PROTOCOL_VERSION_1), the class descriptor will be written jaroslav@601: * internally in a manner that cannot be overridden or customized. jaroslav@601: * jaroslav@601: * @param desc class descriptor to write to the stream jaroslav@601: * @throws IOException If an I/O error has occurred. jaroslav@601: * @see java.io.ObjectInputStream#readClassDescriptor() jaroslav@601: * @see #useProtocolVersion(int) jaroslav@601: * @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_1 jaroslav@601: * @since 1.3 jaroslav@601: */ jaroslav@601: protected void writeClassDescriptor(ObjectStreamClass desc) jaroslav@601: throws IOException jaroslav@601: { jaroslav@601: desc.writeNonProxy(this); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes a byte. This method will block until the byte is actually jaroslav@601: * written. jaroslav@601: * jaroslav@601: * @param val the byte to be written to the stream jaroslav@601: * @throws IOException If an I/O error has occurred. jaroslav@601: */ jaroslav@601: public void write(int val) throws IOException { jaroslav@601: bout.write(val); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes an array of bytes. This method will block until the bytes are jaroslav@601: * actually written. jaroslav@601: * jaroslav@601: * @param buf the data to be written jaroslav@601: * @throws IOException If an I/O error has occurred. jaroslav@601: */ jaroslav@601: public void write(byte[] buf) throws IOException { jaroslav@601: bout.write(buf, 0, buf.length, false); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes a sub array of bytes. jaroslav@601: * jaroslav@601: * @param buf the data to be written jaroslav@601: * @param off the start offset in the data jaroslav@601: * @param len the number of bytes that are written jaroslav@601: * @throws IOException If an I/O error has occurred. jaroslav@601: */ jaroslav@601: public void write(byte[] buf, int off, int len) throws IOException { jaroslav@601: if (buf == null) { jaroslav@601: throw new NullPointerException(); jaroslav@601: } jaroslav@601: int endoff = off + len; jaroslav@601: if (off < 0 || len < 0 || endoff > buf.length || endoff < 0) { jaroslav@601: throw new IndexOutOfBoundsException(); jaroslav@601: } jaroslav@601: bout.write(buf, off, len, false); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Flushes the stream. This will write any buffered output bytes and flush jaroslav@601: * through to the underlying stream. jaroslav@601: * jaroslav@601: * @throws IOException If an I/O error has occurred. jaroslav@601: */ jaroslav@601: public void flush() throws IOException { jaroslav@601: bout.flush(); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Drain any buffered data in ObjectOutputStream. Similar to flush but jaroslav@601: * does not propagate the flush to the underlying stream. jaroslav@601: * jaroslav@601: * @throws IOException if I/O errors occur while writing to the underlying jaroslav@601: * stream jaroslav@601: */ jaroslav@601: protected void drain() throws IOException { jaroslav@601: bout.drain(); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Closes the stream. This method must be called to release any resources jaroslav@601: * associated with the stream. jaroslav@601: * jaroslav@601: * @throws IOException If an I/O error has occurred. jaroslav@601: */ jaroslav@601: public void close() throws IOException { jaroslav@601: flush(); jaroslav@601: clear(); jaroslav@601: bout.close(); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes a boolean. jaroslav@601: * jaroslav@601: * @param val the boolean to be written jaroslav@601: * @throws IOException if I/O errors occur while writing to the underlying jaroslav@601: * stream jaroslav@601: */ jaroslav@601: public void writeBoolean(boolean val) throws IOException { jaroslav@601: bout.writeBoolean(val); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes an 8 bit byte. jaroslav@601: * jaroslav@601: * @param val the byte value to be written jaroslav@601: * @throws IOException if I/O errors occur while writing to the underlying jaroslav@601: * stream jaroslav@601: */ jaroslav@601: public void writeByte(int val) throws IOException { jaroslav@601: bout.writeByte(val); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes a 16 bit short. jaroslav@601: * jaroslav@601: * @param val the short value to be written jaroslav@601: * @throws IOException if I/O errors occur while writing to the underlying jaroslav@601: * stream jaroslav@601: */ jaroslav@601: public void writeShort(int val) throws IOException { jaroslav@601: bout.writeShort(val); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes a 16 bit char. jaroslav@601: * jaroslav@601: * @param val the char value to be written jaroslav@601: * @throws IOException if I/O errors occur while writing to the underlying jaroslav@601: * stream jaroslav@601: */ jaroslav@601: public void writeChar(int val) throws IOException { jaroslav@601: bout.writeChar(val); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes a 32 bit int. jaroslav@601: * jaroslav@601: * @param val the integer value to be written jaroslav@601: * @throws IOException if I/O errors occur while writing to the underlying jaroslav@601: * stream jaroslav@601: */ jaroslav@601: public void writeInt(int val) throws IOException { jaroslav@601: bout.writeInt(val); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes a 64 bit long. jaroslav@601: * jaroslav@601: * @param val the long value to be written jaroslav@601: * @throws IOException if I/O errors occur while writing to the underlying jaroslav@601: * stream jaroslav@601: */ jaroslav@601: public void writeLong(long val) throws IOException { jaroslav@601: bout.writeLong(val); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes a 32 bit float. jaroslav@601: * jaroslav@601: * @param val the float value to be written jaroslav@601: * @throws IOException if I/O errors occur while writing to the underlying jaroslav@601: * stream jaroslav@601: */ jaroslav@601: public void writeFloat(float val) throws IOException { jaroslav@601: bout.writeFloat(val); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes a 64 bit double. jaroslav@601: * jaroslav@601: * @param val the double value to be written jaroslav@601: * @throws IOException if I/O errors occur while writing to the underlying jaroslav@601: * stream jaroslav@601: */ jaroslav@601: public void writeDouble(double val) throws IOException { jaroslav@601: bout.writeDouble(val); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes a String as a sequence of bytes. jaroslav@601: * jaroslav@601: * @param str the String of bytes to be written jaroslav@601: * @throws IOException if I/O errors occur while writing to the underlying jaroslav@601: * stream jaroslav@601: */ jaroslav@601: public void writeBytes(String str) throws IOException { jaroslav@601: bout.writeBytes(str); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes a String as a sequence of chars. jaroslav@601: * jaroslav@601: * @param str the String of chars to be written jaroslav@601: * @throws IOException if I/O errors occur while writing to the underlying jaroslav@601: * stream jaroslav@601: */ jaroslav@601: public void writeChars(String str) throws IOException { jaroslav@601: bout.writeChars(str); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Primitive data write of this String in jaroslav@601: * modified UTF-8 jaroslav@601: * format. Note that there is a jaroslav@601: * significant difference between writing a String into the stream as jaroslav@601: * primitive data or as an Object. A String instance written by writeObject jaroslav@601: * is written into the stream as a String initially. Future writeObject() jaroslav@601: * calls write references to the string into the stream. jaroslav@601: * jaroslav@601: * @param str the String to be written jaroslav@601: * @throws IOException if I/O errors occur while writing to the underlying jaroslav@601: * stream jaroslav@601: */ jaroslav@601: public void writeUTF(String str) throws IOException { jaroslav@601: bout.writeUTF(str); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Provide programmatic access to the persistent fields to be written jaroslav@601: * to ObjectOutput. jaroslav@601: * jaroslav@601: * @since 1.2 jaroslav@601: */ jaroslav@601: public static abstract class PutField { jaroslav@601: jaroslav@601: /** jaroslav@601: * Put the value of the named boolean field into the persistent field. jaroslav@601: * jaroslav@601: * @param name the name of the serializable field jaroslav@601: * @param val the value to assign to the field jaroslav@601: * @throws IllegalArgumentException if name does not jaroslav@601: * match the name of a serializable field for the class whose fields jaroslav@601: * are being written, or if the type of the named field is not jaroslav@601: * boolean jaroslav@601: */ jaroslav@601: public abstract void put(String name, boolean val); jaroslav@601: jaroslav@601: /** jaroslav@601: * Put the value of the named byte field into the persistent field. jaroslav@601: * jaroslav@601: * @param name the name of the serializable field jaroslav@601: * @param val the value to assign to the field jaroslav@601: * @throws IllegalArgumentException if name does not jaroslav@601: * match the name of a serializable field for the class whose fields jaroslav@601: * are being written, or if the type of the named field is not jaroslav@601: * byte jaroslav@601: */ jaroslav@601: public abstract void put(String name, byte val); jaroslav@601: jaroslav@601: /** jaroslav@601: * Put the value of the named char field into the persistent field. jaroslav@601: * jaroslav@601: * @param name the name of the serializable field jaroslav@601: * @param val the value to assign to the field jaroslav@601: * @throws IllegalArgumentException if name does not jaroslav@601: * match the name of a serializable field for the class whose fields jaroslav@601: * are being written, or if the type of the named field is not jaroslav@601: * char jaroslav@601: */ jaroslav@601: public abstract void put(String name, char val); jaroslav@601: jaroslav@601: /** jaroslav@601: * Put the value of the named short field into the persistent field. jaroslav@601: * jaroslav@601: * @param name the name of the serializable field jaroslav@601: * @param val the value to assign to the field jaroslav@601: * @throws IllegalArgumentException if name does not jaroslav@601: * match the name of a serializable field for the class whose fields jaroslav@601: * are being written, or if the type of the named field is not jaroslav@601: * short jaroslav@601: */ jaroslav@601: public abstract void put(String name, short val); jaroslav@601: jaroslav@601: /** jaroslav@601: * Put the value of the named int field into the persistent field. jaroslav@601: * jaroslav@601: * @param name the name of the serializable field jaroslav@601: * @param val the value to assign to the field jaroslav@601: * @throws IllegalArgumentException if name does not jaroslav@601: * match the name of a serializable field for the class whose fields jaroslav@601: * are being written, or if the type of the named field is not jaroslav@601: * int jaroslav@601: */ jaroslav@601: public abstract void put(String name, int val); jaroslav@601: jaroslav@601: /** jaroslav@601: * Put the value of the named long field into the persistent field. jaroslav@601: * jaroslav@601: * @param name the name of the serializable field jaroslav@601: * @param val the value to assign to the field jaroslav@601: * @throws IllegalArgumentException if name does not jaroslav@601: * match the name of a serializable field for the class whose fields jaroslav@601: * are being written, or if the type of the named field is not jaroslav@601: * long jaroslav@601: */ jaroslav@601: public abstract void put(String name, long val); jaroslav@601: jaroslav@601: /** jaroslav@601: * Put the value of the named float field into the persistent field. jaroslav@601: * jaroslav@601: * @param name the name of the serializable field jaroslav@601: * @param val the value to assign to the field jaroslav@601: * @throws IllegalArgumentException if name does not jaroslav@601: * match the name of a serializable field for the class whose fields jaroslav@601: * are being written, or if the type of the named field is not jaroslav@601: * float jaroslav@601: */ jaroslav@601: public abstract void put(String name, float val); jaroslav@601: jaroslav@601: /** jaroslav@601: * Put the value of the named double field into the persistent field. jaroslav@601: * jaroslav@601: * @param name the name of the serializable field jaroslav@601: * @param val the value to assign to the field jaroslav@601: * @throws IllegalArgumentException if name does not jaroslav@601: * match the name of a serializable field for the class whose fields jaroslav@601: * are being written, or if the type of the named field is not jaroslav@601: * double jaroslav@601: */ jaroslav@601: public abstract void put(String name, double val); jaroslav@601: jaroslav@601: /** jaroslav@601: * Put the value of the named Object field into the persistent field. jaroslav@601: * jaroslav@601: * @param name the name of the serializable field jaroslav@601: * @param val the value to assign to the field jaroslav@601: * (which may be null) jaroslav@601: * @throws IllegalArgumentException if name does not jaroslav@601: * match the name of a serializable field for the class whose fields jaroslav@601: * are being written, or if the type of the named field is not a jaroslav@601: * reference type jaroslav@601: */ jaroslav@601: public abstract void put(String name, Object val); jaroslav@601: jaroslav@601: /** jaroslav@601: * Write the data and fields to the specified ObjectOutput stream, jaroslav@601: * which must be the same stream that produced this jaroslav@601: * PutField object. jaroslav@601: * jaroslav@601: * @param out the stream to write the data and fields to jaroslav@601: * @throws IOException if I/O errors occur while writing to the jaroslav@601: * underlying stream jaroslav@601: * @throws IllegalArgumentException if the specified stream is not jaroslav@601: * the same stream that produced this PutField jaroslav@601: * object jaroslav@601: * @deprecated This method does not write the values contained by this jaroslav@601: * PutField object in a proper format, and may jaroslav@601: * result in corruption of the serialization stream. The jaroslav@601: * correct way to write PutField data is by jaroslav@601: * calling the {@link java.io.ObjectOutputStream#writeFields()} jaroslav@601: * method. jaroslav@601: */ jaroslav@601: @Deprecated jaroslav@601: public abstract void write(ObjectOutput out) throws IOException; jaroslav@601: } jaroslav@601: jaroslav@601: jaroslav@601: /** jaroslav@601: * Returns protocol version in use. jaroslav@601: */ jaroslav@601: int getProtocolVersion() { jaroslav@601: return protocol; jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes string without allowing it to be replaced in stream. Used by jaroslav@601: * ObjectStreamClass to write class descriptor type strings. jaroslav@601: */ jaroslav@601: void writeTypeString(String str) throws IOException { jaroslav@601: int handle; jaroslav@601: if (str == null) { jaroslav@601: writeNull(); jaroslav@601: } else if ((handle = handles.lookup(str)) != -1) { jaroslav@601: writeHandle(handle); jaroslav@601: } else { jaroslav@601: writeString(str, false); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Verifies that this (possibly subclass) instance can be constructed jaroslav@601: * without violating security constraints: the subclass must not override jaroslav@601: * security-sensitive non-final methods, or else the jaroslav@601: * "enableSubclassImplementation" SerializablePermission is checked. jaroslav@601: */ jaroslav@601: private void verifySubclass() { jaroslav@601: Class cl = getClass(); jaroslav@601: if (cl == ObjectOutputStream.class) { jaroslav@601: return; jaroslav@601: } jaroslav@604: throw new SecurityException(); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Clears internal data structures. jaroslav@601: */ jaroslav@601: private void clear() { jaroslav@601: subs.clear(); jaroslav@601: handles.clear(); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Underlying writeObject/writeUnshared implementation. jaroslav@601: */ jaroslav@601: private void writeObject0(Object obj, boolean unshared) jaroslav@601: throws IOException jaroslav@601: { jaroslav@601: boolean oldMode = bout.setBlockDataMode(false); jaroslav@601: depth++; jaroslav@601: try { jaroslav@601: // handle previously written and non-replaceable objects jaroslav@601: int h; jaroslav@601: if ((obj = subs.lookup(obj)) == null) { jaroslav@601: writeNull(); jaroslav@601: return; jaroslav@601: } else if (!unshared && (h = handles.lookup(obj)) != -1) { jaroslav@601: writeHandle(h); jaroslav@601: return; jaroslav@601: } else if (obj instanceof Class) { jaroslav@601: writeClass((Class) obj, unshared); jaroslav@601: return; jaroslav@601: } else if (obj instanceof ObjectStreamClass) { jaroslav@601: writeClassDesc((ObjectStreamClass) obj, unshared); jaroslav@601: return; jaroslav@601: } jaroslav@601: jaroslav@601: // check for replacement object jaroslav@601: Object orig = obj; jaroslav@601: Class cl = obj.getClass(); jaroslav@601: ObjectStreamClass desc; jaroslav@601: for (;;) { jaroslav@601: // REMIND: skip this check for strings/arrays? jaroslav@601: Class repCl; jaroslav@601: desc = ObjectStreamClass.lookup(cl, true); jaroslav@601: if (!desc.hasWriteReplaceMethod() || jaroslav@601: (obj = desc.invokeWriteReplace(obj)) == null || jaroslav@601: (repCl = obj.getClass()) == cl) jaroslav@601: { jaroslav@601: break; jaroslav@601: } jaroslav@601: cl = repCl; jaroslav@601: } jaroslav@601: if (enableReplace) { jaroslav@601: Object rep = replaceObject(obj); jaroslav@601: if (rep != obj && rep != null) { jaroslav@601: cl = rep.getClass(); jaroslav@601: desc = ObjectStreamClass.lookup(cl, true); jaroslav@601: } jaroslav@601: obj = rep; jaroslav@601: } jaroslav@601: jaroslav@601: // if object replaced, run through original checks a second time jaroslav@601: if (obj != orig) { jaroslav@601: subs.assign(orig, obj); jaroslav@601: if (obj == null) { jaroslav@601: writeNull(); jaroslav@601: return; jaroslav@601: } else if (!unshared && (h = handles.lookup(obj)) != -1) { jaroslav@601: writeHandle(h); jaroslav@601: return; jaroslav@601: } else if (obj instanceof Class) { jaroslav@601: writeClass((Class) obj, unshared); jaroslav@601: return; jaroslav@601: } else if (obj instanceof ObjectStreamClass) { jaroslav@601: writeClassDesc((ObjectStreamClass) obj, unshared); jaroslav@601: return; jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: // remaining cases jaroslav@601: if (obj instanceof String) { jaroslav@601: writeString((String) obj, unshared); jaroslav@601: } else if (cl.isArray()) { jaroslav@601: writeArray(obj, desc, unshared); jaroslav@601: } else if (obj instanceof Enum) { jaroslav@601: writeEnum((Enum) obj, desc, unshared); jaroslav@601: } else if (obj instanceof Serializable) { jaroslav@601: writeOrdinaryObject(obj, desc, unshared); jaroslav@601: } else { jaroslav@601: if (extendedDebugInfo) { jaroslav@601: throw new NotSerializableException( jaroslav@601: cl.getName() + "\n" + debugInfoStack.toString()); jaroslav@601: } else { jaroslav@601: throw new NotSerializableException(cl.getName()); jaroslav@601: } jaroslav@601: } jaroslav@601: } finally { jaroslav@601: depth--; jaroslav@601: bout.setBlockDataMode(oldMode); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes null code to stream. jaroslav@601: */ jaroslav@601: private void writeNull() throws IOException { jaroslav@601: bout.writeByte(TC_NULL); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes given object handle to stream. jaroslav@601: */ jaroslav@601: private void writeHandle(int handle) throws IOException { jaroslav@601: bout.writeByte(TC_REFERENCE); jaroslav@601: bout.writeInt(baseWireHandle + handle); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes representation of given class to stream. jaroslav@601: */ jaroslav@601: private void writeClass(Class cl, boolean unshared) throws IOException { jaroslav@601: bout.writeByte(TC_CLASS); jaroslav@601: writeClassDesc(ObjectStreamClass.lookup(cl, true), false); jaroslav@601: handles.assign(unshared ? null : cl); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes representation of given class descriptor to stream. jaroslav@601: */ jaroslav@601: private void writeClassDesc(ObjectStreamClass desc, boolean unshared) jaroslav@601: throws IOException jaroslav@601: { jaroslav@601: int handle; jaroslav@601: if (desc == null) { jaroslav@601: writeNull(); jaroslav@601: } else if (!unshared && (handle = handles.lookup(desc)) != -1) { jaroslav@601: writeHandle(handle); jaroslav@601: } else if (desc.isProxy()) { jaroslav@601: writeProxyDesc(desc, unshared); jaroslav@601: } else { jaroslav@601: writeNonProxyDesc(desc, unshared); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes class descriptor representing a dynamic proxy class to stream. jaroslav@601: */ jaroslav@601: private void writeProxyDesc(ObjectStreamClass desc, boolean unshared) jaroslav@601: throws IOException jaroslav@601: { jaroslav@601: bout.writeByte(TC_PROXYCLASSDESC); jaroslav@601: handles.assign(unshared ? null : desc); jaroslav@601: jaroslav@601: Class cl = desc.forClass(); jaroslav@601: Class[] ifaces = cl.getInterfaces(); jaroslav@601: bout.writeInt(ifaces.length); jaroslav@601: for (int i = 0; i < ifaces.length; i++) { jaroslav@601: bout.writeUTF(ifaces[i].getName()); jaroslav@601: } jaroslav@601: jaroslav@601: bout.setBlockDataMode(true); jaroslav@601: annotateProxyClass(cl); jaroslav@601: bout.setBlockDataMode(false); jaroslav@601: bout.writeByte(TC_ENDBLOCKDATA); jaroslav@601: jaroslav@601: writeClassDesc(desc.getSuperDesc(), false); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes class descriptor representing a standard (i.e., not a dynamic jaroslav@601: * proxy) class to stream. jaroslav@601: */ jaroslav@601: private void writeNonProxyDesc(ObjectStreamClass desc, boolean unshared) jaroslav@601: throws IOException jaroslav@601: { jaroslav@601: bout.writeByte(TC_CLASSDESC); jaroslav@601: handles.assign(unshared ? null : desc); jaroslav@601: jaroslav@601: if (protocol == PROTOCOL_VERSION_1) { jaroslav@601: // do not invoke class descriptor write hook with old protocol jaroslav@601: desc.writeNonProxy(this); jaroslav@601: } else { jaroslav@601: writeClassDescriptor(desc); jaroslav@601: } jaroslav@601: jaroslav@601: Class cl = desc.forClass(); jaroslav@601: bout.setBlockDataMode(true); jaroslav@601: annotateClass(cl); jaroslav@601: bout.setBlockDataMode(false); jaroslav@601: bout.writeByte(TC_ENDBLOCKDATA); jaroslav@601: jaroslav@601: writeClassDesc(desc.getSuperDesc(), false); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes given string to stream, using standard or long UTF format jaroslav@601: * depending on string length. jaroslav@601: */ jaroslav@601: private void writeString(String str, boolean unshared) throws IOException { jaroslav@601: handles.assign(unshared ? null : str); jaroslav@601: long utflen = bout.getUTFLength(str); jaroslav@601: if (utflen <= 0xFFFF) { jaroslav@601: bout.writeByte(TC_STRING); jaroslav@601: bout.writeUTF(str, utflen); jaroslav@601: } else { jaroslav@601: bout.writeByte(TC_LONGSTRING); jaroslav@601: bout.writeLongUTF(str, utflen); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes given array object to stream. jaroslav@601: */ jaroslav@601: private void writeArray(Object array, jaroslav@601: ObjectStreamClass desc, jaroslav@601: boolean unshared) jaroslav@601: throws IOException jaroslav@601: { jaroslav@601: bout.writeByte(TC_ARRAY); jaroslav@601: writeClassDesc(desc, false); jaroslav@601: handles.assign(unshared ? null : array); jaroslav@601: jaroslav@601: Class ccl = desc.forClass().getComponentType(); jaroslav@601: if (ccl.isPrimitive()) { jaroslav@601: if (ccl == Integer.TYPE) { jaroslav@601: int[] ia = (int[]) array; jaroslav@601: bout.writeInt(ia.length); jaroslav@601: bout.writeInts(ia, 0, ia.length); jaroslav@601: } else if (ccl == Byte.TYPE) { jaroslav@601: byte[] ba = (byte[]) array; jaroslav@601: bout.writeInt(ba.length); jaroslav@601: bout.write(ba, 0, ba.length, true); jaroslav@601: } else if (ccl == Long.TYPE) { jaroslav@601: long[] ja = (long[]) array; jaroslav@601: bout.writeInt(ja.length); jaroslav@601: bout.writeLongs(ja, 0, ja.length); jaroslav@601: } else if (ccl == Float.TYPE) { jaroslav@601: float[] fa = (float[]) array; jaroslav@601: bout.writeInt(fa.length); jaroslav@601: bout.writeFloats(fa, 0, fa.length); jaroslav@601: } else if (ccl == Double.TYPE) { jaroslav@601: double[] da = (double[]) array; jaroslav@601: bout.writeInt(da.length); jaroslav@601: bout.writeDoubles(da, 0, da.length); jaroslav@601: } else if (ccl == Short.TYPE) { jaroslav@601: short[] sa = (short[]) array; jaroslav@601: bout.writeInt(sa.length); jaroslav@601: bout.writeShorts(sa, 0, sa.length); jaroslav@601: } else if (ccl == Character.TYPE) { jaroslav@601: char[] ca = (char[]) array; jaroslav@601: bout.writeInt(ca.length); jaroslav@601: bout.writeChars(ca, 0, ca.length); jaroslav@601: } else if (ccl == Boolean.TYPE) { jaroslav@601: boolean[] za = (boolean[]) array; jaroslav@601: bout.writeInt(za.length); jaroslav@601: bout.writeBooleans(za, 0, za.length); jaroslav@601: } else { jaroslav@601: throw new InternalError(); jaroslav@601: } jaroslav@601: } else { jaroslav@601: Object[] objs = (Object[]) array; jaroslav@601: int len = objs.length; jaroslav@601: bout.writeInt(len); jaroslav@601: if (extendedDebugInfo) { jaroslav@601: debugInfoStack.push( jaroslav@601: "array (class \"" + array.getClass().getName() + jaroslav@601: "\", size: " + len + ")"); jaroslav@601: } jaroslav@601: try { jaroslav@601: for (int i = 0; i < len; i++) { jaroslav@601: if (extendedDebugInfo) { jaroslav@601: debugInfoStack.push( jaroslav@601: "element of array (index: " + i + ")"); jaroslav@601: } jaroslav@601: try { jaroslav@601: writeObject0(objs[i], false); jaroslav@601: } finally { jaroslav@601: if (extendedDebugInfo) { jaroslav@601: debugInfoStack.pop(); jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: } finally { jaroslav@601: if (extendedDebugInfo) { jaroslav@601: debugInfoStack.pop(); jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes given enum constant to stream. jaroslav@601: */ jaroslav@601: private void writeEnum(Enum en, jaroslav@601: ObjectStreamClass desc, jaroslav@601: boolean unshared) jaroslav@601: throws IOException jaroslav@601: { jaroslav@601: bout.writeByte(TC_ENUM); jaroslav@601: ObjectStreamClass sdesc = desc.getSuperDesc(); jaroslav@601: writeClassDesc((sdesc.forClass() == Enum.class) ? desc : sdesc, false); jaroslav@601: handles.assign(unshared ? null : en); jaroslav@601: writeString(en.name(), false); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes representation of a "ordinary" (i.e., not a String, Class, jaroslav@601: * ObjectStreamClass, array, or enum constant) serializable object to the jaroslav@601: * stream. jaroslav@601: */ jaroslav@601: private void writeOrdinaryObject(Object obj, jaroslav@601: ObjectStreamClass desc, jaroslav@601: boolean unshared) jaroslav@601: throws IOException jaroslav@601: { jaroslav@601: if (extendedDebugInfo) { jaroslav@601: debugInfoStack.push( jaroslav@601: (depth == 1 ? "root " : "") + "object (class \"" + jaroslav@601: obj.getClass().getName() + "\", " + obj.toString() + ")"); jaroslav@601: } jaroslav@601: try { jaroslav@601: desc.checkSerialize(); jaroslav@601: jaroslav@601: bout.writeByte(TC_OBJECT); jaroslav@601: writeClassDesc(desc, false); jaroslav@601: handles.assign(unshared ? null : obj); jaroslav@601: if (desc.isExternalizable() && !desc.isProxy()) { jaroslav@601: writeExternalData((Externalizable) obj); jaroslav@601: } else { jaroslav@601: writeSerialData(obj, desc); jaroslav@601: } jaroslav@601: } finally { jaroslav@601: if (extendedDebugInfo) { jaroslav@601: debugInfoStack.pop(); jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes externalizable data of given object by invoking its jaroslav@601: * writeExternal() method. jaroslav@601: */ jaroslav@601: private void writeExternalData(Externalizable obj) throws IOException { jaroslav@601: PutFieldImpl oldPut = curPut; jaroslav@601: curPut = null; jaroslav@601: jaroslav@601: if (extendedDebugInfo) { jaroslav@601: debugInfoStack.push("writeExternal data"); jaroslav@601: } jaroslav@604: Object oldContext = curContext; jaroslav@601: try { jaroslav@601: curContext = null; jaroslav@601: if (protocol == PROTOCOL_VERSION_1) { jaroslav@601: obj.writeExternal(this); jaroslav@601: } else { jaroslav@601: bout.setBlockDataMode(true); jaroslav@601: obj.writeExternal(this); jaroslav@601: bout.setBlockDataMode(false); jaroslav@601: bout.writeByte(TC_ENDBLOCKDATA); jaroslav@601: } jaroslav@601: } finally { jaroslav@601: curContext = oldContext; jaroslav@601: if (extendedDebugInfo) { jaroslav@601: debugInfoStack.pop(); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: curPut = oldPut; jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes instance data for each serializable class of given object, from jaroslav@601: * superclass to subclass. jaroslav@601: */ jaroslav@601: private void writeSerialData(Object obj, ObjectStreamClass desc) jaroslav@601: throws IOException jaroslav@601: { jaroslav@601: ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout(); jaroslav@601: for (int i = 0; i < slots.length; i++) { jaroslav@601: ObjectStreamClass slotDesc = slots[i].desc; jaroslav@601: if (slotDesc.hasWriteObjectMethod()) { jaroslav@601: PutFieldImpl oldPut = curPut; jaroslav@601: curPut = null; jaroslav@604: Object oldContext = curContext; jaroslav@601: jaroslav@601: if (extendedDebugInfo) { jaroslav@601: debugInfoStack.push( jaroslav@601: "custom writeObject data (class \"" + jaroslav@601: slotDesc.getName() + "\")"); jaroslav@601: } jaroslav@601: try { jaroslav@604: curContext = new Object(); //new SerialCallbackContext(obj, slotDesc); jaroslav@601: bout.setBlockDataMode(true); jaroslav@601: slotDesc.invokeWriteObject(obj, this); jaroslav@601: bout.setBlockDataMode(false); jaroslav@601: bout.writeByte(TC_ENDBLOCKDATA); jaroslav@601: } finally { jaroslav@604: //curContext.setUsed(); jaroslav@601: curContext = oldContext; jaroslav@601: if (extendedDebugInfo) { jaroslav@601: debugInfoStack.pop(); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: curPut = oldPut; jaroslav@601: } else { jaroslav@601: defaultWriteFields(obj, slotDesc); jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Fetches and writes values of serializable fields of given object to jaroslav@601: * stream. The given class descriptor specifies which field values to jaroslav@601: * write, and in which order they should be written. jaroslav@601: */ jaroslav@601: private void defaultWriteFields(Object obj, ObjectStreamClass desc) jaroslav@601: throws IOException jaroslav@601: { jaroslav@601: // REMIND: perform conservative isInstance check here? jaroslav@601: desc.checkDefaultSerialize(); jaroslav@601: jaroslav@601: int primDataSize = desc.getPrimDataSize(); jaroslav@601: if (primVals == null || primVals.length < primDataSize) { jaroslav@601: primVals = new byte[primDataSize]; jaroslav@601: } jaroslav@601: desc.getPrimFieldValues(obj, primVals); jaroslav@601: bout.write(primVals, 0, primDataSize, false); jaroslav@601: jaroslav@601: ObjectStreamField[] fields = desc.getFields(false); jaroslav@601: Object[] objVals = new Object[desc.getNumObjFields()]; jaroslav@601: int numPrimFields = fields.length - objVals.length; jaroslav@601: desc.getObjFieldValues(obj, objVals); jaroslav@601: for (int i = 0; i < objVals.length; i++) { jaroslav@601: if (extendedDebugInfo) { jaroslav@601: debugInfoStack.push( jaroslav@601: "field (class \"" + desc.getName() + "\", name: \"" + jaroslav@601: fields[numPrimFields + i].getName() + "\", type: \"" + jaroslav@601: fields[numPrimFields + i].getType() + "\")"); jaroslav@601: } jaroslav@601: try { jaroslav@601: writeObject0(objVals[i], jaroslav@601: fields[numPrimFields + i].isUnshared()); jaroslav@601: } finally { jaroslav@601: if (extendedDebugInfo) { jaroslav@601: debugInfoStack.pop(); jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Attempts to write to stream fatal IOException that has caused jaroslav@601: * serialization to abort. jaroslav@601: */ jaroslav@601: private void writeFatalException(IOException ex) throws IOException { jaroslav@601: /* jaroslav@601: * Note: the serialization specification states that if a second jaroslav@601: * IOException occurs while attempting to serialize the original fatal jaroslav@601: * exception to the stream, then a StreamCorruptedException should be jaroslav@601: * thrown (section 2.1). However, due to a bug in previous jaroslav@601: * implementations of serialization, StreamCorruptedExceptions were jaroslav@601: * rarely (if ever) actually thrown--the "root" exceptions from jaroslav@601: * underlying streams were thrown instead. This historical behavior is jaroslav@601: * followed here for consistency. jaroslav@601: */ jaroslav@601: clear(); jaroslav@601: boolean oldMode = bout.setBlockDataMode(false); jaroslav@601: try { jaroslav@601: bout.writeByte(TC_EXCEPTION); jaroslav@601: writeObject0(ex, false); jaroslav@601: clear(); jaroslav@601: } finally { jaroslav@601: bout.setBlockDataMode(oldMode); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Converts specified span of float values into byte values. jaroslav@601: */ jaroslav@601: // REMIND: remove once hotspot inlines Float.floatToIntBits jaroslav@601: private static native void floatsToBytes(float[] src, int srcpos, jaroslav@601: byte[] dst, int dstpos, jaroslav@601: int nfloats); jaroslav@601: jaroslav@601: /** jaroslav@601: * Converts specified span of double values into byte values. jaroslav@601: */ jaroslav@601: // REMIND: remove once hotspot inlines Double.doubleToLongBits jaroslav@601: private static native void doublesToBytes(double[] src, int srcpos, jaroslav@601: byte[] dst, int dstpos, jaroslav@601: int ndoubles); jaroslav@601: jaroslav@601: /** jaroslav@601: * Default PutField implementation. jaroslav@601: */ jaroslav@601: private class PutFieldImpl extends PutField { jaroslav@601: jaroslav@601: /** class descriptor describing serializable fields */ jaroslav@601: private final ObjectStreamClass desc; jaroslav@601: /** primitive field values */ jaroslav@601: private final byte[] primVals; jaroslav@601: /** object field values */ jaroslav@601: private final Object[] objVals; jaroslav@601: jaroslav@601: /** jaroslav@601: * Creates PutFieldImpl object for writing fields defined in given jaroslav@601: * class descriptor. jaroslav@601: */ jaroslav@601: PutFieldImpl(ObjectStreamClass desc) { jaroslav@601: this.desc = desc; jaroslav@601: primVals = new byte[desc.getPrimDataSize()]; jaroslav@601: objVals = new Object[desc.getNumObjFields()]; jaroslav@601: } jaroslav@601: jaroslav@601: public void put(String name, boolean val) { jaroslav@601: Bits.putBoolean(primVals, getFieldOffset(name, Boolean.TYPE), val); jaroslav@601: } jaroslav@601: jaroslav@601: public void put(String name, byte val) { jaroslav@601: primVals[getFieldOffset(name, Byte.TYPE)] = val; jaroslav@601: } jaroslav@601: jaroslav@601: public void put(String name, char val) { jaroslav@601: Bits.putChar(primVals, getFieldOffset(name, Character.TYPE), val); jaroslav@601: } jaroslav@601: jaroslav@601: public void put(String name, short val) { jaroslav@601: Bits.putShort(primVals, getFieldOffset(name, Short.TYPE), val); jaroslav@601: } jaroslav@601: jaroslav@601: public void put(String name, int val) { jaroslav@601: Bits.putInt(primVals, getFieldOffset(name, Integer.TYPE), val); jaroslav@601: } jaroslav@601: jaroslav@601: public void put(String name, float val) { jaroslav@601: Bits.putFloat(primVals, getFieldOffset(name, Float.TYPE), val); jaroslav@601: } jaroslav@601: jaroslav@601: public void put(String name, long val) { jaroslav@601: Bits.putLong(primVals, getFieldOffset(name, Long.TYPE), val); jaroslav@601: } jaroslav@601: jaroslav@601: public void put(String name, double val) { jaroslav@601: Bits.putDouble(primVals, getFieldOffset(name, Double.TYPE), val); jaroslav@601: } jaroslav@601: jaroslav@601: public void put(String name, Object val) { jaroslav@601: objVals[getFieldOffset(name, Object.class)] = val; jaroslav@601: } jaroslav@601: jaroslav@601: // deprecated in ObjectOutputStream.PutField jaroslav@601: public void write(ObjectOutput out) throws IOException { jaroslav@601: /* jaroslav@601: * Applications should *not* use this method to write PutField jaroslav@601: * data, as it will lead to stream corruption if the PutField jaroslav@601: * object writes any primitive data (since block data mode is not jaroslav@601: * unset/set properly, as is done in OOS.writeFields()). This jaroslav@601: * broken implementation is being retained solely for behavioral jaroslav@601: * compatibility, in order to support applications which use jaroslav@601: * OOS.PutField.write() for writing only non-primitive data. jaroslav@601: * jaroslav@601: * Serialization of unshared objects is not implemented here since jaroslav@601: * it is not necessary for backwards compatibility; also, unshared jaroslav@601: * semantics may not be supported by the given ObjectOutput jaroslav@601: * instance. Applications which write unshared objects using the jaroslav@601: * PutField API must use OOS.writeFields(). jaroslav@601: */ jaroslav@601: if (ObjectOutputStream.this != out) { jaroslav@601: throw new IllegalArgumentException("wrong stream"); jaroslav@601: } jaroslav@601: out.write(primVals, 0, primVals.length); jaroslav@601: jaroslav@601: ObjectStreamField[] fields = desc.getFields(false); jaroslav@601: int numPrimFields = fields.length - objVals.length; jaroslav@601: // REMIND: warn if numPrimFields > 0? jaroslav@601: for (int i = 0; i < objVals.length; i++) { jaroslav@601: if (fields[numPrimFields + i].isUnshared()) { jaroslav@601: throw new IOException("cannot write unshared object"); jaroslav@601: } jaroslav@601: out.writeObject(objVals[i]); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes buffered primitive data and object fields to stream. jaroslav@601: */ jaroslav@601: void writeFields() throws IOException { jaroslav@601: bout.write(primVals, 0, primVals.length, false); jaroslav@601: jaroslav@601: ObjectStreamField[] fields = desc.getFields(false); jaroslav@601: int numPrimFields = fields.length - objVals.length; jaroslav@601: for (int i = 0; i < objVals.length; i++) { jaroslav@601: if (extendedDebugInfo) { jaroslav@601: debugInfoStack.push( jaroslav@601: "field (class \"" + desc.getName() + "\", name: \"" + jaroslav@601: fields[numPrimFields + i].getName() + "\", type: \"" + jaroslav@601: fields[numPrimFields + i].getType() + "\")"); jaroslav@601: } jaroslav@601: try { jaroslav@601: writeObject0(objVals[i], jaroslav@601: fields[numPrimFields + i].isUnshared()); jaroslav@601: } finally { jaroslav@601: if (extendedDebugInfo) { jaroslav@601: debugInfoStack.pop(); jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Returns offset of field with given name and type. A specified type jaroslav@601: * of null matches all types, Object.class matches all non-primitive jaroslav@601: * types, and any other non-null type matches assignable types only. jaroslav@601: * Throws IllegalArgumentException if no matching field found. jaroslav@601: */ jaroslav@601: private int getFieldOffset(String name, Class type) { jaroslav@601: ObjectStreamField field = desc.getField(name, type); jaroslav@601: if (field == null) { jaroslav@601: throw new IllegalArgumentException("no such field " + name + jaroslav@601: " with type " + type); jaroslav@601: } jaroslav@601: return field.getOffset(); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Buffered output stream with two modes: in default mode, outputs data in jaroslav@601: * same format as DataOutputStream; in "block data" mode, outputs data jaroslav@601: * bracketed by block data markers (see object serialization specification jaroslav@601: * for details). jaroslav@601: */ jaroslav@601: private static class BlockDataOutputStream jaroslav@601: extends OutputStream implements DataOutput jaroslav@601: { jaroslav@601: /** maximum data block length */ jaroslav@601: private static final int MAX_BLOCK_SIZE = 1024; jaroslav@601: /** maximum data block header length */ jaroslav@601: private static final int MAX_HEADER_SIZE = 5; jaroslav@601: /** (tunable) length of char buffer (for writing strings) */ jaroslav@601: private static final int CHAR_BUF_SIZE = 256; jaroslav@601: jaroslav@601: /** buffer for writing general/block data */ jaroslav@601: private final byte[] buf = new byte[MAX_BLOCK_SIZE]; jaroslav@601: /** buffer for writing block data headers */ jaroslav@601: private final byte[] hbuf = new byte[MAX_HEADER_SIZE]; jaroslav@601: /** char buffer for fast string writes */ jaroslav@601: private final char[] cbuf = new char[CHAR_BUF_SIZE]; jaroslav@601: jaroslav@601: /** block data mode */ jaroslav@601: private boolean blkmode = false; jaroslav@601: /** current offset into buf */ jaroslav@601: private int pos = 0; jaroslav@601: jaroslav@601: /** underlying output stream */ jaroslav@601: private final OutputStream out; jaroslav@601: /** loopback stream (for data writes that span data blocks) */ jaroslav@601: private final DataOutputStream dout; jaroslav@601: jaroslav@601: /** jaroslav@601: * Creates new BlockDataOutputStream on top of given underlying stream. jaroslav@601: * Block data mode is turned off by default. jaroslav@601: */ jaroslav@601: BlockDataOutputStream(OutputStream out) { jaroslav@601: this.out = out; jaroslav@601: dout = new DataOutputStream(this); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Sets block data mode to the given mode (true == on, false == off) jaroslav@601: * and returns the previous mode value. If the new mode is the same as jaroslav@601: * the old mode, no action is taken. If the new mode differs from the jaroslav@601: * old mode, any buffered data is flushed before switching to the new jaroslav@601: * mode. jaroslav@601: */ jaroslav@601: boolean setBlockDataMode(boolean mode) throws IOException { jaroslav@601: if (blkmode == mode) { jaroslav@601: return blkmode; jaroslav@601: } jaroslav@601: drain(); jaroslav@601: blkmode = mode; jaroslav@601: return !blkmode; jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Returns true if the stream is currently in block data mode, false jaroslav@601: * otherwise. jaroslav@601: */ jaroslav@601: boolean getBlockDataMode() { jaroslav@601: return blkmode; jaroslav@601: } jaroslav@601: jaroslav@601: /* ----------------- generic output stream methods ----------------- */ jaroslav@601: /* jaroslav@601: * The following methods are equivalent to their counterparts in jaroslav@601: * OutputStream, except that they partition written data into data jaroslav@601: * blocks when in block data mode. jaroslav@601: */ jaroslav@601: jaroslav@601: public void write(int b) throws IOException { jaroslav@601: if (pos >= MAX_BLOCK_SIZE) { jaroslav@601: drain(); jaroslav@601: } jaroslav@601: buf[pos++] = (byte) b; jaroslav@601: } jaroslav@601: jaroslav@601: public void write(byte[] b) throws IOException { jaroslav@601: write(b, 0, b.length, false); jaroslav@601: } jaroslav@601: jaroslav@601: public void write(byte[] b, int off, int len) throws IOException { jaroslav@601: write(b, off, len, false); jaroslav@601: } jaroslav@601: jaroslav@601: public void flush() throws IOException { jaroslav@601: drain(); jaroslav@601: out.flush(); jaroslav@601: } jaroslav@601: jaroslav@601: public void close() throws IOException { jaroslav@601: flush(); jaroslav@601: out.close(); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes specified span of byte values from given array. If copy is jaroslav@601: * true, copies the values to an intermediate buffer before writing jaroslav@601: * them to underlying stream (to avoid exposing a reference to the jaroslav@601: * original byte array). jaroslav@601: */ jaroslav@601: void write(byte[] b, int off, int len, boolean copy) jaroslav@601: throws IOException jaroslav@601: { jaroslav@601: if (!(copy || blkmode)) { // write directly jaroslav@601: drain(); jaroslav@601: out.write(b, off, len); jaroslav@601: return; jaroslav@601: } jaroslav@601: jaroslav@601: while (len > 0) { jaroslav@601: if (pos >= MAX_BLOCK_SIZE) { jaroslav@601: drain(); jaroslav@601: } jaroslav@601: if (len >= MAX_BLOCK_SIZE && !copy && pos == 0) { jaroslav@601: // avoid unnecessary copy jaroslav@601: writeBlockHeader(MAX_BLOCK_SIZE); jaroslav@601: out.write(b, off, MAX_BLOCK_SIZE); jaroslav@601: off += MAX_BLOCK_SIZE; jaroslav@601: len -= MAX_BLOCK_SIZE; jaroslav@601: } else { jaroslav@601: int wlen = Math.min(len, MAX_BLOCK_SIZE - pos); jaroslav@601: System.arraycopy(b, off, buf, pos, wlen); jaroslav@601: pos += wlen; jaroslav@601: off += wlen; jaroslav@601: len -= wlen; jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes all buffered data from this stream to the underlying stream, jaroslav@601: * but does not flush underlying stream. jaroslav@601: */ jaroslav@601: void drain() throws IOException { jaroslav@601: if (pos == 0) { jaroslav@601: return; jaroslav@601: } jaroslav@601: if (blkmode) { jaroslav@601: writeBlockHeader(pos); jaroslav@601: } jaroslav@601: out.write(buf, 0, pos); jaroslav@601: pos = 0; jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes block data header. Data blocks shorter than 256 bytes are jaroslav@601: * prefixed with a 2-byte header; all others start with a 5-byte jaroslav@601: * header. jaroslav@601: */ jaroslav@601: private void writeBlockHeader(int len) throws IOException { jaroslav@601: if (len <= 0xFF) { jaroslav@601: hbuf[0] = TC_BLOCKDATA; jaroslav@601: hbuf[1] = (byte) len; jaroslav@601: out.write(hbuf, 0, 2); jaroslav@601: } else { jaroslav@601: hbuf[0] = TC_BLOCKDATALONG; jaroslav@601: Bits.putInt(hbuf, 1, len); jaroslav@601: out.write(hbuf, 0, 5); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: jaroslav@601: /* ----------------- primitive data output methods ----------------- */ jaroslav@601: /* jaroslav@601: * The following methods are equivalent to their counterparts in jaroslav@601: * DataOutputStream, except that they partition written data into data jaroslav@601: * blocks when in block data mode. jaroslav@601: */ jaroslav@601: jaroslav@601: public void writeBoolean(boolean v) throws IOException { jaroslav@601: if (pos >= MAX_BLOCK_SIZE) { jaroslav@601: drain(); jaroslav@601: } jaroslav@601: Bits.putBoolean(buf, pos++, v); jaroslav@601: } jaroslav@601: jaroslav@601: public void writeByte(int v) throws IOException { jaroslav@601: if (pos >= MAX_BLOCK_SIZE) { jaroslav@601: drain(); jaroslav@601: } jaroslav@601: buf[pos++] = (byte) v; jaroslav@601: } jaroslav@601: jaroslav@601: public void writeChar(int v) throws IOException { jaroslav@601: if (pos + 2 <= MAX_BLOCK_SIZE) { jaroslav@601: Bits.putChar(buf, pos, (char) v); jaroslav@601: pos += 2; jaroslav@601: } else { jaroslav@601: dout.writeChar(v); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: public void writeShort(int v) throws IOException { jaroslav@601: if (pos + 2 <= MAX_BLOCK_SIZE) { jaroslav@601: Bits.putShort(buf, pos, (short) v); jaroslav@601: pos += 2; jaroslav@601: } else { jaroslav@601: dout.writeShort(v); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: public void writeInt(int v) throws IOException { jaroslav@601: if (pos + 4 <= MAX_BLOCK_SIZE) { jaroslav@601: Bits.putInt(buf, pos, v); jaroslav@601: pos += 4; jaroslav@601: } else { jaroslav@601: dout.writeInt(v); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: public void writeFloat(float v) throws IOException { jaroslav@601: if (pos + 4 <= MAX_BLOCK_SIZE) { jaroslav@601: Bits.putFloat(buf, pos, v); jaroslav@601: pos += 4; jaroslav@601: } else { jaroslav@601: dout.writeFloat(v); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: public void writeLong(long v) throws IOException { jaroslav@601: if (pos + 8 <= MAX_BLOCK_SIZE) { jaroslav@601: Bits.putLong(buf, pos, v); jaroslav@601: pos += 8; jaroslav@601: } else { jaroslav@601: dout.writeLong(v); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: public void writeDouble(double v) throws IOException { jaroslav@601: if (pos + 8 <= MAX_BLOCK_SIZE) { jaroslav@601: Bits.putDouble(buf, pos, v); jaroslav@601: pos += 8; jaroslav@601: } else { jaroslav@601: dout.writeDouble(v); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: public void writeBytes(String s) throws IOException { jaroslav@601: int endoff = s.length(); jaroslav@601: int cpos = 0; jaroslav@601: int csize = 0; jaroslav@601: for (int off = 0; off < endoff; ) { jaroslav@601: if (cpos >= csize) { jaroslav@601: cpos = 0; jaroslav@601: csize = Math.min(endoff - off, CHAR_BUF_SIZE); jaroslav@601: s.getChars(off, off + csize, cbuf, 0); jaroslav@601: } jaroslav@601: if (pos >= MAX_BLOCK_SIZE) { jaroslav@601: drain(); jaroslav@601: } jaroslav@601: int n = Math.min(csize - cpos, MAX_BLOCK_SIZE - pos); jaroslav@601: int stop = pos + n; jaroslav@601: while (pos < stop) { jaroslav@601: buf[pos++] = (byte) cbuf[cpos++]; jaroslav@601: } jaroslav@601: off += n; jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: public void writeChars(String s) throws IOException { jaroslav@601: int endoff = s.length(); jaroslav@601: for (int off = 0; off < endoff; ) { jaroslav@601: int csize = Math.min(endoff - off, CHAR_BUF_SIZE); jaroslav@601: s.getChars(off, off + csize, cbuf, 0); jaroslav@601: writeChars(cbuf, 0, csize); jaroslav@601: off += csize; jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: public void writeUTF(String s) throws IOException { jaroslav@601: writeUTF(s, getUTFLength(s)); jaroslav@601: } jaroslav@601: jaroslav@601: jaroslav@601: /* -------------- primitive data array output methods -------------- */ jaroslav@601: /* jaroslav@601: * The following methods write out spans of primitive data values. jaroslav@601: * Though equivalent to calling the corresponding primitive write jaroslav@601: * methods repeatedly, these methods are optimized for writing groups jaroslav@601: * of primitive data values more efficiently. jaroslav@601: */ jaroslav@601: jaroslav@601: void writeBooleans(boolean[] v, int off, int len) throws IOException { jaroslav@601: int endoff = off + len; jaroslav@601: while (off < endoff) { jaroslav@601: if (pos >= MAX_BLOCK_SIZE) { jaroslav@601: drain(); jaroslav@601: } jaroslav@601: int stop = Math.min(endoff, off + (MAX_BLOCK_SIZE - pos)); jaroslav@601: while (off < stop) { jaroslav@601: Bits.putBoolean(buf, pos++, v[off++]); jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: void writeChars(char[] v, int off, int len) throws IOException { jaroslav@601: int limit = MAX_BLOCK_SIZE - 2; jaroslav@601: int endoff = off + len; jaroslav@601: while (off < endoff) { jaroslav@601: if (pos <= limit) { jaroslav@601: int avail = (MAX_BLOCK_SIZE - pos) >> 1; jaroslav@601: int stop = Math.min(endoff, off + avail); jaroslav@601: while (off < stop) { jaroslav@601: Bits.putChar(buf, pos, v[off++]); jaroslav@601: pos += 2; jaroslav@601: } jaroslav@601: } else { jaroslav@601: dout.writeChar(v[off++]); jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: void writeShorts(short[] v, int off, int len) throws IOException { jaroslav@601: int limit = MAX_BLOCK_SIZE - 2; jaroslav@601: int endoff = off + len; jaroslav@601: while (off < endoff) { jaroslav@601: if (pos <= limit) { jaroslav@601: int avail = (MAX_BLOCK_SIZE - pos) >> 1; jaroslav@601: int stop = Math.min(endoff, off + avail); jaroslav@601: while (off < stop) { jaroslav@601: Bits.putShort(buf, pos, v[off++]); jaroslav@601: pos += 2; jaroslav@601: } jaroslav@601: } else { jaroslav@601: dout.writeShort(v[off++]); jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: void writeInts(int[] v, int off, int len) throws IOException { jaroslav@601: int limit = MAX_BLOCK_SIZE - 4; jaroslav@601: int endoff = off + len; jaroslav@601: while (off < endoff) { jaroslav@601: if (pos <= limit) { jaroslav@601: int avail = (MAX_BLOCK_SIZE - pos) >> 2; jaroslav@601: int stop = Math.min(endoff, off + avail); jaroslav@601: while (off < stop) { jaroslav@601: Bits.putInt(buf, pos, v[off++]); jaroslav@601: pos += 4; jaroslav@601: } jaroslav@601: } else { jaroslav@601: dout.writeInt(v[off++]); jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: void writeFloats(float[] v, int off, int len) throws IOException { jaroslav@601: int limit = MAX_BLOCK_SIZE - 4; jaroslav@601: int endoff = off + len; jaroslav@601: while (off < endoff) { jaroslav@601: if (pos <= limit) { jaroslav@601: int avail = (MAX_BLOCK_SIZE - pos) >> 2; jaroslav@601: int chunklen = Math.min(endoff - off, avail); jaroslav@601: floatsToBytes(v, off, buf, pos, chunklen); jaroslav@601: off += chunklen; jaroslav@601: pos += chunklen << 2; jaroslav@601: } else { jaroslav@601: dout.writeFloat(v[off++]); jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: void writeLongs(long[] v, int off, int len) throws IOException { jaroslav@601: int limit = MAX_BLOCK_SIZE - 8; jaroslav@601: int endoff = off + len; jaroslav@601: while (off < endoff) { jaroslav@601: if (pos <= limit) { jaroslav@601: int avail = (MAX_BLOCK_SIZE - pos) >> 3; jaroslav@601: int stop = Math.min(endoff, off + avail); jaroslav@601: while (off < stop) { jaroslav@601: Bits.putLong(buf, pos, v[off++]); jaroslav@601: pos += 8; jaroslav@601: } jaroslav@601: } else { jaroslav@601: dout.writeLong(v[off++]); jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: void writeDoubles(double[] v, int off, int len) throws IOException { jaroslav@601: int limit = MAX_BLOCK_SIZE - 8; jaroslav@601: int endoff = off + len; jaroslav@601: while (off < endoff) { jaroslav@601: if (pos <= limit) { jaroslav@601: int avail = (MAX_BLOCK_SIZE - pos) >> 3; jaroslav@601: int chunklen = Math.min(endoff - off, avail); jaroslav@601: doublesToBytes(v, off, buf, pos, chunklen); jaroslav@601: off += chunklen; jaroslav@601: pos += chunklen << 3; jaroslav@601: } else { jaroslav@601: dout.writeDouble(v[off++]); jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Returns the length in bytes of the UTF encoding of the given string. jaroslav@601: */ jaroslav@601: long getUTFLength(String s) { jaroslav@601: int len = s.length(); jaroslav@601: long utflen = 0; jaroslav@601: for (int off = 0; off < len; ) { jaroslav@601: int csize = Math.min(len - off, CHAR_BUF_SIZE); jaroslav@601: s.getChars(off, off + csize, cbuf, 0); jaroslav@601: for (int cpos = 0; cpos < csize; cpos++) { jaroslav@601: char c = cbuf[cpos]; jaroslav@601: if (c >= 0x0001 && c <= 0x007F) { jaroslav@601: utflen++; jaroslav@601: } else if (c > 0x07FF) { jaroslav@601: utflen += 3; jaroslav@601: } else { jaroslav@601: utflen += 2; jaroslav@601: } jaroslav@601: } jaroslav@601: off += csize; jaroslav@601: } jaroslav@601: return utflen; jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes the given string in UTF format. This method is used in jaroslav@601: * situations where the UTF encoding length of the string is already jaroslav@601: * known; specifying it explicitly avoids a prescan of the string to jaroslav@601: * determine its UTF length. jaroslav@601: */ jaroslav@601: void writeUTF(String s, long utflen) throws IOException { jaroslav@601: if (utflen > 0xFFFFL) { jaroslav@601: throw new UTFDataFormatException(); jaroslav@601: } jaroslav@601: writeShort((int) utflen); jaroslav@601: if (utflen == (long) s.length()) { jaroslav@601: writeBytes(s); jaroslav@601: } else { jaroslav@601: writeUTFBody(s); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes given string in "long" UTF format. "Long" UTF format is jaroslav@601: * identical to standard UTF, except that it uses an 8 byte header jaroslav@601: * (instead of the standard 2 bytes) to convey the UTF encoding length. jaroslav@601: */ jaroslav@601: void writeLongUTF(String s) throws IOException { jaroslav@601: writeLongUTF(s, getUTFLength(s)); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes given string in "long" UTF format, where the UTF encoding jaroslav@601: * length of the string is already known. jaroslav@601: */ jaroslav@601: void writeLongUTF(String s, long utflen) throws IOException { jaroslav@601: writeLong(utflen); jaroslav@601: if (utflen == (long) s.length()) { jaroslav@601: writeBytes(s); jaroslav@601: } else { jaroslav@601: writeUTFBody(s); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Writes the "body" (i.e., the UTF representation minus the 2-byte or jaroslav@601: * 8-byte length header) of the UTF encoding for the given string. jaroslav@601: */ jaroslav@601: private void writeUTFBody(String s) throws IOException { jaroslav@601: int limit = MAX_BLOCK_SIZE - 3; jaroslav@601: int len = s.length(); jaroslav@601: for (int off = 0; off < len; ) { jaroslav@601: int csize = Math.min(len - off, CHAR_BUF_SIZE); jaroslav@601: s.getChars(off, off + csize, cbuf, 0); jaroslav@601: for (int cpos = 0; cpos < csize; cpos++) { jaroslav@601: char c = cbuf[cpos]; jaroslav@601: if (pos <= limit) { jaroslav@601: if (c <= 0x007F && c != 0) { jaroslav@601: buf[pos++] = (byte) c; jaroslav@601: } else if (c > 0x07FF) { jaroslav@601: buf[pos + 2] = (byte) (0x80 | ((c >> 0) & 0x3F)); jaroslav@601: buf[pos + 1] = (byte) (0x80 | ((c >> 6) & 0x3F)); jaroslav@601: buf[pos + 0] = (byte) (0xE0 | ((c >> 12) & 0x0F)); jaroslav@601: pos += 3; jaroslav@601: } else { jaroslav@601: buf[pos + 1] = (byte) (0x80 | ((c >> 0) & 0x3F)); jaroslav@601: buf[pos + 0] = (byte) (0xC0 | ((c >> 6) & 0x1F)); jaroslav@601: pos += 2; jaroslav@601: } jaroslav@601: } else { // write one byte at a time to normalize block jaroslav@601: if (c <= 0x007F && c != 0) { jaroslav@601: write(c); jaroslav@601: } else if (c > 0x07FF) { jaroslav@601: write(0xE0 | ((c >> 12) & 0x0F)); jaroslav@601: write(0x80 | ((c >> 6) & 0x3F)); jaroslav@601: write(0x80 | ((c >> 0) & 0x3F)); jaroslav@601: } else { jaroslav@601: write(0xC0 | ((c >> 6) & 0x1F)); jaroslav@601: write(0x80 | ((c >> 0) & 0x3F)); jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: off += csize; jaroslav@601: } jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Lightweight identity hash table which maps objects to integer handles, jaroslav@601: * assigned in ascending order. jaroslav@601: */ jaroslav@601: private static class HandleTable { jaroslav@601: jaroslav@601: /* number of mappings in table/next available handle */ jaroslav@601: private int size; jaroslav@601: /* size threshold determining when to expand hash spine */ jaroslav@601: private int threshold; jaroslav@601: /* factor for computing size threshold */ jaroslav@601: private final float loadFactor; jaroslav@601: /* maps hash value -> candidate handle value */ jaroslav@601: private int[] spine; jaroslav@601: /* maps handle value -> next candidate handle value */ jaroslav@601: private int[] next; jaroslav@601: /* maps handle value -> associated object */ jaroslav@601: private Object[] objs; jaroslav@601: jaroslav@601: /** jaroslav@601: * Creates new HandleTable with given capacity and load factor. jaroslav@601: */ jaroslav@601: HandleTable(int initialCapacity, float loadFactor) { jaroslav@601: this.loadFactor = loadFactor; jaroslav@601: spine = new int[initialCapacity]; jaroslav@601: next = new int[initialCapacity]; jaroslav@601: objs = new Object[initialCapacity]; jaroslav@601: threshold = (int) (initialCapacity * loadFactor); jaroslav@601: clear(); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Assigns next available handle to given object, and returns handle jaroslav@601: * value. Handles are assigned in ascending order starting at 0. jaroslav@601: */ jaroslav@601: int assign(Object obj) { jaroslav@601: if (size >= next.length) { jaroslav@601: growEntries(); jaroslav@601: } jaroslav@601: if (size >= threshold) { jaroslav@601: growSpine(); jaroslav@601: } jaroslav@601: insert(obj, size); jaroslav@601: return size++; jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Looks up and returns handle associated with given object, or -1 if jaroslav@601: * no mapping found. jaroslav@601: */ jaroslav@601: int lookup(Object obj) { jaroslav@601: if (size == 0) { jaroslav@601: return -1; jaroslav@601: } jaroslav@601: int index = hash(obj) % spine.length; jaroslav@601: for (int i = spine[index]; i >= 0; i = next[i]) { jaroslav@601: if (objs[i] == obj) { jaroslav@601: return i; jaroslav@601: } jaroslav@601: } jaroslav@601: return -1; jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Resets table to its initial (empty) state. jaroslav@601: */ jaroslav@601: void clear() { jaroslav@601: Arrays.fill(spine, -1); jaroslav@601: Arrays.fill(objs, 0, size, null); jaroslav@601: size = 0; jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Returns the number of mappings currently in table. jaroslav@601: */ jaroslav@601: int size() { jaroslav@601: return size; jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Inserts mapping object -> handle mapping into table. Assumes table jaroslav@601: * is large enough to accommodate new mapping. jaroslav@601: */ jaroslav@601: private void insert(Object obj, int handle) { jaroslav@601: int index = hash(obj) % spine.length; jaroslav@601: objs[handle] = obj; jaroslav@601: next[handle] = spine[index]; jaroslav@601: spine[index] = handle; jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Expands the hash "spine" -- equivalent to increasing the number of jaroslav@601: * buckets in a conventional hash table. jaroslav@601: */ jaroslav@601: private void growSpine() { jaroslav@601: spine = new int[(spine.length << 1) + 1]; jaroslav@601: threshold = (int) (spine.length * loadFactor); jaroslav@601: Arrays.fill(spine, -1); jaroslav@601: for (int i = 0; i < size; i++) { jaroslav@601: insert(objs[i], i); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Increases hash table capacity by lengthening entry arrays. jaroslav@601: */ jaroslav@601: private void growEntries() { jaroslav@601: int newLength = (next.length << 1) + 1; jaroslav@601: int[] newNext = new int[newLength]; jaroslav@601: System.arraycopy(next, 0, newNext, 0, size); jaroslav@601: next = newNext; jaroslav@601: jaroslav@601: Object[] newObjs = new Object[newLength]; jaroslav@601: System.arraycopy(objs, 0, newObjs, 0, size); jaroslav@601: objs = newObjs; jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Returns hash value for given object. jaroslav@601: */ jaroslav@601: private int hash(Object obj) { jaroslav@601: return System.identityHashCode(obj) & 0x7FFFFFFF; jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Lightweight identity hash table which maps objects to replacement jaroslav@601: * objects. jaroslav@601: */ jaroslav@601: private static class ReplaceTable { jaroslav@601: jaroslav@601: /* maps object -> index */ jaroslav@601: private final HandleTable htab; jaroslav@601: /* maps index -> replacement object */ jaroslav@601: private Object[] reps; jaroslav@601: jaroslav@601: /** jaroslav@601: * Creates new ReplaceTable with given capacity and load factor. jaroslav@601: */ jaroslav@601: ReplaceTable(int initialCapacity, float loadFactor) { jaroslav@601: htab = new HandleTable(initialCapacity, loadFactor); jaroslav@601: reps = new Object[initialCapacity]; jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Enters mapping from object to replacement object. jaroslav@601: */ jaroslav@601: void assign(Object obj, Object rep) { jaroslav@601: int index = htab.assign(obj); jaroslav@601: while (index >= reps.length) { jaroslav@601: grow(); jaroslav@601: } jaroslav@601: reps[index] = rep; jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Looks up and returns replacement for given object. If no jaroslav@601: * replacement is found, returns the lookup object itself. jaroslav@601: */ jaroslav@601: Object lookup(Object obj) { jaroslav@601: int index = htab.lookup(obj); jaroslav@601: return (index >= 0) ? reps[index] : obj; jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Resets table to its initial (empty) state. jaroslav@601: */ jaroslav@601: void clear() { jaroslav@601: Arrays.fill(reps, 0, htab.size(), null); jaroslav@601: htab.clear(); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Returns the number of mappings currently in table. jaroslav@601: */ jaroslav@601: int size() { jaroslav@601: return htab.size(); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Increases table capacity. jaroslav@601: */ jaroslav@601: private void grow() { jaroslav@601: Object[] newReps = new Object[(reps.length << 1) + 1]; jaroslav@601: System.arraycopy(reps, 0, newReps, 0, reps.length); jaroslav@601: reps = newReps; jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Stack to keep debug information about the state of the jaroslav@601: * serialization process, for embedding in exception messages. jaroslav@601: */ jaroslav@601: private static class DebugTraceInfoStack { jaroslav@601: private final List stack; jaroslav@601: jaroslav@601: DebugTraceInfoStack() { jaroslav@601: stack = new ArrayList<>(); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Removes all of the elements from enclosed list. jaroslav@601: */ jaroslav@601: void clear() { jaroslav@601: stack.clear(); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Removes the object at the top of enclosed list. jaroslav@601: */ jaroslav@601: void pop() { jaroslav@601: stack.remove(stack.size()-1); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Pushes a String onto the top of enclosed list. jaroslav@601: */ jaroslav@601: void push(String entry) { jaroslav@601: stack.add("\t- " + entry); jaroslav@601: } jaroslav@601: jaroslav@601: /** jaroslav@601: * Returns a string representation of this object jaroslav@601: */ jaroslav@601: public String toString() { jaroslav@601: StringBuilder buffer = new StringBuilder(); jaroslav@601: if (!stack.isEmpty()) { jaroslav@601: for(int i = stack.size(); i > 0; i-- ) { jaroslav@601: buffer.append(stack.get(i-1) + ((i != 1) ? "\n" : "")); jaroslav@601: } jaroslav@601: } jaroslav@601: return buffer.toString(); jaroslav@601: } jaroslav@601: } jaroslav@601: jaroslav@601: }