Source Code Cross Referenced for ObjectInputStream.java in  » Science » Cougaar12_4 » java » io » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Science » Cougaar12_4 » java.io 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /** Modified by cougaar
0002:         * <copyright>
0003:         *  Copyright 2003 BBNT Solutions, LLC
0004:         *  under sponsorship of the Defense Advanced Research Projects Agency (DARPA).
0005:         * 
0006:         *  This program is free software; you can redistribute it and/or modify
0007:         *  it under the terms of the Cougaar Open Source License as published by
0008:         *  DARPA on the Cougaar Open Source Website (www.cougaar.org).
0009:         * 
0010:         *  THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS
0011:         *  PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR
0012:         *  IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF
0013:         *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT
0014:         *  ANY WARRANTIES AS TO NON-INFRINGEMENT.  IN NO EVENT SHALL COPYRIGHT
0015:         *  HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL
0016:         *  DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS,
0017:         *  TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
0018:         *  PERFORMANCE OF THE COUGAAR SOFTWARE.
0019:         * </copyright>
0020:         **/package java.io;
0021:
0022:        import java.lang.reflect.Array;
0023:        import java.lang.reflect.Modifier;
0024:        import java.lang.reflect.Proxy;
0025:        import java.security.AccessController;
0026:        import java.security.PrivilegedAction;
0027:        import java.util.Arrays;
0028:        import java.util.HashMap;
0029:        import sun.misc.SoftCache;
0030:
0031:        /**
0032:         * An ObjectInputStream deserializes primitive data and objects previously
0033:         * written using an ObjectOutputStream.
0034:         * 
0035:         * <p>ObjectOutputStream and ObjectInputStream can provide an application with
0036:         * persistent storage for graphs of objects when used with a FileOutputStream
0037:         * and FileInputStream respectively.  ObjectInputStream is used to recover
0038:         * those objects previously serialized. Other uses include passing objects
0039:         * between hosts using a socket stream or for marshaling and unmarshaling
0040:         * arguments and parameters in a remote communication system.
0041:         *
0042:         * <p>ObjectInputStream ensures that the types of all objects in the graph
0043:         * created from the stream match the classes present in the Java Virtual
0044:         * Machine.  Classes are loaded as required using the standard mechanisms.
0045:         *
0046:         * <p>Only objects that support the java.io.Serializable or
0047:         * java.io.Externalizable interface can be read from streams.
0048:         *
0049:         * <p>The method <code>readObject</code> is used to read an object from the
0050:         * stream.  Java's safe casting should be used to get the desired type.  In
0051:         * Java, strings and arrays are objects and are treated as objects during
0052:         * serialization. When read they need to be cast to the expected type.
0053:         *
0054:         * <p>Primitive data types can be read from the stream using the appropriate
0055:         * method on DataInput.
0056:         * 
0057:         * <p>The default deserialization mechanism for objects restores the contents
0058:         * of each field to the value and type it had when it was written.  Fields
0059:         * declared as transient or static are ignored by the deserialization process.
0060:         * References to other objects cause those objects to be read from the stream
0061:         * as necessary.  Graphs of objects are restored correctly using a reference
0062:         * sharing mechanism.  New objects are always allocated when deserializing,
0063:         * which prevents existing objects from being overwritten.
0064:         *
0065:         * <p>Reading an object is analogous to running the constructors of a new
0066:         * object.  Memory is allocated for the object and initialized to zero (NULL).
0067:         * No-arg constructors are invoked for the non-serializable classes and then
0068:         * the fields of the serializable classes are restored from the stream starting
0069:         * with the serializable class closest to java.lang.object and finishing with
0070:         * the object's most specific class.
0071:         *
0072:         * <p>For example to read from a stream as written by the example in
0073:         * ObjectOutputStream:
0074:         * <br>
0075:         * <pre>
0076:         *	FileInputStream fis = new FileInputStream("t.tmp");
0077:         *	ObjectInputStream ois = new ObjectInputStream(fis);
0078:         *
0079:         *	int i = ois.readInt();
0080:         *	String today = (String) ois.readObject();
0081:         *	Date date = (Date) ois.readObject();
0082:         *
0083:         *	ois.close();
0084:         * </pre>
0085:         *
0086:         * <p>Classes control how they are serialized by implementing either the
0087:         * java.io.Serializable or java.io.Externalizable interfaces.
0088:         *
0089:         * <p>Implementing the Serializable interface allows object serialization to
0090:         * save and restore the entire state of the object and it allows classes to
0091:         * evolve between the time the stream is written and the time it is read.  It
0092:         * automatically traverses references between objects, saving and restoring
0093:         * entire graphs.
0094:         *
0095:         * <p>Serializable classes that require special handling during the
0096:         * serialization and deserialization process should implement the following
0097:         * methods:<p>
0098:         * 
0099:         * <pre>
0100:         * private void writeObject(java.io.ObjectOutputStream stream)
0101:         *     throws IOException;
0102:         * private void readObject(java.io.ObjectInputStream stream)
0103:         *     throws IOException, ClassNotFoundException; 
0104:         * private void readObjectNoData() 
0105:         *     throws ObjectStreamException;
0106:         * </pre>
0107:         *
0108:         * <p>The readObject method is responsible for reading and restoring the state
0109:         * of the object for its particular class using data written to the stream by
0110:         * the corresponding writeObject method.  The method does not need to concern
0111:         * itself with the state belonging to its superclasses or subclasses.  State is
0112:         * restored by reading data from the ObjectInputStream for the individual
0113:         * fields and making assignments to the appropriate fields of the object.
0114:         * Reading primitive data types is supported by DataInput.
0115:         *
0116:         * <p>Any attempt to read object data which exceeds the boundaries of the
0117:         * custom data written by the corresponding writeObject method will cause an
0118:         * OptionalDataException to be thrown with an eof field value of true.
0119:         * Non-object reads which exceed the end of the allotted data will reflect the
0120:         * end of data in the same way that they would indicate the end of the stream:
0121:         * bytewise reads will return -1 as the byte read or number of bytes read, and
0122:         * primitive reads will throw EOFExceptions.  If there is no corresponding
0123:         * writeObject method, then the end of default serialized data marks the end of
0124:         * the allotted data.
0125:         *
0126:         * <p>Primitive and object read calls issued from within a readExternal method
0127:         * behave in the same manner--if the stream is already positioned at the end of
0128:         * data written by the corresponding writeExternal method, object reads will
0129:         * throw OptionalDataExceptions with eof set to true, bytewise reads will
0130:         * return -1, and primitive reads will throw EOFExceptions.  Note that this
0131:         * behavior does not hold for streams written with the old
0132:         * <code>ObjectStreamConstants.PROTOCOL_VERSION_1</code> protocol, in which the
0133:         * end of data written by writeExternal methods is not demarcated, and hence
0134:         * cannot be detected.
0135:         *
0136:         * <p>The readObjectNoData method is responsible for initializing the state of
0137:         * the object for its particular class in the event that the serialization
0138:         * stream does not list the given class as a superclass of the object being
0139:         * deserialized.  This may occur in cases where the receiving party uses a
0140:         * different version of the deserialized instance's class than the sending
0141:         * party, and the receiver's version extends classes that are not extended by
0142:         * the sender's version.  This may also occur if the serialization stream has
0143:         * been tampered; hence, readObjectNoData is useful for initializing
0144:         * deserialized objects properly despite a "hostile" or incomplete source
0145:         * stream.
0146:         * 
0147:         * <p>Serialization does not read or assign values to the fields of any object
0148:         * that does not implement the java.io.Serializable interface.  Subclasses of
0149:         * Objects that are not serializable can be serializable. In this case the
0150:         * non-serializable class must have a no-arg constructor to allow its fields to
0151:         * be initialized.  In this case it is the responsibility of the subclass to
0152:         * save and restore the state of the non-serializable class. It is frequently
0153:         * the case that the fields of that class are accessible (public, package, or
0154:         * protected) or that there are get and set methods that can be used to restore
0155:         * the state.
0156:         *
0157:         * <p>Any exception that occurs while deserializing an object will be caught by
0158:         * the ObjectInputStream and abort the reading process.
0159:         *
0160:         * <p>Implementing the Externalizable interface allows the object to assume
0161:         * complete control over the contents and format of the object's serialized
0162:         * form.  The methods of the Externalizable interface, writeExternal and
0163:         * readExternal, are called to save and restore the objects state.  When
0164:         * implemented by a class they can write and read their own state using all of
0165:         * the methods of ObjectOutput and ObjectInput.  It is the responsibility of
0166:         * the objects to handle any versioning that occurs.
0167:         *
0168:         * <p>Enum constants are deserialized differently than ordinary serializable or
0169:         * externalizable objects.  The serialized form of an enum constant consists
0170:         * solely of its name; field values of the constant are not transmitted.  To
0171:         * deserialize an enum constant, ObjectInputStream reads the constant name from
0172:         * the stream; the deserialized constant is then obtained by calling the static
0173:         * method <code>Enum.valueOf(Class, String)</code> with the enum constant's
0174:         * base type and the received constant name as arguments.  Like other
0175:         * serializable or externalizable objects, enum constants can function as the
0176:         * targets of back references appearing subsequently in the serialization
0177:         * stream.  The process by which enum constants are deserialized cannot be
0178:         * customized: any class-specific readObject, readObjectNoData, and readResolve
0179:         * methods defined by enum types are ignored during deserialization.
0180:         * Similarly, any serialPersistentFields or serialVersionUID field declarations
0181:         * are also ignored--all enum types have a fixed serialVersionUID of 0L.
0182:         *
0183:         * @author	Mike Warres
0184:         * @author	Roger Riggs
0185:         * @version 1.155, 04/05/28
0186:         * @see java.io.DataInput
0187:         * @see java.io.ObjectOutputStream
0188:         * @see java.io.Serializable
0189:         * @see <a href="../../../guide/serialization/spec/input.doc.html"> Object Serialization Specification, Section 3, Object Input Classes</a>
0190:         * @since   JDK1.1
0191:         */
0192:        public class ObjectInputStream extends InputStream implements 
0193:                ObjectInput, ObjectStreamConstants {
0194:            /** handle value representing null */
0195:            private static final int NULL_HANDLE = -1;
0196:
0197:            /** marker for unshared objects in internal handle table */
0198:            private static final Object unsharedMarker = new Object();
0199:
0200:            /** table mapping primitive type names to corresponding class objects */
0201:            private static final HashMap primClasses = new HashMap(8, 1.0F);
0202:            static {
0203:                primClasses.put("boolean", boolean.class);
0204:                primClasses.put("byte", byte.class);
0205:                primClasses.put("char", char.class);
0206:                primClasses.put("short", short.class);
0207:                primClasses.put("int", int.class);
0208:                primClasses.put("long", long.class);
0209:                primClasses.put("float", float.class);
0210:                primClasses.put("double", double.class);
0211:                primClasses.put("void", void.class);
0212:            }
0213:
0214:            /** cache of subclass security audit results */
0215:            private static final SoftCache subclassAudits = new SoftCache(5);
0216:
0217:            /** filter stream for handling block data conversion */
0218:            private final BlockDataInputStream bin;
0219:            /** validation callback list */
0220:            private final ValidationList vlist;
0221:            /** recursion depth */
0222:            private int depth;
0223:            /** whether stream is closed */
0224:            private boolean closed;
0225:
0226:            /** wire handle -> obj/exception map */
0227:            private final HandleTable handles;
0228:            /** scratch field for passing handle values up/down call stack */
0229:            private int passHandle = NULL_HANDLE;
0230:            /** flag set when at end of field value block with no TC_ENDBLOCKDATA */
0231:            private boolean defaultDataEnd = false;
0232:
0233:            /** buffer for reading primitive field values */
0234:            private byte[] primVals;
0235:
0236:            /** if true, invoke readObjectOverride() instead of readObject() */
0237:            private final boolean enableOverride;
0238:            /** if true, invoke resolveObject() */
0239:            private boolean enableResolve;
0240:
0241:            // values below valid only during upcalls to readObject()/readExternal()
0242:            /** object currently being deserialized */
0243:            private Object curObj;
0244:            /** descriptor for current class (null if in readExternal()) */
0245:            private ObjectStreamClass curDesc;
0246:            /** current GetField object */
0247:            private GetFieldImpl curGet;
0248:
0249:            /**
0250:             * Creates an ObjectInputStream that reads from the specified InputStream.
0251:             * A serialization stream header is read from the stream and verified.
0252:             * This constructor will block until the corresponding ObjectOutputStream
0253:             * has written and flushed the header.
0254:             *
0255:             * <p>If a security manager is installed, this constructor will check for
0256:             * the "enableSubclassImplementation" SerializablePermission when invoked
0257:             * directly or indirectly by the constructor of a subclass which overrides
0258:             * the ObjectInputStream.readFields or ObjectInputStream.readUnshared
0259:             * methods.
0260:             *
0261:             * @param	in input stream to read from
0262:             * @throws	StreamCorruptedException if the stream header is incorrect
0263:             * @throws	IOException if an I/O error occurs while reading stream header
0264:             * @throws	SecurityException if untrusted subclass illegally overrides
0265:             * 		security-sensitive methods
0266:             * @throws	NullPointerException if <code>in</code> is <code>null</code>
0267:             * @see	ObjectInputStream#ObjectInputStream()
0268:             * @see	ObjectInputStream#readFields()
0269:             * @see	ObjectOutputStream#ObjectOutputStream(OutputStream)
0270:             */
0271:            public ObjectInputStream(InputStream in) throws IOException {
0272:                verifySubclass();
0273:                bin = new BlockDataInputStream(in);
0274:                handles = new HandleTable(10);
0275:                vlist = new ValidationList();
0276:                enableOverride = false;
0277:                readStreamHeader();
0278:                bin.setBlockDataMode(true);
0279:            }
0280:
0281:            /**
0282:             * Provide a way for subclasses that are completely reimplementing
0283:             * ObjectInputStream to not have to allocate private data just used by this
0284:             * implementation of ObjectInputStream.
0285:             *
0286:             * <p>If there is a security manager installed, this method first calls the
0287:             * security manager's <code>checkPermission</code> method with the
0288:             * <code>SerializablePermission("enableSubclassImplementation")</code>
0289:             * permission to ensure it's ok to enable subclassing.
0290:             *
0291:             * @throws	SecurityException if a security manager exists and its
0292:             * 		<code>checkPermission</code> method denies enabling
0293:             * 		subclassing.
0294:             * @see SecurityManager#checkPermission
0295:             * @see java.io.SerializablePermission
0296:             */
0297:            protected ObjectInputStream() throws IOException, SecurityException {
0298:                SecurityManager sm = System.getSecurityManager();
0299:                if (sm != null) {
0300:                    sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
0301:                }
0302:                bin = null;
0303:                handles = null;
0304:                vlist = null;
0305:                enableOverride = true;
0306:            }
0307:
0308:            /**
0309:             * Read an object from the ObjectInputStream.  The class of the object, the
0310:             * signature of the class, and the values of the non-transient and
0311:             * non-static fields of the class and all of its supertypes are read.
0312:             * Default deserializing for a class can be overriden using the writeObject
0313:             * and readObject methods.  Objects referenced by this object are read
0314:             * transitively so that a complete equivalent graph of objects is
0315:             * reconstructed by readObject.
0316:             *
0317:             * <p>The root object is completely restored when all of its fields and the
0318:             * objects it references are completely restored.  At this point the object
0319:             * validation callbacks are executed in order based on their registered
0320:             * priorities. The callbacks are registered by objects (in the readObject
0321:             * special methods) as they are individually restored.
0322:             *
0323:             * <p>Exceptions are thrown for problems with the InputStream and for
0324:             * classes that should not be deserialized.  All exceptions are fatal to
0325:             * the InputStream and leave it in an indeterminate state; it is up to the
0326:             * caller to ignore or recover the stream state.
0327:             *
0328:             * @throws	ClassNotFoundException Class of a serialized object cannot be
0329:             * 		found.
0330:             * @throws	InvalidClassException Something is wrong with a class used by
0331:             * 		serialization.
0332:             * @throws	StreamCorruptedException Control information in the
0333:             * 		stream is inconsistent.
0334:             * @throws	OptionalDataException Primitive data was found in the 
0335:             * 		stream instead of objects.
0336:             * @throws	IOException Any of the usual Input/Output related exceptions.
0337:             */
0338:            public final Object readObject() throws IOException,
0339:                    ClassNotFoundException {
0340:                if (enableOverride) {
0341:                    return readObjectOverride();
0342:                }
0343:
0344:                // if nested read, passHandle contains handle of enclosing object
0345:                int outerHandle = passHandle;
0346:                try {
0347:                    Object obj = readObject0(false);
0348:                    handles.markDependency(outerHandle, passHandle);
0349:                    ClassNotFoundException ex = handles
0350:                            .lookupException(passHandle);
0351:                    if (ex != null) {
0352:                        throw ex;
0353:                    }
0354:                    if (depth == 0) {
0355:                        vlist.doCallbacks();
0356:                    }
0357:                    return obj;
0358:                } finally {
0359:                    passHandle = outerHandle;
0360:                    if (closed && depth == 0) {
0361:                        clear();
0362:                    }
0363:                }
0364:            }
0365:
0366:            /**
0367:             * This method is called by trusted subclasses of ObjectOutputStream that
0368:             * constructed ObjectOutputStream using the protected no-arg constructor.
0369:             * The subclass is expected to provide an override method with the modifier
0370:             * "final".
0371:             *
0372:             * @return	the Object read from the stream.
0373:             * @throws	ClassNotFoundException Class definition of a serialized object
0374:             * 		cannot be found.
0375:             * @throws	OptionalDataException Primitive data was found in the stream
0376:             * 		instead of objects.
0377:             * @throws	IOException if I/O errors occurred while reading from the
0378:             * 		underlying stream
0379:             * @see #ObjectInputStream()
0380:             * @see #readObject()
0381:             * @since 1.2
0382:             */
0383:            protected Object readObjectOverride() throws IOException,
0384:                    ClassNotFoundException {
0385:                return null;
0386:            }
0387:
0388:            /**
0389:             * Reads an "unshared" object from the ObjectInputStream.  This method is
0390:             * identical to readObject, except that it prevents subsequent calls to
0391:             * readObject and readUnshared from returning additional references to the
0392:             * deserialized instance obtained via this call.  Specifically:
0393:             * <ul>
0394:             *   <li>If readUnshared is called to deserialize a back-reference (the
0395:             *       stream representation of an object which has been written
0396:             *       previously to the stream), an ObjectStreamException will be
0397:             *       thrown.
0398:             *
0399:             *   <li>If readUnshared returns successfully, then any subsequent attempts
0400:             *       to deserialize back-references to the stream handle deserialized
0401:             *       by readUnshared will cause an ObjectStreamException to be thrown.
0402:             * </ul>
0403:             * Deserializing an object via readUnshared invalidates the stream handle
0404:             * associated with the returned object.  Note that this in itself does not
0405:             * always guarantee that the reference returned by readUnshared is unique;
0406:             * the deserialized object may define a readResolve method which returns an
0407:             * object visible to other parties, or readUnshared may return a Class
0408:             * object or enum constant obtainable elsewhere in the stream or through
0409:             * external means.
0410:             *
0411:             * <p>However, for objects which are not enum constants or instances of
0412:             * java.lang.Class and do not define readResolve methods, readUnshared
0413:             * guarantees that the returned object reference is unique and cannot be
0414:             * obtained a second time from the ObjectInputStream that created it, even
0415:             * if the underlying data stream has been manipulated.  This guarantee
0416:             * applies only to the base-level object returned by readUnshared, and not
0417:             * to any transitively referenced sub-objects in the returned object graph.
0418:             *
0419:             * <p>ObjectInputStream subclasses which override this method can only be
0420:             * constructed in security contexts possessing the
0421:             * "enableSubclassImplementation" SerializablePermission; any attempt to
0422:             * instantiate such a subclass without this permission will cause a
0423:             * SecurityException to be thrown.
0424:             *
0425:             * @return  reference to deserialized object
0426:             * @throws  ClassNotFoundException if class of an object to deserialize
0427:             *          cannot be found
0428:             * @throws  StreamCorruptedException if control information in the stream
0429:             *          is inconsistent
0430:             * @throws  ObjectStreamException if object to deserialize has already
0431:             *          appeared in stream
0432:             * @throws  OptionalDataException if primitive data is next in stream
0433:             * @throws  IOException if an I/O error occurs during deserialization
0434:             */
0435:            public Object readUnshared() throws IOException,
0436:                    ClassNotFoundException {
0437:                // if nested read, passHandle contains handle of enclosing object
0438:                int outerHandle = passHandle;
0439:                try {
0440:                    Object obj = readObject0(true);
0441:                    handles.markDependency(outerHandle, passHandle);
0442:                    ClassNotFoundException ex = handles
0443:                            .lookupException(passHandle);
0444:                    if (ex != null) {
0445:                        throw ex;
0446:                    }
0447:                    if (depth == 0) {
0448:                        vlist.doCallbacks();
0449:                    }
0450:                    return obj;
0451:                } finally {
0452:                    passHandle = outerHandle;
0453:                    if (closed && depth == 0) {
0454:                        clear();
0455:                    }
0456:                }
0457:            }
0458:
0459:            /**
0460:             * Read the non-static and non-transient fields of the current class from
0461:             * this stream.  This may only be called from the readObject method of the
0462:             * class being deserialized. It will throw the NotActiveException if it is
0463:             * called otherwise.
0464:             *
0465:             * @throws	ClassNotFoundException if the class of a serialized object
0466:             * 		could not be found.
0467:             * @throws	IOException if an I/O error occurs.
0468:             * @throws	NotActiveException if the stream is not currently reading
0469:             * 		objects.
0470:             */
0471:            public void defaultReadObject() throws IOException,
0472:                    ClassNotFoundException {
0473:                if (curObj == null || curDesc == null) {
0474:                    throw new NotActiveException("not in call to readObject");
0475:                }
0476:                bin.setBlockDataMode(false);
0477:                defaultReadFields(curObj, curDesc);
0478:                bin.setBlockDataMode(true);
0479:                if (!curDesc.hasWriteObjectData()) {
0480:                    /*
0481:                     * Fix for 4360508: since stream does not contain terminating
0482:                     * TC_ENDBLOCKDATA tag, set flag so that reading code elsewhere
0483:                     * knows to simulate end-of-custom-data behavior.
0484:                     */
0485:                    defaultDataEnd = true;
0486:                }
0487:                ClassNotFoundException ex = handles.lookupException(passHandle);
0488:                if (ex != null) {
0489:                    throw ex;
0490:                }
0491:            }
0492:
0493:            /**
0494:             * Reads the persistent fields from the stream and makes them available by
0495:             * name.
0496:             * 
0497:             * @return	the <code>GetField</code> object representing the persistent
0498:             * 		fields of the object being deserialized
0499:             * @throws	ClassNotFoundException if the class of a serialized object
0500:             * 		could not be found.
0501:             * @throws	IOException if an I/O error occurs.
0502:             * @throws	NotActiveException if the stream is not currently reading
0503:             * 		objects.
0504:             * @since 1.2
0505:             */
0506:            public ObjectInputStream.GetField readFields() throws IOException,
0507:                    ClassNotFoundException {
0508:                if (curGet == null) {
0509:                    if (curObj == null || curDesc == null) {
0510:                        throw new NotActiveException(
0511:                                "not in call to readObject");
0512:                    }
0513:                    curGet = new GetFieldImpl(curDesc);
0514:                }
0515:                bin.setBlockDataMode(false);
0516:                curGet.readFields();
0517:                bin.setBlockDataMode(true);
0518:                if (!curDesc.hasWriteObjectData()) {
0519:                    /*
0520:                     * Fix for 4360508: since stream does not contain terminating
0521:                     * TC_ENDBLOCKDATA tag, set flag so that reading code elsewhere
0522:                     * knows to simulate end-of-custom-data behavior.
0523:                     */
0524:                    defaultDataEnd = true;
0525:                }
0526:
0527:                return curGet;
0528:            }
0529:
0530:            /**
0531:             * Register an object to be validated before the graph is returned.  While
0532:             * similar to resolveObject these validations are called after the entire
0533:             * graph has been reconstituted.  Typically, a readObject method will
0534:             * register the object with the stream so that when all of the objects are
0535:             * restored a final set of validations can be performed.
0536:             *
0537:             * @param	obj the object to receive the validation callback.
0538:             * @param	prio controls the order of callbacks;zero is a good default.
0539:             * 		Use higher numbers to be called back earlier, lower numbers for
0540:             * 		later callbacks. Within a priority, callbacks are processed in
0541:             * 		no particular order.
0542:             * @throws	NotActiveException The stream is not currently reading objects
0543:             * 		so it is invalid to register a callback.
0544:             * @throws	InvalidObjectException The validation object is null.
0545:             */
0546:            public void registerValidation(ObjectInputValidation obj, int prio)
0547:                    throws NotActiveException, InvalidObjectException {
0548:                if (depth == 0) {
0549:                    throw new NotActiveException("stream inactive");
0550:                }
0551:                vlist.register(obj, prio);
0552:            }
0553:
0554:            /**
0555:             * Load the local class equivalent of the specified stream class
0556:             * description.  Subclasses may implement this method to allow classes to
0557:             * be fetched from an alternate source. 
0558:             *
0559:             * <p>The corresponding method in <code>ObjectOutputStream</code> is
0560:             * <code>annotateClass</code>.  This method will be invoked only once for
0561:             * each unique class in the stream.  This method can be implemented by
0562:             * subclasses to use an alternate loading mechanism but must return a
0563:             * <code>Class</code> object.  Once returned, the serialVersionUID of the
0564:             * class is compared to the serialVersionUID of the serialized class.  If
0565:             * there is a mismatch, the deserialization fails and an exception is
0566:             * raised.
0567:             *
0568:             * <p>By default the class name is resolved relative to the class that
0569:             * called <code>readObject</code>.
0570:             *
0571:             * @param	desc an instance of class <code>ObjectStreamClass</code>
0572:             * @return	a <code>Class</code> object corresponding to <code>desc</code>
0573:             * @throws	IOException any of the usual input/output exceptions
0574:             * @throws	ClassNotFoundException if class of a serialized object cannot
0575:             * 		be found
0576:             */
0577:            protected Class<?> resolveClass(ObjectStreamClass desc)
0578:                    throws IOException, ClassNotFoundException {
0579:                String name = desc.getName();
0580:                try {
0581:                    return Class
0582:                            .forName(name, false, latestUserDefinedLoader());
0583:                } catch (ClassNotFoundException ex) {
0584:                    Class cl = (Class) primClasses.get(name);
0585:                    if (cl != null) {
0586:                        return cl;
0587:                    } else {
0588:                        throw ex;
0589:                    }
0590:                }
0591:            }
0592:
0593:            /**
0594:             * Returns a proxy class that implements the interfaces named in a proxy
0595:             * class descriptor; subclasses may implement this method to read custom
0596:             * data from the stream along with the descriptors for dynamic proxy
0597:             * classes, allowing them to use an alternate loading mechanism for the
0598:             * interfaces and the proxy class.
0599:             *
0600:             * <p>This method is called exactly once for each unique proxy class
0601:             * descriptor in the stream.
0602:             *
0603:             * <p>The corresponding method in <code>ObjectOutputStream</code> is
0604:             * <code>annotateProxyClass</code>.  For a given subclass of
0605:             * <code>ObjectInputStream</code> that overrides this method, the
0606:             * <code>annotateProxyClass</code> method in the corresponding subclass of
0607:             * <code>ObjectOutputStream</code> must write any data or objects read by
0608:             * this method.
0609:             *
0610:             * <p>The default implementation of this method in
0611:             * <code>ObjectInputStream</code> returns the result of calling
0612:             * <code>Proxy.getProxyClass</code> with the list of <code>Class</code>
0613:             * objects for the interfaces that are named in the <code>interfaces</code>
0614:             * parameter.  The <code>Class</code> object for each interface name
0615:             * <code>i</code> is the value returned by calling
0616:             * <pre>
0617:             *     Class.forName(i, false, loader)
0618:             * </pre>
0619:             * where <code>loader</code> is that of the first non-<code>null</code>
0620:             * class loader up the execution stack, or <code>null</code> if no
0621:             * non-<code>null</code> class loaders are on the stack (the same class
0622:             * loader choice used by the <code>resolveClass</code> method).  Unless any
0623:             * of the resolved interfaces are non-public, this same value of
0624:             * <code>loader</code> is also the class loader passed to
0625:             * <code>Proxy.getProxyClass</code>; if non-public interfaces are present,
0626:             * their class loader is passed instead (if more than one non-public
0627:             * interface class loader is encountered, an
0628:             * <code>IllegalAccessError</code> is thrown).  
0629:             * If <code>Proxy.getProxyClass</code> throws an
0630:             * <code>IllegalArgumentException</code>, <code>resolveProxyClass</code>
0631:             * will throw a <code>ClassNotFoundException</code> containing the
0632:             * <code>IllegalArgumentException</code>.
0633:             *
0634:             * @param	interfaces the list of interface names that were
0635:             *		deserialized in the proxy class descriptor
0636:             * @return  a proxy class for the specified interfaces
0637:             * @throws	IOException any exception thrown by the underlying
0638:             *		<code>InputStream</code>
0639:             * @throws	ClassNotFoundException if the proxy class or any of the
0640:             * 		named interfaces could not be found
0641:             * @see ObjectOutputStream#annotateProxyClass(Class)
0642:             * @since	1.3
0643:             */
0644:            protected Class<?> resolveProxyClass(String[] interfaces)
0645:                    throws IOException, ClassNotFoundException {
0646:                ClassLoader latestLoader = latestUserDefinedLoader();
0647:                ClassLoader nonPublicLoader = null;
0648:                boolean hasNonPublicInterface = false;
0649:
0650:                // define proxy in class loader of non-public interface(s), if any
0651:                Class[] classObjs = new Class[interfaces.length];
0652:                for (int i = 0; i < interfaces.length; i++) {
0653:                    Class cl = Class
0654:                            .forName(interfaces[i], false, latestLoader);
0655:                    if ((cl.getModifiers() & Modifier.PUBLIC) == 0) {
0656:                        if (hasNonPublicInterface) {
0657:                            if (nonPublicLoader != cl.getClassLoader()) {
0658:                                throw new IllegalAccessError(
0659:                                        "conflicting non-public interface class loaders");
0660:                            }
0661:                        } else {
0662:                            nonPublicLoader = cl.getClassLoader();
0663:                            hasNonPublicInterface = true;
0664:                        }
0665:                    }
0666:                    classObjs[i] = cl;
0667:                }
0668:                try {
0669:                    return Proxy.getProxyClass(
0670:                            hasNonPublicInterface ? nonPublicLoader
0671:                                    : latestLoader, classObjs);
0672:                } catch (IllegalArgumentException e) {
0673:                    throw new ClassNotFoundException(null, e);
0674:                }
0675:            }
0676:
0677:            /**
0678:             * This method will allow trusted subclasses of ObjectInputStream to
0679:             * substitute one object for another during deserialization. Replacing
0680:             * objects is disabled until enableResolveObject is called. The
0681:             * enableResolveObject method checks that the stream requesting to resolve
0682:             * object can be trusted. Every reference to serializable objects is passed
0683:             * to resolveObject.  To insure that the private state of objects is not
0684:             * unintentionally exposed only trusted streams may use resolveObject.
0685:             *
0686:             * <p>This method is called after an object has been read but before it is
0687:             * returned from readObject.  The default resolveObject method just returns
0688:             * the same object.
0689:             *
0690:             * <p>When a subclass is replacing objects it must insure that the
0691:             * substituted object is compatible with every field where the reference
0692:             * will be stored.  Objects whose type is not a subclass of the type of the
0693:             * field or array element abort the serialization by raising an exception
0694:             * and the object is not be stored.
0695:             *
0696:             * <p>This method is called only once when each object is first
0697:             * encountered.  All subsequent references to the object will be redirected
0698:             * to the new object.
0699:             *
0700:             * @param	obj object to be substituted
0701:             * @return	the substituted object
0702:             * @throws	IOException Any of the usual Input/Output exceptions.
0703:             */
0704:            protected Object resolveObject(Object obj) throws IOException {
0705:                return obj;
0706:            }
0707:
0708:            /**
0709:             * Enable the stream to allow objects read from the stream to be replaced.
0710:             * When enabled, the resolveObject method is called for every object being
0711:             * deserialized.
0712:             *
0713:             * <p>If <i>enable</i> is true, and there is a security manager installed,
0714:             * this method first calls the security manager's
0715:             * <code>checkPermission</code> method with the
0716:             * <code>SerializablePermission("enableSubstitution")</code> permission to
0717:             * ensure it's ok to enable the stream to allow objects read from the
0718:             * stream to be replaced.
0719:             * 
0720:             * @param	enable true for enabling use of <code>resolveObject</code> for
0721:             * 		every object being deserialized
0722:             * @return	the previous setting before this method was invoked
0723:             * @throws	SecurityException if a security manager exists and its
0724:             * 		<code>checkPermission</code> method denies enabling the stream
0725:             * 		to allow objects read from the stream to be replaced.
0726:             * @see SecurityManager#checkPermission
0727:             * @see java.io.SerializablePermission
0728:             */
0729:            protected boolean enableResolveObject(boolean enable)
0730:                    throws SecurityException {
0731:                if (enable == enableResolve) {
0732:                    return enable;
0733:                }
0734:                if (enable) {
0735:                    SecurityManager sm = System.getSecurityManager();
0736:                    if (sm != null) {
0737:                        sm.checkPermission(SUBSTITUTION_PERMISSION);
0738:                    }
0739:                }
0740:                enableResolve = enable;
0741:                return !enableResolve;
0742:            }
0743:
0744:            /**
0745:             * The readStreamHeader method is provided to allow subclasses to read and
0746:             * verify their own stream headers. It reads and verifies the magic number
0747:             * and version number.
0748:             *
0749:             * @throws	IOException if there are I/O errors while reading from the
0750:             * 		underlying <code>InputStream</code> 
0751:             * @throws	StreamCorruptedException if control information in the stream
0752:             * 		is inconsistent
0753:             */
0754:            protected void readStreamHeader() throws IOException,
0755:                    StreamCorruptedException {
0756:                if (bin.readShort() != STREAM_MAGIC
0757:                        || bin.readShort() != STREAM_VERSION) {
0758:                    throw new StreamCorruptedException("invalid stream header");
0759:                }
0760:            }
0761:
0762:            /**
0763:             * Read a class descriptor from the serialization stream.  This method is
0764:             * called when the ObjectInputStream expects a class descriptor as the next
0765:             * item in the serialization stream.  Subclasses of ObjectInputStream may
0766:             * override this method to read in class descriptors that have been written
0767:             * in non-standard formats (by subclasses of ObjectOutputStream which have
0768:             * overridden the <code>writeClassDescriptor</code> method).  By default,
0769:             * this method reads class descriptors according to the format defined in
0770:             * the Object Serialization specification.
0771:             *
0772:             * @return	the class descriptor read
0773:             * @throws	IOException If an I/O error has occurred.
0774:             * @throws	ClassNotFoundException If the Class of a serialized object used
0775:             * 		in the class descriptor representation cannot be found
0776:             * @see java.io.ObjectOutputStream#writeClassDescriptor(java.io.ObjectStreamClass)
0777:             * @since 1.3
0778:             */
0779:            protected ObjectStreamClass readClassDescriptor()
0780:                    throws IOException, ClassNotFoundException {
0781:                ObjectStreamClass desc = new ObjectStreamClass();
0782:                desc.readNonProxy(this );
0783:                return desc;
0784:            }
0785:
0786:            /**
0787:             * Reads a byte of data. This method will block if no input is available.
0788:             *
0789:             * @return	the byte read, or -1 if the end of the stream is reached.
0790:             * @throws	IOException If an I/O error has occurred.
0791:             */
0792:            public int read() throws IOException {
0793:                return bin.read();
0794:            }
0795:
0796:            /**
0797:             * Reads into an array of bytes.  This method will block until some input
0798:             * is available. Consider using java.io.DataInputStream.readFully to read
0799:             * exactly 'length' bytes.
0800:             *
0801:             * @param	buf the buffer into which the data is read
0802:             * @param	off the start offset of the data
0803:             * @param	len the maximum number of bytes read
0804:             * @return	the actual number of bytes read, -1 is returned when the end of
0805:             * 		the stream is reached.
0806:             * @throws	IOException If an I/O error has occurred.
0807:             * @see java.io.DataInputStream#readFully(byte[],int,int)
0808:             */
0809:            public int read(byte[] buf, int off, int len) throws IOException {
0810:                if (buf == null) {
0811:                    throw new NullPointerException();
0812:                }
0813:                int endoff = off + len;
0814:                if (off < 0 || len < 0 || endoff > buf.length || endoff < 0) {
0815:                    throw new IndexOutOfBoundsException();
0816:                }
0817:                return bin.read(buf, off, len, false);
0818:            }
0819:
0820:            /**
0821:             * Returns the number of bytes that can be read without blocking.
0822:             *
0823:             * @return	the number of available bytes.
0824:             * @throws	IOException if there are I/O errors while reading from the
0825:             * 		underlying <code>InputStream</code>
0826:             */
0827:            public int available() throws IOException {
0828:                return bin.available();
0829:            }
0830:
0831:            /**
0832:             * Closes the input stream. Must be called to release any resources
0833:             * associated with the stream.
0834:             *
0835:             * @throws	IOException If an I/O error has occurred.
0836:             */
0837:            public void close() throws IOException {
0838:                /*
0839:                 * Even if stream already closed, propagate redundant close to
0840:                 * underlying stream to stay consistent with previous implementations.
0841:                 */
0842:                closed = true;
0843:                if (depth == 0) {
0844:                    clear();
0845:                }
0846:                bin.close();
0847:            }
0848:
0849:            /**
0850:             * Reads in a boolean.
0851:             * 
0852:             * @return	the boolean read.
0853:             * @throws	EOFException If end of file is reached.
0854:             * @throws	IOException If other I/O error has occurred.
0855:             */
0856:            public boolean readBoolean() throws IOException {
0857:                return bin.readBoolean();
0858:            }
0859:
0860:            /**
0861:             * Reads an 8 bit byte.
0862:             * 
0863:             * @return	the 8 bit byte read.
0864:             * @throws	EOFException If end of file is reached.
0865:             * @throws	IOException If other I/O error has occurred.
0866:             */
0867:            public byte readByte() throws IOException {
0868:                return bin.readByte();
0869:            }
0870:
0871:            /**
0872:             * Reads an unsigned 8 bit byte.
0873:             *
0874:             * @return	the 8 bit byte read.
0875:             * @throws	EOFException If end of file is reached.
0876:             * @throws	IOException If other I/O error has occurred.
0877:             */
0878:            public int readUnsignedByte() throws IOException {
0879:                return bin.readUnsignedByte();
0880:            }
0881:
0882:            /**
0883:             * Reads a 16 bit char.
0884:             *
0885:             * @return	the 16 bit char read. 
0886:             * @throws	EOFException If end of file is reached.
0887:             * @throws	IOException If other I/O error has occurred.
0888:             */
0889:            public char readChar() throws IOException {
0890:                return bin.readChar();
0891:            }
0892:
0893:            /**
0894:             * Reads a 16 bit short.
0895:             *
0896:             * @return	the 16 bit short read.
0897:             * @throws	EOFException If end of file is reached.
0898:             * @throws	IOException If other I/O error has occurred.
0899:             */
0900:            public short readShort() throws IOException {
0901:                return bin.readShort();
0902:            }
0903:
0904:            /**
0905:             * Reads an unsigned 16 bit short.
0906:             *
0907:             * @return	the 16 bit short read.
0908:             * @throws	EOFException If end of file is reached.
0909:             * @throws	IOException If other I/O error has occurred.
0910:             */
0911:            public int readUnsignedShort() throws IOException {
0912:                return bin.readUnsignedShort();
0913:            }
0914:
0915:            /**
0916:             * Reads a 32 bit int.
0917:             *
0918:             * @return	the 32 bit integer read.
0919:             * @throws	EOFException If end of file is reached.
0920:             * @throws	IOException If other I/O error has occurred.
0921:             */
0922:            public int readInt() throws IOException {
0923:                return bin.readInt();
0924:            }
0925:
0926:            /**
0927:             * Reads a 64 bit long.
0928:             *
0929:             * @return	the read 64 bit long.
0930:             * @throws	EOFException If end of file is reached.
0931:             * @throws	IOException If other I/O error has occurred.
0932:             */
0933:            public long readLong() throws IOException {
0934:                return bin.readLong();
0935:            }
0936:
0937:            /**
0938:             * Reads a 32 bit float.
0939:             *
0940:             * @return	the 32 bit float read.
0941:             * @throws	EOFException If end of file is reached.
0942:             * @throws	IOException If other I/O error has occurred.
0943:             */
0944:            public float readFloat() throws IOException {
0945:                return bin.readFloat();
0946:            }
0947:
0948:            /**
0949:             * Reads a 64 bit double.
0950:             *
0951:             * @return	the 64 bit double read.
0952:             * @throws	EOFException If end of file is reached.
0953:             * @throws	IOException If other I/O error has occurred.
0954:             */
0955:            public double readDouble() throws IOException {
0956:                return bin.readDouble();
0957:            }
0958:
0959:            /**
0960:             * Reads bytes, blocking until all bytes are read.
0961:             *
0962:             * @param	buf the buffer into which the data is read
0963:             * @throws	EOFException If end of file is reached.
0964:             * @throws	IOException If other I/O error has occurred.
0965:             */
0966:            public void readFully(byte[] buf) throws IOException {
0967:                bin.readFully(buf, 0, buf.length, false);
0968:            }
0969:
0970:            /**
0971:             * Reads bytes, blocking until all bytes are read.
0972:             *
0973:             * @param	buf the buffer into which the data is read
0974:             * @param	off the start offset of the data
0975:             * @param	len the maximum number of bytes to read
0976:             * @throws	EOFException If end of file is reached.
0977:             * @throws	IOException If other I/O error has occurred.
0978:             */
0979:            public void readFully(byte[] buf, int off, int len)
0980:                    throws IOException {
0981:                int endoff = off + len;
0982:                if (off < 0 || len < 0 || endoff > buf.length || endoff < 0) {
0983:                    throw new IndexOutOfBoundsException();
0984:                }
0985:                bin.readFully(buf, off, len, false);
0986:            }
0987:
0988:            /**
0989:             * Skips bytes, block until all bytes are skipped.
0990:             *
0991:             * @param	len the number of bytes to be skipped
0992:             * @return	the actual number of bytes skipped.
0993:             * @throws	EOFException If end of file is reached.
0994:             * @throws	IOException If other I/O error has occurred.
0995:             */
0996:            public int skipBytes(int len) throws IOException {
0997:                return bin.skipBytes(len);
0998:            }
0999:
1000:            /**
1001:             * Reads in a line that has been terminated by a \n, \r, \r\n or EOF.
1002:             *
1003:             * @return	a String copy of the line.
1004:             * @throws	IOException if there are I/O errors while reading from the
1005:             * 		underlying <code>InputStream</code>
1006:             * @deprecated This method does not properly convert bytes to characters.
1007:             * 		see DataInputStream for the details and alternatives.
1008:             */
1009:            @Deprecated
1010:            public String readLine() throws IOException {
1011:                return bin.readLine();
1012:            }
1013:
1014:            /**
1015:             * Reads a String in
1016:             * <a href="DataInput.html#modified-utf-8">modified UTF-8</a>
1017:             * format.
1018:             *
1019:             * @return	the String.
1020:             * @throws	IOException if there are I/O errors while reading from the
1021:             * 		underlying <code>InputStream</code>
1022:             * @throws	UTFDataFormatException if read bytes do not represent a valid
1023:             * 		modified UTF-8 encoding of a string
1024:             */
1025:            public String readUTF() throws IOException {
1026:                return bin.readUTF();
1027:            }
1028:
1029:            /**
1030:             * Provide access to the persistent fields read from the input stream.
1031:             */
1032:            public static abstract class GetField {
1033:
1034:                /**
1035:                 * Get the ObjectStreamClass that describes the fields in the stream.
1036:                 *
1037:                 * @return  the descriptor class that describes the serializable fields
1038:                 */
1039:                public abstract ObjectStreamClass getObjectStreamClass();
1040:
1041:                /**
1042:                 * Return true if the named field is defaulted and has no value in this
1043:                 * stream.
1044:                 *
1045:                 * @param  name the name of the field
1046:                 * @return true, if and only if the named field is defaulted
1047:                 * @throws IOException if there are I/O errors while reading from
1048:                 * 	   the underlying <code>InputStream</code>
1049:                 * @throws IllegalArgumentException if <code>name</code> does not
1050:                 * 	   correspond to a serializable field
1051:                 */
1052:                public abstract boolean defaulted(String name)
1053:                        throws IOException;
1054:
1055:                /**
1056:                 * Get the value of the named boolean field from the persistent field.
1057:                 *
1058:                 * @param  name the name of the field
1059:                 * @param  val the default value to use if <code>name</code> does not
1060:                 * 	   have a value
1061:                 * @return the value of the named <code>boolean</code> field
1062:                 * @throws IOException if there are I/O errors while reading from the
1063:                 * 	   underlying <code>InputStream</code>
1064:                 * @throws IllegalArgumentException if type of <code>name</code> is
1065:                 * 	   not serializable or if the field type is incorrect
1066:                 */
1067:                public abstract boolean get(String name, boolean val)
1068:                        throws IOException;
1069:
1070:                /**
1071:                 * Get the value of the named byte field from the persistent field.
1072:                 *
1073:                 * @param  name the name of the field
1074:                 * @param  val the default value to use if <code>name</code> does not
1075:                 * 	   have a value
1076:                 * @return the value of the named <code>byte</code> field
1077:                 * @throws IOException if there are I/O errors while reading from the
1078:                 * 	   underlying <code>InputStream</code>
1079:                 * @throws IllegalArgumentException if type of <code>name</code> is
1080:                 * 	   not serializable or if the field type is incorrect
1081:                 */
1082:                public abstract byte get(String name, byte val)
1083:                        throws IOException;
1084:
1085:                /**
1086:                 * Get the value of the named char field from the persistent field.
1087:                 *
1088:                 * @param  name the name of the field
1089:                 * @param  val the default value to use if <code>name</code> does not
1090:                 * 	   have a value
1091:                 * @return the value of the named <code>char</code> field
1092:                 * @throws IOException if there are I/O errors while reading from the
1093:                 * 	   underlying <code>InputStream</code>
1094:                 * @throws IllegalArgumentException if type of <code>name</code> is
1095:                 * 	   not serializable or if the field type is incorrect
1096:                 */
1097:                public abstract char get(String name, char val)
1098:                        throws IOException;
1099:
1100:                /**
1101:                 * Get the value of the named short field from the persistent field.
1102:                 *
1103:                 * @param  name the name of the field
1104:                 * @param  val the default value to use if <code>name</code> does not
1105:                 * 	   have a value
1106:                 * @return the value of the named <code>short</code> field
1107:                 * @throws IOException if there are I/O errors while reading from the
1108:                 * 	   underlying <code>InputStream</code>
1109:                 * @throws IllegalArgumentException if type of <code>name</code> is
1110:                 * 	   not serializable or if the field type is incorrect
1111:                 */
1112:                public abstract short get(String name, short val)
1113:                        throws IOException;
1114:
1115:                /**
1116:                 * Get the value of the named int field from the persistent field.
1117:                 *
1118:                 * @param  name the name of the field
1119:                 * @param  val the default value to use if <code>name</code> does not
1120:                 * 	   have a value
1121:                 * @return the value of the named <code>int</code> field
1122:                 * @throws IOException if there are I/O errors while reading from the
1123:                 * 	   underlying <code>InputStream</code>
1124:                 * @throws IllegalArgumentException if type of <code>name</code> is
1125:                 * 	   not serializable or if the field type is incorrect
1126:                 */
1127:                public abstract int get(String name, int val)
1128:                        throws IOException;
1129:
1130:                /**
1131:                 * Get the value of the named long field from the persistent field.
1132:                 *
1133:                 * @param  name the name of the field
1134:                 * @param  val the default value to use if <code>name</code> does not
1135:                 * 	   have a value
1136:                 * @return the value of the named <code>long</code> field
1137:                 * @throws IOException if there are I/O errors while reading from the
1138:                 * 	   underlying <code>InputStream</code>
1139:                 * @throws IllegalArgumentException if type of <code>name</code> is
1140:                 * 	   not serializable or if the field type is incorrect
1141:                 */
1142:                public abstract long get(String name, long val)
1143:                        throws IOException;
1144:
1145:                /**
1146:                 * Get the value of the named float field from the persistent field.
1147:                 *
1148:                 * @param  name the name of the field
1149:                 * @param  val the default value to use if <code>name</code> does not
1150:                 * 	   have a value
1151:                 * @return the value of the named <code>float</code> field
1152:                 * @throws IOException if there are I/O errors while reading from the
1153:                 * 	   underlying <code>InputStream</code>
1154:                 * @throws IllegalArgumentException if type of <code>name</code> is
1155:                 * 	   not serializable or if the field type is incorrect
1156:                 */
1157:                public abstract float get(String name, float val)
1158:                        throws IOException;
1159:
1160:                /**
1161:                 * Get the value of the named double field from the persistent field.
1162:                 *
1163:                 * @param  name the name of the field
1164:                 * @param  val the default value to use if <code>name</code> does not
1165:                 * 	   have a value
1166:                 * @return the value of the named <code>double</code> field
1167:                 * @throws IOException if there are I/O errors while reading from the
1168:                 * 	   underlying <code>InputStream</code>
1169:                 * @throws IllegalArgumentException if type of <code>name</code> is
1170:                 * 	   not serializable or if the field type is incorrect
1171:                 */
1172:                public abstract double get(String name, double val)
1173:                        throws IOException;
1174:
1175:                /**
1176:                 * Get the value of the named Object field from the persistent field.
1177:                 *
1178:                 * @param  name the name of the field
1179:                 * @param  val the default value to use if <code>name</code> does not
1180:                 * 	   have a value
1181:                 * @return the value of the named <code>Object</code> field
1182:                 * @throws IOException if there are I/O errors while reading from the
1183:                 * 	   underlying <code>InputStream</code>
1184:                 * @throws IllegalArgumentException if type of <code>name</code> is
1185:                 * 	   not serializable or if the field type is incorrect
1186:                 */
1187:                public abstract Object get(String name, Object val)
1188:                        throws IOException;
1189:            }
1190:
1191:            /**
1192:             * Verifies that this (possibly subclass) instance can be constructed
1193:             * without violating security constraints: the subclass must not override
1194:             * security-sensitive non-final methods, or else the
1195:             * "enableSubclassImplementation" SerializablePermission is checked.
1196:             */
1197:            private void verifySubclass() {
1198:                Class cl = getClass();
1199:                synchronized (subclassAudits) {
1200:                    Boolean result = (Boolean) subclassAudits.get(cl);
1201:                    if (result == null) {
1202:                        /*
1203:                         * Note: only new Boolean instances (i.e., not Boolean.TRUE or
1204:                         * Boolean.FALSE) must be used as cache values, otherwise cache
1205:                         * entry will pin associated class.
1206:                         */
1207:                        result = new Boolean(auditSubclass(cl));
1208:                        subclassAudits.put(cl, result);
1209:                    }
1210:                    if (result.booleanValue()) {
1211:                        return;
1212:                    }
1213:                }
1214:                SecurityManager sm = System.getSecurityManager();
1215:                if (sm != null) {
1216:                    sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
1217:                }
1218:            }
1219:
1220:            /**
1221:             * Performs reflective checks on given subclass to verify that it doesn't
1222:             * override security-sensitive non-final methods.  Returns true if subclass
1223:             * is "safe", false otherwise.
1224:             */
1225:            private static boolean auditSubclass(final Class subcl) {
1226:                Boolean result = (Boolean) AccessController
1227:                        .doPrivileged(new PrivilegedAction() {
1228:                            public Object run() {
1229:                                for (Class cl = subcl; cl != ObjectInputStream.class; cl = cl
1230:                                        .getSuperclass()) {
1231:                                    try {
1232:                                        cl.getDeclaredMethod("readUnshared",
1233:                                                new Class[0]);
1234:                                        return Boolean.FALSE;
1235:                                    } catch (NoSuchMethodException ex) {
1236:                                    }
1237:                                    try {
1238:                                        cl.getDeclaredMethod("readFields",
1239:                                                new Class[0]);
1240:                                        return Boolean.FALSE;
1241:                                    } catch (NoSuchMethodException ex) {
1242:                                    }
1243:                                }
1244:                                return Boolean.TRUE;
1245:                            }
1246:                        });
1247:                return result.booleanValue();
1248:            }
1249:
1250:            /**
1251:             * Clears internal data structures.
1252:             */
1253:            private void clear() {
1254:                handles.clear();
1255:                vlist.clear();
1256:            }
1257:
1258:            /**
1259:             * Underlying readObject implementation.
1260:             */
1261:            private Object readObject0(boolean unshared) throws IOException {
1262:                boolean oldMode = bin.getBlockDataMode();
1263:                if (oldMode) {
1264:                    int remain = bin.currentBlockRemaining();
1265:                    if (remain > 0) {
1266:                        throw new OptionalDataException(remain);
1267:                    } else if (defaultDataEnd) {
1268:                        /*
1269:                         * Fix for 4360508: stream is currently at the end of a field
1270:                         * value block written via default serialization; since there
1271:                         * is no terminating TC_ENDBLOCKDATA tag, simulate
1272:                         * end-of-custom-data behavior explicitly.
1273:                         */
1274:                        throw new OptionalDataException(true);
1275:                    }
1276:                    bin.setBlockDataMode(false);
1277:                }
1278:
1279:                byte tc;
1280:                while ((tc = bin.peekByte()) == TC_RESET) {
1281:                    bin.readByte();
1282:                    handleReset();
1283:                }
1284:
1285:                depth++;
1286:                try {
1287:                    switch (tc) {
1288:                    case TC_NULL:
1289:                        return readNull();
1290:
1291:                    case TC_REFERENCE:
1292:                        return readHandle(unshared);
1293:
1294:                    case TC_CLASS:
1295:                        return readClass(unshared);
1296:
1297:                    case TC_CLASSDESC:
1298:                    case TC_PROXYCLASSDESC:
1299:                        return readClassDesc(unshared);
1300:
1301:                    case TC_STRING:
1302:                    case TC_LONGSTRING:
1303:                        return checkResolve(readString(unshared));
1304:
1305:                    case TC_ARRAY:
1306:                        return checkResolve(readArray(unshared));
1307:
1308:                    case TC_ENUM:
1309:                        return checkResolve(readEnum(unshared));
1310:
1311:                    case TC_OBJECT:
1312:                        return checkResolve(readOrdinaryObject(unshared));
1313:
1314:                    case TC_EXCEPTION:
1315:                        IOException ex = readFatalException();
1316:                        throw new WriteAbortedException("writing aborted", ex);
1317:
1318:                    case TC_BLOCKDATA:
1319:                    case TC_BLOCKDATALONG:
1320:                        if (oldMode) {
1321:                            bin.setBlockDataMode(true);
1322:                            bin.peek(); // force header read
1323:                            throw new OptionalDataException(bin
1324:                                    .currentBlockRemaining());
1325:                        } else {
1326:                            throw new StreamCorruptedException(
1327:                                    "unexpected block data");
1328:                        }
1329:
1330:                    case TC_ENDBLOCKDATA:
1331:                        if (oldMode) {
1332:                            throw new OptionalDataException(true);
1333:                        } else {
1334:                            throw new StreamCorruptedException(
1335:                                    "unexpected end of block data");
1336:                        }
1337:
1338:                    default:
1339:                        throw new StreamCorruptedException();
1340:                    }
1341:                } finally {
1342:                    depth--;
1343:                    bin.setBlockDataMode(oldMode);
1344:                }
1345:            }
1346:
1347:            /**
1348:             * If resolveObject has been enabled and given object does not have an
1349:             * exception associated with it, calls resolveObject to determine
1350:             * replacement for object, and updates handle table accordingly.  Returns
1351:             * replacement object, or echoes provided object if no replacement
1352:             * occurred.  Expects that passHandle is set to given object's handle prior
1353:             * to calling this method.
1354:             */
1355:            private Object checkResolve(Object obj) throws IOException {
1356:                if (!enableResolve
1357:                        || handles.lookupException(passHandle) != null) {
1358:                    return obj;
1359:                }
1360:                Object rep = resolveObject(obj);
1361:                if (rep != obj) {
1362:                    handles.setObject(passHandle, rep);
1363:                }
1364:                return rep;
1365:            }
1366:
1367:            /**
1368:             * Reads string without allowing it to be replaced in stream.  Called from
1369:             * within ObjectStreamClass.read().
1370:             */
1371:            String readTypeString() throws IOException {
1372:                int oldHandle = passHandle;
1373:                try {
1374:                    switch (bin.peekByte()) {
1375:                    case TC_NULL:
1376:                        return (String) readNull();
1377:
1378:                    case TC_REFERENCE:
1379:                        return (String) readHandle(false);
1380:
1381:                    case TC_STRING:
1382:                    case TC_LONGSTRING:
1383:                        return readString(false);
1384:
1385:                    default:
1386:                        throw new StreamCorruptedException();
1387:                    }
1388:                } finally {
1389:                    passHandle = oldHandle;
1390:                }
1391:            }
1392:
1393:            /**
1394:             * Reads in null code, sets passHandle to NULL_HANDLE and returns null.
1395:             */
1396:            private Object readNull() throws IOException {
1397:                if (bin.readByte() != TC_NULL) {
1398:                    throw new StreamCorruptedException();
1399:                }
1400:                passHandle = NULL_HANDLE;
1401:                return null;
1402:            }
1403:
1404:            /**
1405:             * Reads in object handle, sets passHandle to the read handle, and returns
1406:             * object associated with the handle.
1407:             */
1408:            private Object readHandle(boolean unshared) throws IOException {
1409:                if (bin.readByte() != TC_REFERENCE) {
1410:                    throw new StreamCorruptedException();
1411:                }
1412:                passHandle = bin.readInt() - baseWireHandle;
1413:                if (passHandle < 0 || passHandle >= handles.size()) {
1414:                    throw new StreamCorruptedException("illegal handle value");
1415:                }
1416:                if (unshared) {
1417:                    // REMIND: what type of exception to throw here?
1418:                    throw new InvalidObjectException(
1419:                            "cannot read back reference as unshared");
1420:                }
1421:
1422:                Object obj = handles.lookupObject(passHandle);
1423:                if (obj == unsharedMarker) {
1424:                    // REMIND: what type of exception to throw here?
1425:                    throw new InvalidObjectException(
1426:                            "cannot read back reference to unshared object");
1427:                }
1428:                return obj;
1429:            }
1430:
1431:            /**
1432:             * Reads in and returns class object.  Sets passHandle to class object's
1433:             * assigned handle.  Returns null if class is unresolvable (in which case a
1434:             * ClassNotFoundException will be associated with the class' handle in the
1435:             * handle table).
1436:             */
1437:            private Class readClass(boolean unshared) throws IOException {
1438:                if (bin.readByte() != TC_CLASS) {
1439:                    throw new StreamCorruptedException();
1440:                }
1441:                ObjectStreamClass desc = readClassDesc(false);
1442:                Class cl = desc.forClass();
1443:                passHandle = handles.assign(unshared ? unsharedMarker : cl);
1444:
1445:                ClassNotFoundException resolveEx = desc.getResolveException();
1446:                if (resolveEx != null) {
1447:                    handles.markException(passHandle, resolveEx);
1448:                }
1449:
1450:                handles.finish(passHandle);
1451:                return cl;
1452:            }
1453:
1454:            /**
1455:             * Reads in and returns (possibly null) class descriptor.  Sets passHandle
1456:             * to class descriptor's assigned handle.  If class descriptor cannot be
1457:             * resolved to a class in the local VM, a ClassNotFoundException is
1458:             * associated with the class descriptor's handle.
1459:             */
1460:            private ObjectStreamClass readClassDesc(boolean unshared)
1461:                    throws IOException {
1462:                switch (bin.peekByte()) {
1463:                case TC_NULL:
1464:                    return (ObjectStreamClass) readNull();
1465:
1466:                case TC_REFERENCE:
1467:                    return (ObjectStreamClass) readHandle(unshared);
1468:
1469:                case TC_PROXYCLASSDESC:
1470:                    return readProxyDesc(unshared);
1471:
1472:                case TC_CLASSDESC:
1473:                    return readNonProxyDesc(unshared);
1474:
1475:                default:
1476:                    throw new StreamCorruptedException();
1477:                }
1478:            }
1479:
1480:            /**
1481:             * Reads in and returns class descriptor for a dynamic proxy class.  Sets
1482:             * passHandle to proxy class descriptor's assigned handle.  If proxy class
1483:             * descriptor cannot be resolved to a class in the local VM, a
1484:             * ClassNotFoundException is associated with the descriptor's handle.
1485:             */
1486:            private ObjectStreamClass readProxyDesc(boolean unshared)
1487:                    throws IOException {
1488:                if (bin.readByte() != TC_PROXYCLASSDESC) {
1489:                    throw new StreamCorruptedException();
1490:                }
1491:
1492:                ObjectStreamClass desc = new ObjectStreamClass();
1493:                int descHandle = handles.assign(unshared ? unsharedMarker
1494:                        : desc);
1495:                passHandle = NULL_HANDLE;
1496:
1497:                int numIfaces = bin.readInt();
1498:                String[] ifaces = new String[numIfaces];
1499:                for (int i = 0; i < numIfaces; i++) {
1500:                    ifaces[i] = bin.readUTF();
1501:                }
1502:
1503:                Class cl = null;
1504:                ClassNotFoundException resolveEx = null;
1505:                bin.setBlockDataMode(true);
1506:                try {
1507:                    if ((cl = resolveProxyClass(ifaces)) == null) {
1508:                        throw new ClassNotFoundException("null class");
1509:                    }
1510:                } catch (ClassNotFoundException ex) {
1511:                    resolveEx = ex;
1512:                }
1513:                skipCustomData();
1514:
1515:                desc.initProxy(cl, resolveEx, readClassDesc(false));
1516:
1517:                handles.finish(descHandle);
1518:                passHandle = descHandle;
1519:                return desc;
1520:            }
1521:
1522:            /**
1523:             * Reads in and returns class descriptor for a class that is not a dynamic
1524:             * proxy class.  Sets passHandle to class descriptor's assigned handle.  If
1525:             * class descriptor cannot be resolved to a class in the local VM, a
1526:             * ClassNotFoundException is associated with the descriptor's handle.
1527:             */
1528:            private ObjectStreamClass readNonProxyDesc(boolean unshared)
1529:                    throws IOException {
1530:                if (bin.readByte() != TC_CLASSDESC) {
1531:                    throw new StreamCorruptedException();
1532:                }
1533:
1534:                ObjectStreamClass desc = new ObjectStreamClass();
1535:                int descHandle = handles.assign(unshared ? unsharedMarker
1536:                        : desc);
1537:                passHandle = NULL_HANDLE;
1538:
1539:                ObjectStreamClass readDesc = null;
1540:                try {
1541:                    readDesc = readClassDescriptor();
1542:                } catch (ClassNotFoundException ex) {
1543:                    throw (IOException) new InvalidClassException(
1544:                            "failed to read class descriptor").initCause(ex);
1545:                }
1546:
1547:                Class cl = null;
1548:                ClassNotFoundException resolveEx = null;
1549:                bin.setBlockDataMode(true);
1550:                try {
1551:                    if ((cl = resolveClass(readDesc)) == null) {
1552:                        throw new ClassNotFoundException("null class");
1553:                    }
1554:                } catch (ClassNotFoundException ex) {
1555:                    resolveEx = ex;
1556:                }
1557:                skipCustomData();
1558:
1559:                desc
1560:                        .initNonProxy(readDesc, cl, resolveEx,
1561:                                readClassDesc(false));
1562:
1563:                handles.finish(descHandle);
1564:                passHandle = descHandle;
1565:                return desc;
1566:            }
1567:
1568:            /**
1569:             * Reads in and returns new string.  Sets passHandle to new string's
1570:             * assigned handle.
1571:             */
1572:            private String readString(boolean unshared) throws IOException {
1573:                String str;
1574:                switch (bin.readByte()) {
1575:                case TC_STRING:
1576:                    str = bin.readUTF();
1577:                    break;
1578:
1579:                case TC_LONGSTRING:
1580:                    str = bin.readLongUTF();
1581:                    break;
1582:
1583:                default:
1584:                    throw new StreamCorruptedException();
1585:                }
1586:                passHandle = handles.assign(unshared ? unsharedMarker : str);
1587:                handles.finish(passHandle);
1588:                return str;
1589:            }
1590:
1591:            /**
1592:             * Reads in and returns array object, or null if array class is
1593:             * unresolvable.  Sets passHandle to array's assigned handle.
1594:             */
1595:            private Object readArray(boolean unshared) throws IOException {
1596:                if (bin.readByte() != TC_ARRAY) {
1597:                    throw new StreamCorruptedException();
1598:                }
1599:
1600:                ObjectStreamClass desc = readClassDesc(false);
1601:                int len = bin.readInt();
1602:
1603:                Object array = null;
1604:                Class cl, ccl = null;
1605:                if ((cl = desc.forClass()) != null) {
1606:                    ccl = cl.getComponentType();
1607:                    array = Array.newInstance(ccl, len);
1608:                }
1609:
1610:                int arrayHandle = handles.assign(unshared ? unsharedMarker
1611:                        : array);
1612:                ClassNotFoundException resolveEx = desc.getResolveException();
1613:                if (resolveEx != null) {
1614:                    handles.markException(arrayHandle, resolveEx);
1615:                }
1616:
1617:                if (ccl == null) {
1618:                    for (int i = 0; i < len; i++) {
1619:                        readObject0(false);
1620:                    }
1621:                } else if (ccl.isPrimitive()) {
1622:                    if (ccl == Integer.TYPE) {
1623:                        bin.readInts((int[]) array, 0, len);
1624:                    } else if (ccl == Byte.TYPE) {
1625:                        bin.readFully((byte[]) array, 0, len, true);
1626:                    } else if (ccl == Long.TYPE) {
1627:                        bin.readLongs((long[]) array, 0, len);
1628:                    } else if (ccl == Float.TYPE) {
1629:                        bin.readFloats((float[]) array, 0, len);
1630:                    } else if (ccl == Double.TYPE) {
1631:                        bin.readDoubles((double[]) array, 0, len);
1632:                    } else if (ccl == Short.TYPE) {
1633:                        bin.readShorts((short[]) array, 0, len);
1634:                    } else if (ccl == Character.TYPE) {
1635:                        bin.readChars((char[]) array, 0, len);
1636:                    } else if (ccl == Boolean.TYPE) {
1637:                        bin.readBooleans((boolean[]) array, 0, len);
1638:                    } else {
1639:                        throw new InternalError();
1640:                    }
1641:                } else {
1642:                    Object[] oa = (Object[]) array;
1643:                    for (int i = 0; i < len; i++) {
1644:                        oa[i] = readObject0(false);
1645:                        handles.markDependency(arrayHandle, passHandle);
1646:                    }
1647:                }
1648:
1649:                handles.finish(arrayHandle);
1650:                passHandle = arrayHandle;
1651:                return array;
1652:            }
1653:
1654:            /**
1655:             * Reads in and returns enum constant, or null if enum type is
1656:             * unresolvable.  Sets passHandle to enum constant's assigned handle.
1657:             */
1658:            private Enum readEnum(boolean unshared) throws IOException {
1659:                if (bin.readByte() != TC_ENUM) {
1660:                    throw new StreamCorruptedException();
1661:                }
1662:
1663:                ObjectStreamClass desc = readClassDesc(false);
1664:                if (!desc.isEnum()) {
1665:                    throw new InvalidClassException("non-enum class: " + desc);
1666:                }
1667:
1668:                int enumHandle = handles.assign(unshared ? unsharedMarker
1669:                        : null);
1670:                ClassNotFoundException resolveEx = desc.getResolveException();
1671:                if (resolveEx != null) {
1672:                    handles.markException(enumHandle, resolveEx);
1673:                }
1674:
1675:                String name = readString(false);
1676:                Enum en = null;
1677:                Class cl = desc.forClass();
1678:                if (cl != null) {
1679:                    try {
1680:                        en = Enum.valueOf(cl, name);
1681:                    } catch (IllegalArgumentException ex) {
1682:                        throw (IOException) new InvalidObjectException(
1683:                                "enum constant " + name + " does not exist in "
1684:                                        + cl).initCause(ex);
1685:                    }
1686:                    if (!unshared) {
1687:                        handles.setObject(enumHandle, en);
1688:                    }
1689:                }
1690:
1691:                handles.finish(enumHandle);
1692:                passHandle = enumHandle;
1693:                return en;
1694:            }
1695:
1696:            /**
1697:             * Reads and returns "ordinary" (i.e., not a String, Class,
1698:             * ObjectStreamClass, array, or enum constant) object, or null if object's
1699:             * class is unresolvable (in which case a ClassNotFoundException will be
1700:             * associated with object's handle).  Sets passHandle to object's assigned
1701:             * handle.
1702:             */
1703:            private Object readOrdinaryObject(boolean unshared)
1704:                    throws IOException {
1705:                if (bin.readByte() != TC_OBJECT) {
1706:                    throw new StreamCorruptedException();
1707:                }
1708:
1709:                ObjectStreamClass desc = readClassDesc(false);
1710:                desc.checkDeserialize();
1711:
1712:                Object obj;
1713:                try {
1714:                    // obj = desc.isInstantiable() ? desc.newInstance() : null;
1715:                    // COUGAAR mod
1716:                    obj = desc.isInstantiable() ? newInstanceFromDesc(desc)
1717:                            : null;
1718:                } catch (Exception ex) {
1719:                    throw new InvalidClassException(desc.forClass().getName(),
1720:                            "unable to create instance");
1721:                }
1722:
1723:                passHandle = handles.assign(unshared ? unsharedMarker : obj);
1724:                ClassNotFoundException resolveEx = desc.getResolveException();
1725:                if (resolveEx != null) {
1726:                    handles.markException(passHandle, resolveEx);
1727:                }
1728:
1729:                if (desc.isExternalizable()) {
1730:                    readExternalData((Externalizable) obj, desc);
1731:                } else {
1732:                    readSerialData(obj, desc);
1733:                }
1734:
1735:                handles.finish(passHandle);
1736:
1737:                if (obj != null && handles.lookupException(passHandle) == null
1738:                        && desc.hasReadResolveMethod()) {
1739:                    Object rep = desc.invokeReadResolve(obj);
1740:                    if (rep != obj) {
1741:                        handles.setObject(passHandle, obj = rep);
1742:                    }
1743:                }
1744:
1745:                return obj;
1746:            }
1747:
1748:            /**
1749:             * If obj is non-null, reads externalizable data by invoking readExternal()
1750:             * method of obj; otherwise, attempts to skip over externalizable data.
1751:             * Expects that passHandle is set to obj's handle before this method is
1752:             * called.
1753:             */
1754:            private void readExternalData(Externalizable obj,
1755:                    ObjectStreamClass desc) throws IOException {
1756:                Object oldObj = curObj;
1757:                ObjectStreamClass oldDesc = curDesc;
1758:                GetFieldImpl oldGet = curGet;
1759:                curObj = obj;
1760:                curDesc = null;
1761:                curGet = null;
1762:
1763:                boolean blocked = desc.hasBlockExternalData();
1764:                if (blocked) {
1765:                    bin.setBlockDataMode(true);
1766:                }
1767:                if (obj != null) {
1768:                    try {
1769:                        obj.readExternal(this );
1770:                    } catch (ClassNotFoundException ex) {
1771:                        /*
1772:                         * In most cases, the handle table has already propagated a
1773:                         * CNFException to passHandle at this point; this mark call is
1774:                         * included to address cases where the readExternal method has
1775:                         * cons'ed and thrown a new CNFException of its own.
1776:                         */
1777:                        handles.markException(passHandle, ex);
1778:                    }
1779:                }
1780:                if (blocked) {
1781:                    skipCustomData();
1782:                }
1783:
1784:                /*
1785:                 * At this point, if the externalizable data was not written in
1786:                 * block-data form and either the externalizable class doesn't exist
1787:                 * locally (i.e., obj == null) or readExternal() just threw a
1788:                 * CNFException, then the stream is probably in an inconsistent state,
1789:                 * since some (or all) of the externalizable data may not have been
1790:                 * consumed.  Since there's no "correct" action to take in this case,
1791:                 * we mimic the behavior of past serialization implementations and
1792:                 * blindly hope that the stream is in sync; if it isn't and additional
1793:                 * externalizable data remains in the stream, a subsequent read will
1794:                 * most likely throw a StreamCorruptedException.
1795:                 */
1796:
1797:                curObj = oldObj;
1798:                curDesc = oldDesc;
1799:                curGet = oldGet;
1800:            }
1801:
1802:            /**
1803:             * Reads (or attempts to skip, if obj is null or is tagged with a
1804:             * ClassNotFoundException) instance data for each serializable class of
1805:             * object in stream, from superclass to subclass.  Expects that passHandle
1806:             * is set to obj's handle before this method is called.
1807:             */
1808:            private void readSerialData(Object obj, ObjectStreamClass desc)
1809:                    throws IOException {
1810:                ObjectStreamClass.ClassDataSlot[] slots = desc
1811:                        .getClassDataLayout();
1812:                for (int i = 0; i < slots.length; i++) {
1813:                    ObjectStreamClass slotDesc = slots[i].desc;
1814:
1815:                    if (slots[i].hasData) {
1816:                        if (obj != null && slotDesc.hasReadObjectMethod()
1817:                                && handles.lookupException(passHandle) == null) {
1818:                            Object oldObj = curObj;
1819:                            ObjectStreamClass oldDesc = curDesc;
1820:                            GetFieldImpl oldGet = curGet;
1821:                            curObj = obj;
1822:                            curDesc = slotDesc;
1823:                            curGet = null;
1824:
1825:                            bin.setBlockDataMode(true);
1826:                            try {
1827:                                slotDesc.invokeReadObject(obj, this );
1828:                            } catch (ClassNotFoundException ex) {
1829:                                /*
1830:                                 * In most cases, the handle table has already
1831:                                 * propagated a CNFException to passHandle at this
1832:                                 * point; this mark call is included to address cases
1833:                                 * where the custom readObject method has cons'ed and
1834:                                 * thrown a new CNFException of its own.
1835:                                 */
1836:                                handles.markException(passHandle, ex);
1837:                            }
1838:
1839:                            curObj = oldObj;
1840:                            curDesc = oldDesc;
1841:                            curGet = oldGet;
1842:
1843:                            /*
1844:                             * defaultDataEnd may have been set indirectly by custom
1845:                             * readObject() method when calling defaultReadObject() or
1846:                             * readFields(); clear it to restore normal read behavior.
1847:                             */
1848:                            defaultDataEnd = false;
1849:                        } else {
1850:                            defaultReadFields(obj, slotDesc);
1851:                        }
1852:                        if (slotDesc.hasWriteObjectData()) {
1853:                            skipCustomData();
1854:                        } else {
1855:                            bin.setBlockDataMode(false);
1856:                        }
1857:                    } else {
1858:                        if (obj != null && slotDesc.hasReadObjectNoDataMethod()
1859:                                && handles.lookupException(passHandle) == null) {
1860:                            slotDesc.invokeReadObjectNoData(obj);
1861:                        }
1862:                    }
1863:                }
1864:            }
1865:
1866:            /**
1867:             * Skips over all block data and objects until TC_ENDBLOCKDATA is
1868:             * encountered.
1869:             */
1870:            private void skipCustomData() throws IOException {
1871:                int oldHandle = passHandle;
1872:                for (;;) {
1873:                    if (bin.getBlockDataMode()) {
1874:                        bin.skipBlockData();
1875:                        bin.setBlockDataMode(false);
1876:                    }
1877:                    switch (bin.peekByte()) {
1878:                    case TC_BLOCKDATA:
1879:                    case TC_BLOCKDATALONG:
1880:                        bin.setBlockDataMode(true);
1881:                        break;
1882:
1883:                    case TC_ENDBLOCKDATA:
1884:                        bin.readByte();
1885:                        passHandle = oldHandle;
1886:                        return;
1887:
1888:                    default:
1889:                        readObject0(false);
1890:                        break;
1891:                    }
1892:                }
1893:            }
1894:
1895:            /**
1896:             * Reads in values of serializable fields declared by given class
1897:             * descriptor.  If obj is non-null, sets field values in obj.  Expects that
1898:             * passHandle is set to obj's handle before this method is called.
1899:             */
1900:            private void defaultReadFields(Object obj, ObjectStreamClass desc)
1901:                    throws IOException {
1902:                // REMIND: is isInstance check necessary?
1903:                Class cl = desc.forClass();
1904:                if (cl != null && obj != null && !cl.isInstance(obj)) {
1905:                    throw new ClassCastException();
1906:                }
1907:
1908:                int primDataSize = desc.getPrimDataSize();
1909:                if (primVals == null || primVals.length < primDataSize) {
1910:                    primVals = new byte[primDataSize];
1911:                }
1912:                bin.readFully(primVals, 0, primDataSize, false);
1913:                if (obj != null) {
1914:                    desc.setPrimFieldValues(obj, primVals);
1915:                }
1916:
1917:                int objHandle = passHandle;
1918:                ObjectStreamField[] fields = desc.getFields(false);
1919:                Object[] objVals = new Object[desc.getNumObjFields()];
1920:                int numPrimFields = fields.length - objVals.length;
1921:                for (int i = 0; i < objVals.length; i++) {
1922:                    ObjectStreamField f = fields[numPrimFields + i];
1923:                    objVals[i] = readObject0(f.isUnshared());
1924:                    if (f.getField() != null) {
1925:                        handles.markDependency(objHandle, passHandle);
1926:                    }
1927:                }
1928:                if (obj != null) {
1929:                    desc.setObjFieldValues(obj, objVals);
1930:                }
1931:                passHandle = objHandle;
1932:            }
1933:
1934:            /**
1935:             * Reads in and returns IOException that caused serialization to abort.
1936:             * All stream state is discarded prior to reading in fatal exception.  Sets
1937:             * passHandle to fatal exception's handle.
1938:             */
1939:            private IOException readFatalException() throws IOException {
1940:                if (bin.readByte() != TC_EXCEPTION) {
1941:                    throw new StreamCorruptedException();
1942:                }
1943:                clear();
1944:                return (IOException) readObject0(false);
1945:            }
1946:
1947:            /**
1948:             * If recursion depth is 0, clears internal data structures; otherwise,
1949:             * throws a StreamCorruptedException.  This method is called when a
1950:             * TC_RESET typecode is encountered.
1951:             */
1952:            private void handleReset() throws StreamCorruptedException {
1953:                if (depth > 0) {
1954:                    throw new StreamCorruptedException("unexpected reset");
1955:                }
1956:                clear();
1957:            }
1958:
1959:            /**
1960:             * Converts specified span of bytes into float values.
1961:             */
1962:            // REMIND: remove once hotspot inlines Float.intBitsToFloat
1963:            private static native void bytesToFloats(byte[] src, int srcpos,
1964:                    float[] dst, int dstpos, int nfloats);
1965:
1966:            /**
1967:             * Converts specified span of bytes into double values.
1968:             */
1969:            // REMIND: remove once hotspot inlines Double.longBitsToDouble
1970:            private static native void bytesToDoubles(byte[] src, int srcpos,
1971:                    double[] dst, int dstpos, int ndoubles);
1972:
1973:            /**
1974:             * Returns the first non-null class loader (not counting class loaders of
1975:             * generated reflection implementation classes) up the execution stack, or
1976:             * null if only code from the null class loader is on the stack.  This
1977:             * method is also called via reflection by the following RMI-IIOP class:
1978:             * 
1979:             *     com.sun.corba.se.internal.util.JDKClassLoader
1980:             *     
1981:             * This method should not be removed or its signature changed without
1982:             * corresponding modifications to the above class.
1983:             */
1984:            // REMIND: change name to something more accurate?
1985:            private static native ClassLoader latestUserDefinedLoader();
1986:
1987:            /**
1988:             * Default GetField implementation.
1989:             */
1990:            private class GetFieldImpl extends GetField {
1991:
1992:                /** class descriptor describing serializable fields */
1993:                private final ObjectStreamClass desc;
1994:                /** primitive field values */
1995:                private final byte[] primVals;
1996:                /** object field values */
1997:                private final Object[] objVals;
1998:                /** object field value handles */
1999:                private final int[] objHandles;
2000:
2001:                /**
2002:                 * Creates GetFieldImpl object for reading fields defined in given
2003:                 * class descriptor.
2004:                 */
2005:                GetFieldImpl(ObjectStreamClass desc) {
2006:                    this .desc = desc;
2007:                    primVals = new byte[desc.getPrimDataSize()];
2008:                    objVals = new Object[desc.getNumObjFields()];
2009:                    objHandles = new int[objVals.length];
2010:                }
2011:
2012:                public ObjectStreamClass getObjectStreamClass() {
2013:                    return desc;
2014:                }
2015:
2016:                public boolean defaulted(String name) throws IOException {
2017:                    return (getFieldOffset(name, null) < 0);
2018:                }
2019:
2020:                public boolean get(String name, boolean val) throws IOException {
2021:                    int off = getFieldOffset(name, Boolean.TYPE);
2022:                    return (off >= 0) ? Bits.getBoolean(primVals, off) : val;
2023:                }
2024:
2025:                public byte get(String name, byte val) throws IOException {
2026:                    int off = getFieldOffset(name, Byte.TYPE);
2027:                    return (off >= 0) ? primVals[off] : val;
2028:                }
2029:
2030:                public char get(String name, char val) throws IOException {
2031:                    int off = getFieldOffset(name, Character.TYPE);
2032:                    return (off >= 0) ? Bits.getChar(primVals, off) : val;
2033:                }
2034:
2035:                public short get(String name, short val) throws IOException {
2036:                    int off = getFieldOffset(name, Short.TYPE);
2037:                    return (off >= 0) ? Bits.getShort(primVals, off) : val;
2038:                }
2039:
2040:                public int get(String name, int val) throws IOException {
2041:                    int off = getFieldOffset(name, Integer.TYPE);
2042:                    return (off >= 0) ? Bits.getInt(primVals, off) : val;
2043:                }
2044:
2045:                public float get(String name, float val) throws IOException {
2046:                    int off = getFieldOffset(name, Float.TYPE);
2047:                    return (off >= 0) ? Bits.getFloat(primVals, off) : val;
2048:                }
2049:
2050:                public long get(String name, long val) throws IOException {
2051:                    int off = getFieldOffset(name, Long.TYPE);
2052:                    return (off >= 0) ? Bits.getLong(primVals, off) : val;
2053:                }
2054:
2055:                public double get(String name, double val) throws IOException {
2056:                    int off = getFieldOffset(name, Double.TYPE);
2057:                    return (off >= 0) ? Bits.getDouble(primVals, off) : val;
2058:                }
2059:
2060:                public Object get(String name, Object val) throws IOException {
2061:                    int off = getFieldOffset(name, Object.class);
2062:                    if (off >= 0) {
2063:                        int objHandle = objHandles[off];
2064:                        handles.markDependency(passHandle, objHandle);
2065:                        return (handles.lookupException(objHandle) == null) ? objVals[off]
2066:                                : null;
2067:                    } else {
2068:                        return val;
2069:                    }
2070:                }
2071:
2072:                /**
2073:                 * Reads primitive and object field values from stream.
2074:                 */
2075:                void readFields() throws IOException {
2076:                    bin.readFully(primVals, 0, primVals.length, false);
2077:
2078:                    int oldHandle = passHandle;
2079:                    ObjectStreamField[] fields = desc.getFields(false);
2080:                    int numPrimFields = fields.length - objVals.length;
2081:                    for (int i = 0; i < objVals.length; i++) {
2082:                        objVals[i] = readObject0(fields[numPrimFields + i]
2083:                                .isUnshared());
2084:                        objHandles[i] = passHandle;
2085:                    }
2086:                    passHandle = oldHandle;
2087:                }
2088:
2089:                /**
2090:                 * Returns offset of field with given name and type.  A specified type
2091:                 * of null matches all types, Object.class matches all non-primitive
2092:                 * types, and any other non-null type matches assignable types only.
2093:                 * If no matching field is found in the (incoming) class
2094:                 * descriptor but a matching field is present in the associated local
2095:                 * class descriptor, returns -1.  Throws IllegalArgumentException if
2096:                 * neither incoming nor local class descriptor contains a match.
2097:                 */
2098:                private int getFieldOffset(String name, Class type) {
2099:                    ObjectStreamField field = desc.getField(name, type);
2100:                    if (field != null) {
2101:                        return field.getOffset();
2102:                    } else if (desc.getLocalDesc().getField(name, type) != null) {
2103:                        return -1;
2104:                    } else {
2105:                        throw new IllegalArgumentException("no such field");
2106:                    }
2107:                }
2108:            }
2109:
2110:            /**
2111:             * Prioritized list of callbacks to be performed once object graph has been
2112:             * completely deserialized.
2113:             */
2114:            private static class ValidationList {
2115:
2116:                private static class Callback {
2117:                    final ObjectInputValidation obj;
2118:                    final int priority;
2119:                    Callback next;
2120:
2121:                    Callback(ObjectInputValidation obj, int priority,
2122:                            Callback next) {
2123:                        this .obj = obj;
2124:                        this .priority = priority;
2125:                        this .next = next;
2126:                    }
2127:                }
2128:
2129:                /** linked list of callbacks */
2130:                private Callback list;
2131:
2132:                /**
2133:                 * Creates new (empty) ValidationList.
2134:                 */
2135:                ValidationList() {
2136:                }
2137:
2138:                /**
2139:                 * Registers callback.  Throws InvalidObjectException if callback
2140:                 * object is null.
2141:                 */
2142:                void register(ObjectInputValidation obj, int priority)
2143:                        throws InvalidObjectException {
2144:                    if (obj == null) {
2145:                        throw new InvalidObjectException("null callback");
2146:                    }
2147:
2148:                    Callback prev = null, cur = list;
2149:                    while (cur != null && priority < cur.priority) {
2150:                        prev = cur;
2151:                        cur = cur.next;
2152:                    }
2153:                    if (prev != null) {
2154:                        prev.next = new Callback(obj, priority, cur);
2155:                    } else {
2156:                        list = new Callback(obj, priority, list);
2157:                    }
2158:                }
2159:
2160:                /**
2161:                 * Invokes all registered callbacks and clears the callback list.
2162:                 * Callbacks with higher priorities are called first; those with equal
2163:                 * priorities may be called in any order.  If any of the callbacks
2164:                 * throws an InvalidObjectException, the callback process is terminated
2165:                 * and the exception propagated upwards.
2166:                 */
2167:                void doCallbacks() throws InvalidObjectException {
2168:                    try {
2169:                        while (list != null) {
2170:                            list.obj.validateObject();
2171:                            list = list.next;
2172:                        }
2173:                    } catch (InvalidObjectException ex) {
2174:                        list = null;
2175:                        throw ex;
2176:                    }
2177:                }
2178:
2179:                /**
2180:                 * Resets the callback list to its initial (empty) state.
2181:                 */
2182:                public void clear() {
2183:                    list = null;
2184:                }
2185:            }
2186:
2187:            /**
2188:             * Input stream supporting single-byte peek operations.
2189:             */
2190:            private static class PeekInputStream extends InputStream {
2191:
2192:                /** underlying stream */
2193:                private final InputStream in;
2194:                /** peeked byte */
2195:                private int peekb = -1;
2196:
2197:                /**
2198:                 * Creates new PeekInputStream on top of given underlying stream.
2199:                 */
2200:                PeekInputStream(InputStream in) {
2201:                    this .in = in;
2202:                }
2203:
2204:                /**
2205:                 * Peeks at next byte value in stream.  Similar to read(), except
2206:                 * that it does not consume the read value.
2207:                 */
2208:                int peek() throws IOException {
2209:                    return (peekb >= 0) ? peekb : (peekb = in.read());
2210:                }
2211:
2212:                public int read() throws IOException {
2213:                    if (peekb >= 0) {
2214:                        int v = peekb;
2215:                        peekb = -1;
2216:                        return v;
2217:                    } else {
2218:                        return in.read();
2219:                    }
2220:                }
2221:
2222:                public int read(byte[] b, int off, int len) throws IOException {
2223:                    if (len == 0) {
2224:                        return 0;
2225:                    } else if (peekb < 0) {
2226:                        return in.read(b, off, len);
2227:                    } else {
2228:                        b[off++] = (byte) peekb;
2229:                        len--;
2230:                        peekb = -1;
2231:                        int n = in.read(b, off, len);
2232:                        return (n >= 0) ? (n + 1) : 1;
2233:                    }
2234:                }
2235:
2236:                void readFully(byte[] b, int off, int len) throws IOException {
2237:                    int n = 0;
2238:                    while (n < len) {
2239:                        int count = read(b, off + n, len - n);
2240:                        if (count < 0) {
2241:                            throw new EOFException();
2242:                        }
2243:                        n += count;
2244:                    }
2245:                }
2246:
2247:                public long skip(long n) throws IOException {
2248:                    if (n <= 0) {
2249:                        return 0;
2250:                    }
2251:                    int skipped = 0;
2252:                    if (peekb >= 0) {
2253:                        peekb = -1;
2254:                        skipped++;
2255:                        n--;
2256:                    }
2257:                    return skipped + skip(n);
2258:                }
2259:
2260:                public int available() throws IOException {
2261:                    return in.available() + ((peekb >= 0) ? 1 : 0);
2262:                }
2263:
2264:                public void close() throws IOException {
2265:                    in.close();
2266:                }
2267:            }
2268:
2269:            /**
2270:             * Input stream with two modes: in default mode, inputs data written in the
2271:             * same format as DataOutputStream; in "block data" mode, inputs data
2272:             * bracketed by block data markers (see object serialization specification
2273:             * for details).  Buffering depends on block data mode: when in default
2274:             * mode, no data is buffered in advance; when in block data mode, all data
2275:             * for the current data block is read in at once (and buffered).
2276:             */
2277:            private class BlockDataInputStream extends InputStream implements 
2278:                    DataInput {
2279:                /** maximum data block length */
2280:                private static final int MAX_BLOCK_SIZE = 1024;
2281:                /** maximum data block header length */
2282:                private static final int MAX_HEADER_SIZE = 5;
2283:                /** (tunable) length of char buffer (for reading strings) */
2284:                private static final int CHAR_BUF_SIZE = 256;
2285:                /** readBlockHeader() return value indicating header read may block */
2286:                private static final int HEADER_BLOCKED = -2;
2287:
2288:                /** buffer for reading general/block data */
2289:                private final byte[] buf = new byte[MAX_BLOCK_SIZE];
2290:                /** buffer for reading block data headers */
2291:                private final byte[] hbuf = new byte[MAX_HEADER_SIZE];
2292:                /** char buffer for fast string reads */
2293:                private final char[] cbuf = new char[CHAR_BUF_SIZE];
2294:
2295:                /** block data mode */
2296:                private boolean blkmode = false;
2297:
2298:                // block data state fields; values meaningful only when blkmode true
2299:                /** current offset into buf */
2300:                private int pos = 0;
2301:                /** end offset of valid data in buf, or -1 if no more block data */
2302:                private int end = -1;
2303:                /** number of bytes in current block yet to be read from stream */
2304:                private int unread = 0;
2305:
2306:                /** underlying stream (wrapped in peekable filter stream) */
2307:                private final PeekInputStream in;
2308:                /** loopback stream (for data reads that span data blocks) */
2309:                private final DataInputStream din;
2310:
2311:                /**
2312:                 * Creates new BlockDataInputStream on top of given underlying stream.
2313:                 * Block data mode is turned off by default.
2314:                 */
2315:                BlockDataInputStream(InputStream in) {
2316:                    this .in = new PeekInputStream(in);
2317:                    din = new DataInputStream(this );
2318:                }
2319:
2320:                /**
2321:                 * Sets block data mode to the given mode (true == on, false == off)
2322:                 * and returns the previous mode value.  If the new mode is the same as
2323:                 * the old mode, no action is taken.  Throws IllegalStateException if
2324:                 * block data mode is being switched from on to off while unconsumed
2325:                 * block data is still present in the stream.
2326:                 */
2327:                boolean setBlockDataMode(boolean newmode) throws IOException {
2328:                    if (blkmode == newmode) {
2329:                        return blkmode;
2330:                    }
2331:                    if (newmode) {
2332:                        pos = 0;
2333:                        end = 0;
2334:                        unread = 0;
2335:                    } else if (pos < end) {
2336:                        throw new IllegalStateException("unread block data");
2337:                    }
2338:                    blkmode = newmode;
2339:                    return !blkmode;
2340:                }
2341:
2342:                /**
2343:                 * Returns true if the stream is currently in block data mode, false
2344:                 * otherwise.
2345:                 */
2346:                boolean getBlockDataMode() {
2347:                    return blkmode;
2348:                }
2349:
2350:                /**
2351:                 * If in block data mode, skips to the end of the current group of data
2352:                 * blocks (but does not unset block data mode).  If not in block data
2353:                 * mode, throws an IllegalStateException.
2354:                 */
2355:                void skipBlockData() throws IOException {
2356:                    if (!blkmode) {
2357:                        throw new IllegalStateException(
2358:                                "not in block data mode");
2359:                    }
2360:                    while (end >= 0) {
2361:                        refill();
2362:                    }
2363:                }
2364:
2365:                /**
2366:                 * Attempts to read in the next block data header (if any).  If
2367:                 * canBlock is false and a full header cannot be read without possibly
2368:                 * blocking, returns HEADER_BLOCKED, else if the next element in the
2369:                 * stream is a block data header, returns the block data length
2370:                 * specified by the header, else returns -1.
2371:                 */
2372:                private int readBlockHeader(boolean canBlock)
2373:                        throws IOException {
2374:                    if (defaultDataEnd) {
2375:                        /*
2376:                         * Fix for 4360508: stream is currently at the end of a field
2377:                         * value block written via default serialization; since there
2378:                         * is no terminating TC_ENDBLOCKDATA tag, simulate
2379:                         * end-of-custom-data behavior explicitly.
2380:                         */
2381:                        return -1;
2382:                    }
2383:                    try {
2384:                        for (;;) {
2385:                            int avail = canBlock ? Integer.MAX_VALUE : in
2386:                                    .available();
2387:                            if (avail == 0) {
2388:                                return HEADER_BLOCKED;
2389:                            }
2390:
2391:                            int tc = in.peek();
2392:                            switch (tc) {
2393:                            case TC_BLOCKDATA:
2394:                                if (avail < 2) {
2395:                                    return HEADER_BLOCKED;
2396:                                }
2397:                                in.readFully(hbuf, 0, 2);
2398:                                return hbuf[1] & 0xFF;
2399:
2400:                            case TC_BLOCKDATALONG:
2401:                                if (avail < 5) {
2402:                                    return HEADER_BLOCKED;
2403:                                }
2404:                                in.readFully(hbuf, 0, 5);
2405:                                int len = Bits.getInt(hbuf, 1);
2406:                                if (len < 0) {
2407:                                    throw new StreamCorruptedException(
2408:                                            "illegal block data header length");
2409:                                }
2410:                                return len;
2411:
2412:                                /*
2413:                                 * TC_RESETs may occur in between data blocks.
2414:                                 * Unfortunately, this case must be parsed at a lower
2415:                                 * level than other typecodes, since primitive data
2416:                                 * reads may span data blocks separated by a TC_RESET.
2417:                                 */
2418:                            case TC_RESET:
2419:                                in.read();
2420:                                handleReset();
2421:                                break;
2422:
2423:                            default:
2424:                                if (tc >= 0 && (tc < TC_BASE || tc > TC_MAX)) {
2425:                                    throw new StreamCorruptedException();
2426:                                }
2427:                                return -1;
2428:                            }
2429:                        }
2430:                    } catch (EOFException ex) {
2431:                        throw new StreamCorruptedException(
2432:                                "unexpected EOF while reading block data header");
2433:                    }
2434:                }
2435:
2436:                /**
2437:                 * Refills internal buffer buf with block data.  Any data in buf at the
2438:                 * time of the call is considered consumed.  Sets the pos, end, and
2439:                 * unread fields to reflect the new amount of available block data; if
2440:                 * the next element in the stream is not a data block, sets pos and
2441:                 * unread to 0 and end to -1.
2442:                 */
2443:                private void refill() throws IOException {
2444:                    try {
2445:                        do {
2446:                            pos = 0;
2447:                            if (unread > 0) {
2448:                                int n = in.read(buf, 0, Math.min(unread,
2449:                                        MAX_BLOCK_SIZE));
2450:                                if (n >= 0) {
2451:                                    end = n;
2452:                                    unread -= n;
2453:                                } else {
2454:                                    throw new StreamCorruptedException(
2455:                                            "unexpected EOF in middle of data block");
2456:                                }
2457:                            } else {
2458:                                int n = readBlockHeader(true);
2459:                                if (n >= 0) {
2460:                                    end = 0;
2461:                                    unread = n;
2462:                                } else {
2463:                                    end = -1;
2464:                                    unread = 0;
2465:                                }
2466:                            }
2467:                        } while (pos == end);
2468:                    } catch (IOException ex) {
2469:                        pos = 0;
2470:                        end = -1;
2471:                        unread = 0;
2472:                        throw ex;
2473:                    }
2474:                }
2475:
2476:                /**
2477:                 * If in block data mode, returns the number of unconsumed bytes
2478:                 * remaining in the current data block.  If not in block data mode,
2479:                 * throws an IllegalStateException.
2480:                 */
2481:                int currentBlockRemaining() {
2482:                    if (blkmode) {
2483:                        return (end >= 0) ? (end - pos) + unread : 0;
2484:                    } else {
2485:                        throw new IllegalStateException();
2486:                    }
2487:                }
2488:
2489:                /**
2490:                 * Peeks at (but does not consume) and returns the next byte value in
2491:                 * the stream, or -1 if the end of the stream/block data (if in block
2492:                 * data mode) has been reached.
2493:                 */
2494:                int peek() throws IOException {
2495:                    if (blkmode) {
2496:                        if (pos == end) {
2497:                            refill();
2498:                        }
2499:                        return (end >= 0) ? (buf[pos] & 0xFF) : -1;
2500:                    } else {
2501:                        return in.peek();
2502:                    }
2503:                }
2504:
2505:                /**
2506:                 * Peeks at (but does not consume) and returns the next byte value in
2507:                 * the stream, or throws EOFException if end of stream/block data has
2508:                 * been reached.
2509:                 */
2510:                byte peekByte() throws IOException {
2511:                    int val = peek();
2512:                    if (val < 0) {
2513:                        throw new EOFException();
2514:                    }
2515:                    return (byte) val;
2516:                }
2517:
2518:                /* ----------------- generic input stream methods ------------------ */
2519:                /*
2520:                 * The following methods are equivalent to their counterparts in
2521:                 * InputStream, except that they interpret data block boundaries and
2522:                 * read the requested data from within data blocks when in block data
2523:                 * mode.
2524:                 */
2525:
2526:                public int read() throws IOException {
2527:                    if (blkmode) {
2528:                        if (pos == end) {
2529:                            refill();
2530:                        }
2531:                        return (end >= 0) ? (buf[pos++] & 0xFF) : -1;
2532:                    } else {
2533:                        return in.read();
2534:                    }
2535:                }
2536:
2537:                public int read(byte[] b, int off, int len) throws IOException {
2538:                    return read(b, off, len, false);
2539:                }
2540:
2541:                public long skip(long len) throws IOException {
2542:                    long remain = len;
2543:                    while (remain > 0) {
2544:                        if (blkmode) {
2545:                            if (pos == end) {
2546:                                refill();
2547:                            }
2548:                            if (end < 0) {
2549:                                break;
2550:                            }
2551:                            int nread = (int) Math.min(remain, end - pos);
2552:                            remain -= nread;
2553:                            pos += nread;
2554:                        } else {
2555:                            int nread = (int) Math.min(remain, MAX_BLOCK_SIZE);
2556:                            if ((nread = in.read(buf, 0, nread)) < 0) {
2557:                                break;
2558:                            }
2559:                            remain -= nread;
2560:                        }
2561:                    }
2562:                    return len - remain;
2563:                }
2564:
2565:                public int available() throws IOException {
2566:                    if (blkmode) {
2567:                        if ((pos == end) && (unread == 0)) {
2568:                            int n;
2569:                            while ((n = readBlockHeader(false)) == 0)
2570:                                ;
2571:                            switch (n) {
2572:                            case HEADER_BLOCKED:
2573:                                break;
2574:
2575:                            case -1:
2576:                                pos = 0;
2577:                                end = -1;
2578:                                break;
2579:
2580:                            default:
2581:                                pos = 0;
2582:                                end = 0;
2583:                                unread = n;
2584:                                break;
2585:                            }
2586:                        }
2587:                        // avoid unnecessary call to in.available() if possible
2588:                        int unreadAvail = (unread > 0) ? Math.min(in
2589:                                .available(), unread) : 0;
2590:                        return (end >= 0) ? (end - pos) + unreadAvail : 0;
2591:                    } else {
2592:                        return in.available();
2593:                    }
2594:                }
2595:
2596:                public void close() throws IOException {
2597:                    if (blkmode) {
2598:                        pos = 0;
2599:                        end = -1;
2600:                        unread = 0;
2601:                    }
2602:                    in.close();
2603:                }
2604:
2605:                /**
2606:                 * Attempts to read len bytes into byte array b at offset off.  Returns
2607:                 * the number of bytes read, or -1 if the end of stream/block data has
2608:                 * been reached.  If copy is true, reads values into an intermediate
2609:                 * buffer before copying them to b (to avoid exposing a reference to
2610:                 * b).
2611:                 */
2612:                int read(byte[] b, int off, int len, boolean copy)
2613:                        throws IOException {
2614:                    if (len == 0) {
2615:                        return 0;
2616:                    } else if (blkmode) {
2617:                        if (pos == end) {
2618:                            refill();
2619:                        }
2620:                        if (end < 0) {
2621:                            return -1;
2622:                        }
2623:                        int nread = Math.min(len, end - pos);
2624:                        System.arraycopy(buf, pos, b, off, nread);
2625:                        pos += nread;
2626:                        return nread;
2627:                    } else if (copy) {
2628:                        int nread = in.read(buf, 0, Math.min(len,
2629:                                MAX_BLOCK_SIZE));
2630:                        if (nread > 0) {
2631:                            System.arraycopy(buf, 0, b, off, nread);
2632:                        }
2633:                        return nread;
2634:                    } else {
2635:                        return in.read(b, off, len);
2636:                    }
2637:                }
2638:
2639:                /* ----------------- primitive data input methods ------------------ */
2640:                /*
2641:                 * The following methods are equivalent to their counterparts in
2642:                 * DataInputStream, except that they interpret data block boundaries
2643:                 * and read the requested data from within data blocks when in block
2644:                 * data mode.
2645:                 */
2646:
2647:                public void readFully(byte[] b) throws IOException {
2648:                    readFully(b, 0, b.length, false);
2649:                }
2650:
2651:                public void readFully(byte[] b, int off, int len)
2652:                        throws IOException {
2653:                    readFully(b, off, len, false);
2654:                }
2655:
2656:                public void readFully(byte[] b, int off, int len, boolean copy)
2657:                        throws IOException {
2658:                    while (len > 0) {
2659:                        int n = read(b, off, len, copy);
2660:                        if (n < 0) {
2661:                            throw new EOFException();
2662:                        }
2663:                        off += n;
2664:                        len -= n;
2665:                    }
2666:                }
2667:
2668:                public int skipBytes(int n) throws IOException {
2669:                    return din.skipBytes(n);
2670:                }
2671:
2672:                public boolean readBoolean() throws IOException {
2673:                    int v = read();
2674:                    if (v < 0) {
2675:                        throw new EOFException();
2676:                    }
2677:                    return (v != 0);
2678:                }
2679:
2680:                public byte readByte() throws IOException {
2681:                    int v = read();
2682:                    if (v < 0) {
2683:                        throw new EOFException();
2684:                    }
2685:                    return (byte) v;
2686:                }
2687:
2688:                public int readUnsignedByte() throws IOException {
2689:                    int v = read();
2690:                    if (v < 0) {
2691:                        throw new EOFException();
2692:                    }
2693:                    return v;
2694:                }
2695:
2696:                public char readChar() throws IOException {
2697:                    if (!blkmode) {
2698:                        pos = 0;
2699:                        in.readFully(buf, 0, 2);
2700:                    } else if (end - pos < 2) {
2701:                        return din.readChar();
2702:                    }
2703:                    char v = Bits.getChar(buf, pos);
2704:                    pos += 2;
2705:                    return v;
2706:                }
2707:
2708:                public short readShort() throws IOException {
2709:                    if (!blkmode) {
2710:                        pos = 0;
2711:                        in.readFully(buf, 0, 2);
2712:                    } else if (end - pos < 2) {
2713:                        return din.readShort();
2714:                    }
2715:                    short v = Bits.getShort(buf, pos);
2716:                    pos += 2;
2717:                    return v;
2718:                }
2719:
2720:                public int readUnsignedShort() throws IOException {
2721:                    if (!blkmode) {
2722:                        pos = 0;
2723:                        in.readFully(buf, 0, 2);
2724:                    } else if (end - pos < 2) {
2725:                        return din.readUnsignedShort();
2726:                    }
2727:                    int v = Bits.getShort(buf, pos) & 0xFFFF;
2728:                    pos += 2;
2729:                    return v;
2730:                }
2731:
2732:                public int readInt() throws IOException {
2733:                    if (!blkmode) {
2734:                        pos = 0;
2735:                        in.readFully(buf, 0, 4);
2736:                    } else if (end - pos < 4) {
2737:                        return din.readInt();
2738:                    }
2739:                    int v = Bits.getInt(buf, pos);
2740:                    pos += 4;
2741:                    return v;
2742:                }
2743:
2744:                public float readFloat() throws IOException {
2745:                    if (!blkmode) {
2746:                        pos = 0;
2747:                        in.readFully(buf, 0, 4);
2748:                    } else if (end - pos < 4) {
2749:                        return din.readFloat();
2750:                    }
2751:                    float v = Bits.getFloat(buf, pos);
2752:                    pos += 4;
2753:                    return v;
2754:                }
2755:
2756:                public long readLong() throws IOException {
2757:                    if (!blkmode) {
2758:                        pos = 0;
2759:                        in.readFully(buf, 0, 8);
2760:                    } else if (end - pos < 8) {
2761:                        return din.readLong();
2762:                    }
2763:                    long v = Bits.getLong(buf, pos);
2764:                    pos += 8;
2765:                    return v;
2766:                }
2767:
2768:                public double readDouble() throws IOException {
2769:                    if (!blkmode) {
2770:                        pos = 0;
2771:                        in.readFully(buf, 0, 8);
2772:                    } else if (end - pos < 8) {
2773:                        return din.readDouble();
2774:                    }
2775:                    double v = Bits.getDouble(buf, pos);
2776:                    pos += 8;
2777:                    return v;
2778:                }
2779:
2780:                public String readUTF() throws IOException {
2781:                    return readUTFBody(readUnsignedShort());
2782:                }
2783:
2784:                public String readLine() throws IOException {
2785:                    return ((DataInput) din).readLine(); // deprecated, not worth optimizing
2786:                }
2787:
2788:                /* -------------- primitive data array input methods --------------- */
2789:                /*
2790:                 * The following methods read in spans of primitive data values.
2791:                 * Though equivalent to calling the corresponding primitive read
2792:                 * methods repeatedly, these methods are optimized for reading groups
2793:                 * of primitive data values more efficiently.
2794:                 */
2795:
2796:                void readBooleans(boolean[] v, int off, int len)
2797:                        throws IOException {
2798:                    int stop, endoff = off + len;
2799:                    while (off < endoff) {
2800:                        if (!blkmode) {
2801:                            int span = Math.min(endoff - off, MAX_BLOCK_SIZE);
2802:                            in.readFully(buf, 0, span);
2803:                            stop = off + span;
2804:                            pos = 0;
2805:                        } else if (end - pos < 1) {
2806:                            v[off++] = din.readBoolean();
2807:                            continue;
2808:                        } else {
2809:                            stop = Math.min(endoff, off + end - pos);
2810:                        }
2811:
2812:                        while (off < stop) {
2813:                            v[off++] = Bits.getBoolean(buf, pos++);
2814:                        }
2815:                    }
2816:                }
2817:
2818:                void readChars(char[] v, int off, int len) throws IOException {
2819:                    int stop, endoff = off + len;
2820:                    while (off < endoff) {
2821:                        if (!blkmode) {
2822:                            int span = Math.min(endoff - off,
2823:                                    MAX_BLOCK_SIZE >> 1);
2824:                            in.readFully(buf, 0, span << 1);
2825:                            stop = off + span;
2826:                            pos = 0;
2827:                        } else if (end - pos < 2) {
2828:                            v[off++] = din.readChar();
2829:                            continue;
2830:                        } else {
2831:                            stop = Math.min(endoff, off + ((end - pos) >> 1));
2832:                        }
2833:
2834:                        while (off < stop) {
2835:                            v[off++] = Bits.getChar(buf, pos);
2836:                            pos += 2;
2837:                        }
2838:                    }
2839:                }
2840:
2841:                void readShorts(short[] v, int off, int len) throws IOException {
2842:                    int stop, endoff = off + len;
2843:                    while (off < endoff) {
2844:                        if (!blkmode) {
2845:                            int span = Math.min(endoff - off,
2846:                                    MAX_BLOCK_SIZE >> 1);
2847:                            in.readFully(buf, 0, span << 1);
2848:                            stop = off + span;
2849:                            pos = 0;
2850:                        } else if (end - pos < 2) {
2851:                            v[off++] = din.readShort();
2852:                            continue;
2853:                        } else {
2854:                            stop = Math.min(endoff, off + ((end - pos) >> 1));
2855:                        }
2856:
2857:                        while (off < stop) {
2858:                            v[off++] = Bits.getShort(buf, pos);
2859:                            pos += 2;
2860:                        }
2861:                    }
2862:                }
2863:
2864:                void readInts(int[] v, int off, int len) throws IOException {
2865:                    int stop, endoff = off + len;
2866:                    while (off < endoff) {
2867:                        if (!blkmode) {
2868:                            int span = Math.min(endoff - off,
2869:                                    MAX_BLOCK_SIZE >> 2);
2870:                            in.readFully(buf, 0, span << 2);
2871:                            stop = off + span;
2872:                            pos = 0;
2873:                        } else if (end - pos < 4) {
2874:                            v[off++] = din.readInt();
2875:                            continue;
2876:                        } else {
2877:                            stop = Math.min(endoff, off + ((end - pos) >> 2));
2878:                        }
2879:
2880:                        while (off < stop) {
2881:                            v[off++] = Bits.getInt(buf, pos);
2882:                            pos += 4;
2883:                        }
2884:                    }
2885:                }
2886:
2887:                void readFloats(float[] v, int off, int len) throws IOException {
2888:                    int span, endoff = off + len;
2889:                    while (off < endoff) {
2890:                        if (!blkmode) {
2891:                            span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 2);
2892:                            in.readFully(buf, 0, span << 2);
2893:                            pos = 0;
2894:                        } else if (end - pos < 4) {
2895:                            v[off++] = din.readFloat();
2896:                            continue;
2897:                        } else {
2898:                            span = Math.min(endoff - off, ((end - pos) >> 2));
2899:                        }
2900:
2901:                        bytesToFloats(buf, pos, v, off, span);
2902:                        off += span;
2903:                        pos += span << 2;
2904:                    }
2905:                }
2906:
2907:                void readLongs(long[] v, int off, int len) throws IOException {
2908:                    int stop, endoff = off + len;
2909:                    while (off < endoff) {
2910:                        if (!blkmode) {
2911:                            int span = Math.min(endoff - off,
2912:                                    MAX_BLOCK_SIZE >> 3);
2913:                            in.readFully(buf, 0, span << 3);
2914:                            stop = off + span;
2915:                            pos = 0;
2916:                        } else if (end - pos < 8) {
2917:                            v[off++] = din.readLong();
2918:                            continue;
2919:                        } else {
2920:                            stop = Math.min(endoff, off + ((end - pos) >> 3));
2921:                        }
2922:
2923:                        while (off < stop) {
2924:                            v[off++] = Bits.getLong(buf, pos);
2925:                            pos += 8;
2926:                        }
2927:                    }
2928:                }
2929:
2930:                void readDoubles(double[] v, int off, int len)
2931:                        throws IOException {
2932:                    int span, endoff = off + len;
2933:                    while (off < endoff) {
2934:                        if (!blkmode) {
2935:                            span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 3);
2936:                            in.readFully(buf, 0, span << 3);
2937:                            pos = 0;
2938:                        } else if (end - pos < 8) {
2939:                            v[off++] = din.readDouble();
2940:                            continue;
2941:                        } else {
2942:                            span = Math.min(endoff - off, ((end - pos) >> 3));
2943:                        }
2944:
2945:                        bytesToDoubles(buf, pos, v, off, span);
2946:                        off += span;
2947:                        pos += span << 3;
2948:                    }
2949:                }
2950:
2951:                /**
2952:                 * Reads in string written in "long" UTF format.  "Long" UTF format is
2953:                 * identical to standard UTF, except that it uses an 8 byte header
2954:                 * (instead of the standard 2 bytes) to convey the UTF encoding length.
2955:                 */
2956:                String readLongUTF() throws IOException {
2957:                    return readUTFBody(readLong());
2958:                }
2959:
2960:                /**
2961:                 * Reads in the "body" (i.e., the UTF representation minus the 2-byte
2962:                 * or 8-byte length header) of a UTF encoding, which occupies the next
2963:                 * utflen bytes.
2964:                 */
2965:                private String readUTFBody(long utflen) throws IOException {
2966:                    StringBuffer sbuf = new StringBuffer();
2967:                    if (!blkmode) {
2968:                        end = pos = 0;
2969:                    }
2970:
2971:                    while (utflen > 0) {
2972:                        int avail = end - pos;
2973:                        if (avail >= 3 || (long) avail == utflen) {
2974:                            utflen -= readUTFSpan(sbuf, utflen);
2975:                        } else {
2976:                            if (blkmode) {
2977:                                // near block boundary, read one byte at a time
2978:                                utflen -= readUTFChar(sbuf, utflen);
2979:                            } else {
2980:                                // shift and refill buffer manually
2981:                                if (avail > 0) {
2982:                                    System.arraycopy(buf, pos, buf, 0, avail);
2983:                                }
2984:                                pos = 0;
2985:                                end = (int) Math.min(MAX_BLOCK_SIZE, utflen);
2986:                                in.readFully(buf, avail, end - avail);
2987:                            }
2988:                        }
2989:                    }
2990:
2991:                    return sbuf.toString();
2992:                }
2993:
2994:                /**
2995:                 * Reads span of UTF-encoded characters out of internal buffer
2996:                 * (starting at offset pos and ending at or before offset end),
2997:                 * consuming no more than utflen bytes.  Appends read characters to
2998:                 * sbuf.  Returns the number of bytes consumed.
2999:                 */
3000:                private long readUTFSpan(StringBuffer sbuf, long utflen)
3001:                        throws IOException {
3002:                    int cpos = 0;
3003:                    int start = pos;
3004:                    int avail = Math.min(end - pos, CHAR_BUF_SIZE);
3005:                    // stop short of last char unless all of utf bytes in buffer
3006:                    int stop = pos
3007:                            + ((utflen > avail) ? avail - 2 : (int) utflen);
3008:                    boolean outOfBounds = false;
3009:
3010:                    try {
3011:                        while (pos < stop) {
3012:                            int b1, b2, b3;
3013:                            b1 = buf[pos++] & 0xFF;
3014:                            switch (b1 >> 4) {
3015:                            case 0:
3016:                            case 1:
3017:                            case 2:
3018:                            case 3:
3019:                            case 4:
3020:                            case 5:
3021:                            case 6:
3022:                            case 7: // 1 byte format: 0xxxxxxx
3023:                                cbuf[cpos++] = (char) b1;
3024:                                break;
3025:
3026:                            case 12:
3027:                            case 13: // 2 byte format: 110xxxxx 10xxxxxx
3028:                                b2 = buf[pos++];
3029:                                if ((b2 & 0xC0) != 0x80) {
3030:                                    throw new UTFDataFormatException();
3031:                                }
3032:                                cbuf[cpos++] = (char) (((b1 & 0x1F) << 6) | ((b2 & 0x3F) << 0));
3033:                                break;
3034:
3035:                            case 14: // 3 byte format: 1110xxxx 10xxxxxx 10xxxxxx
3036:                                b3 = buf[pos + 1];
3037:                                b2 = buf[pos + 0];
3038:                                pos += 2;
3039:                                if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80) {
3040:                                    throw new UTFDataFormatException();
3041:                                }
3042:                                cbuf[cpos++] = (char) (((b1 & 0x0F) << 12)
3043:                                        | ((b2 & 0x3F) << 6) | ((b3 & 0x3F) << 0));
3044:                                break;
3045:
3046:                            default: // 10xx xxxx, 1111 xxxx
3047:                                throw new UTFDataFormatException();
3048:                            }
3049:                        }
3050:                    } catch (ArrayIndexOutOfBoundsException ex) {
3051:                        outOfBounds = true;
3052:                    } finally {
3053:                        if (outOfBounds || (pos - start) > utflen) {
3054:                            /*
3055:                             * Fix for 4450867: if a malformed utf char causes the
3056:                             * conversion loop to scan past the expected end of the utf
3057:                             * string, only consume the expected number of utf bytes.
3058:                             */
3059:                            pos = start + (int) utflen;
3060:                            throw new UTFDataFormatException();
3061:                        }
3062:                    }
3063:
3064:                    sbuf.append(cbuf, 0, cpos);
3065:                    return pos - start;
3066:                }
3067:
3068:                /**
3069:                 * Reads in single UTF-encoded character one byte at a time, appends
3070:                 * the character to sbuf, and returns the number of bytes consumed.
3071:                 * This method is used when reading in UTF strings written in block
3072:                 * data mode to handle UTF-encoded characters which (potentially)
3073:                 * straddle block-data boundaries.
3074:                 */
3075:                private int readUTFChar(StringBuffer sbuf, long utflen)
3076:                        throws IOException {
3077:                    int b1, b2, b3;
3078:                    b1 = readByte() & 0xFF;
3079:                    switch (b1 >> 4) {
3080:                    case 0:
3081:                    case 1:
3082:                    case 2:
3083:                    case 3:
3084:                    case 4:
3085:                    case 5:
3086:                    case 6:
3087:                    case 7: // 1 byte format: 0xxxxxxx
3088:                        sbuf.append((char) b1);
3089:                        return 1;
3090:
3091:                    case 12:
3092:                    case 13: // 2 byte format: 110xxxxx 10xxxxxx
3093:                        if (utflen < 2) {
3094:                            throw new UTFDataFormatException();
3095:                        }
3096:                        b2 = readByte();
3097:                        if ((b2 & 0xC0) != 0x80) {
3098:                            throw new UTFDataFormatException();
3099:                        }
3100:                        sbuf
3101:                                .append((char) (((b1 & 0x1F) << 6) | ((b2 & 0x3F) << 0)));
3102:                        return 2;
3103:
3104:                    case 14: // 3 byte format: 1110xxxx 10xxxxxx 10xxxxxx
3105:                        if (utflen < 3) {
3106:                            if (utflen == 2) {
3107:                                readByte(); // consume remaining byte
3108:                            }
3109:                            throw new UTFDataFormatException();
3110:                        }
3111:                        b2 = readByte();
3112:                        b3 = readByte();
3113:                        if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80) {
3114:                            throw new UTFDataFormatException();
3115:                        }
3116:                        sbuf.append((char) (((b1 & 0x0F) << 12)
3117:                                | ((b2 & 0x3F) << 6) | ((b3 & 0x3F) << 0)));
3118:                        return 3;
3119:
3120:                    default: // 10xx xxxx, 1111 xxxx
3121:                        throw new UTFDataFormatException();
3122:                    }
3123:                }
3124:            }
3125:
3126:            /**
3127:             * Unsynchronized table which tracks wire handle to object mappings, as
3128:             * well as ClassNotFoundExceptions associated with deserialized objects.
3129:             * This class implements an exception-propagation algorithm for
3130:             * determining which objects should have ClassNotFoundExceptions associated
3131:             * with them, taking into account cycles and discontinuities (e.g., skipped
3132:             * fields) in the object graph.
3133:             * 
3134:             * <p>General use of the table is as follows: during deserialization, a
3135:             * given object is first assigned a handle by calling the assign method.
3136:             * This method leaves the assigned handle in an "open" state, wherein
3137:             * dependencies on the exception status of other handles can be registered
3138:             * by calling the markDependency method, or an exception can be directly
3139:             * associated with the handle by calling markException.  When a handle is
3140:             * tagged with an exception, the HandleTable assumes responsibility for
3141:             * propagating the exception to any other objects which depend
3142:             * (transitively) on the exception-tagged object.
3143:             * 
3144:             * <p>Once all exception information/dependencies for the handle have been
3145:             * registered, the handle should be "closed" by calling the finish method
3146:             * on it.  The act of finishing a handle allows the exception propagation
3147:             * algorithm to aggressively prune dependency links, lessening the
3148:             * performance/memory impact of exception tracking.
3149:             * 
3150:             * <p>Note that the exception propagation algorithm used depends on handles
3151:             * being assigned/finished in LIFO order; however, for simplicity as well
3152:             * as memory conservation, it does not enforce this constraint.
3153:             */
3154:            // REMIND: add full description of exception propagation algorithm?
3155:            private static class HandleTable {
3156:
3157:                /* status codes indicating whether object has associated exception */
3158:                private static final byte STATUS_OK = 1;
3159:                private static final byte STATUS_UNKNOWN = 2;
3160:                private static final byte STATUS_EXCEPTION = 3;
3161:
3162:                /** array mapping handle -> object status */
3163:                byte[] status;
3164:                /** array mapping handle -> object/exception (depending on status) */
3165:                Object[] entries;
3166:                /** array mapping handle -> list of dependent handles (if any) */
3167:                HandleList[] deps;
3168:                /** lowest unresolved dependency */
3169:                int lowDep = -1;
3170:                /** number of handles in table */
3171:                int size = 0;
3172:
3173:                /**
3174:                 * Creates handle table with the given initial capacity.
3175:                 */
3176:                HandleTable(int initialCapacity) {
3177:                    status = new byte[initialCapacity];
3178:                    entries = new Object[initialCapacity];
3179:                    deps = new HandleList[initialCapacity];
3180:                }
3181:
3182:                /**
3183:                 * Assigns next available handle to given object, and returns assigned
3184:                 * handle.  Once object has been completely deserialized (and all
3185:                 * dependencies on other objects identified), the handle should be
3186:                 * "closed" by passing it to finish().
3187:                 */
3188:                int assign(Object obj) {
3189:                    if (size >= entries.length) {
3190:                        grow();
3191:                    }
3192:                    status[size] = STATUS_UNKNOWN;
3193:                    entries[size] = obj;
3194:                    return size++;
3195:                }
3196:
3197:                /**
3198:                 * Registers a dependency (in exception status) of one handle on
3199:                 * another.  The dependent handle must be "open" (i.e., assigned, but
3200:                 * not finished yet).  No action is taken if either dependent or target
3201:                 * handle is NULL_HANDLE.
3202:                 */
3203:                void markDependency(int dependent, int target) {
3204:                    if (dependent == NULL_HANDLE || target == NULL_HANDLE) {
3205:                        return;
3206:                    }
3207:                    switch (status[dependent]) {
3208:
3209:                    case STATUS_UNKNOWN:
3210:                        switch (status[target]) {
3211:                        case STATUS_OK:
3212:                            // ignore dependencies on objs with no exception
3213:                            break;
3214:
3215:                        case STATUS_EXCEPTION:
3216:                            // eagerly propagate exception
3217:                            markException(dependent,
3218:                                    (ClassNotFoundException) entries[target]);
3219:                            break;
3220:
3221:                        case STATUS_UNKNOWN:
3222:                            // add to dependency list of target
3223:                            if (deps[target] == null) {
3224:                                deps[target] = new HandleList();
3225:                            }
3226:                            deps[target].add(dependent);
3227:
3228:                            // remember lowest unresolved target seen
3229:                            if (lowDep < 0 || lowDep > target) {
3230:                                lowDep = target;
3231:                            }
3232:                            break;
3233:
3234:                        default:
3235:                            throw new InternalError();
3236:                        }
3237:                        break;
3238:
3239:                    case STATUS_EXCEPTION:
3240:                        break;
3241:
3242:                    default:
3243:                        throw new InternalError();
3244:                    }
3245:                }
3246:
3247:                /**
3248:                 * Associates a ClassNotFoundException (if one not already associated)
3249:                 * with the currently active handle and propagates it to other
3250:                 * referencing objects as appropriate.  The specified handle must be
3251:                 * "open" (i.e., assigned, but not finished yet).
3252:                 */
3253:                void markException(int handle, ClassNotFoundException ex) {
3254:                    switch (status[handle]) {
3255:                    case STATUS_UNKNOWN:
3256:                        status[handle] = STATUS_EXCEPTION;
3257:                        entries[handle] = ex;
3258:
3259:                        // propagate exception to dependents
3260:                        HandleList dlist = deps[handle];
3261:                        if (dlist != null) {
3262:                            int ndeps = dlist.size();
3263:                            for (int i = 0; i < ndeps; i++) {
3264:                                markException(dlist.get(i), ex);
3265:                            }
3266:                            deps[handle] = null;
3267:                        }
3268:                        break;
3269:
3270:                    case STATUS_EXCEPTION:
3271:                        break;
3272:
3273:                    default:
3274:                        throw new InternalError();
3275:                    }
3276:                }
3277:
3278:                /**
3279:                 * Marks given handle as finished, meaning that no new dependencies
3280:                 * will be marked for handle.  Calls to the assign and finish methods
3281:                 * must occur in LIFO order.
3282:                 */
3283:                void finish(int handle) {
3284:                    int end;
3285:                    if (lowDep < 0) {
3286:                        // no pending unknowns, only resolve current handle
3287:                        end = handle + 1;
3288:                    } else if (lowDep >= handle) {
3289:                        // pending unknowns now clearable, resolve all upward handles
3290:                        end = size;
3291:                        lowDep = -1;
3292:                    } else {
3293:                        // unresolved backrefs present, can't resolve anything yet
3294:                        return;
3295:                    }
3296:
3297:                    // change STATUS_UNKNOWN -> STATUS_OK in selected span of handles
3298:                    for (int i = handle; i < end; i++) {
3299:                        switch (status[i]) {
3300:                        case STATUS_UNKNOWN:
3301:                            status[i] = STATUS_OK;
3302:                            deps[i] = null;
3303:                            break;
3304:
3305:                        case STATUS_OK:
3306:                        case STATUS_EXCEPTION:
3307:                            break;
3308:
3309:                        default:
3310:                            throw new InternalError();
3311:                        }
3312:                    }
3313:                }
3314:
3315:                /**
3316:                 * Assigns a new object to the given handle.  The object previously
3317:                 * associated with the handle is forgotten.  This method has no effect
3318:                 * if the given handle already has an exception associated with it.
3319:                 * This method may be called at any time after the handle is assigned.
3320:                 */
3321:                void setObject(int handle, Object obj) {
3322:                    switch (status[handle]) {
3323:                    case STATUS_UNKNOWN:
3324:                    case STATUS_OK:
3325:                        entries[handle] = obj;
3326:                        break;
3327:
3328:                    case STATUS_EXCEPTION:
3329:                        break;
3330:
3331:                    default:
3332:                        throw new InternalError();
3333:                    }
3334:                }
3335:
3336:                /**
3337:                 * Looks up and returns object associated with the given handle.
3338:                 * Returns null if the given handle is NULL_HANDLE, or if it has an
3339:                 * associated ClassNotFoundException.
3340:                 */
3341:                Object lookupObject(int handle) {
3342:                    return (handle != NULL_HANDLE && status[handle] != STATUS_EXCEPTION) ? entries[handle]
3343:                            : null;
3344:                }
3345:
3346:                /**
3347:                 * Looks up and returns ClassNotFoundException associated with the
3348:                 * given handle.  Returns null if the given handle is NULL_HANDLE, or
3349:                 * if there is no ClassNotFoundException associated with the handle.
3350:                 */
3351:                ClassNotFoundException lookupException(int handle) {
3352:                    return (handle != NULL_HANDLE && status[handle] == STATUS_EXCEPTION) ? (ClassNotFoundException) entries[handle]
3353:                            : null;
3354:                }
3355:
3356:                /**
3357:                 * Resets table to its initial state.
3358:                 */
3359:                void clear() {
3360:                    Arrays.fill(status, 0, size, (byte) 0);
3361:                    Arrays.fill(entries, 0, size, null);
3362:                    Arrays.fill(deps, 0, size, null);
3363:                    lowDep = -1;
3364:                    size = 0;
3365:                }
3366:
3367:                /**
3368:                 * Returns number of handles registered in table.
3369:                 */
3370:                int size() {
3371:                    return size;
3372:                }
3373:
3374:                /**
3375:                 * Expands capacity of internal arrays.
3376:                 */
3377:                private void grow() {
3378:                    int newCapacity = (entries.length << 1) + 1;
3379:
3380:                    byte[] newStatus = new byte[newCapacity];
3381:                    Object[] newEntries = new Object[newCapacity];
3382:                    HandleList[] newDeps = new HandleList[newCapacity];
3383:
3384:                    System.arraycopy(status, 0, newStatus, 0, size);
3385:                    System.arraycopy(entries, 0, newEntries, 0, size);
3386:                    System.arraycopy(deps, 0, newDeps, 0, size);
3387:
3388:                    status = newStatus;
3389:                    entries = newEntries;
3390:                    deps = newDeps;
3391:                }
3392:
3393:                /**
3394:                 * Simple growable list of (integer) handles.
3395:                 */
3396:                private static class HandleList {
3397:                    private int[] list = new int[4];
3398:                    private int size = 0;
3399:
3400:                    public HandleList() {
3401:                    }
3402:
3403:                    public void add(int handle) {
3404:                        if (size >= list.length) {
3405:                            int[] newList = new int[list.length << 1];
3406:                            System.arraycopy(list, 0, newList, 0, list.length);
3407:                            list = newList;
3408:                        }
3409:                        list[size++] = handle;
3410:                    }
3411:
3412:                    public int get(int index) {
3413:                        if (index >= size) {
3414:                            throw new ArrayIndexOutOfBoundsException();
3415:                        }
3416:                        return list[index];
3417:                    }
3418:
3419:                    public int size() {
3420:                        return size;
3421:                    }
3422:                }
3423:            }
3424:
3425:            // COUGAAR
3426:            protected Object newInstanceFromDesc(ObjectStreamClass desc)
3427:                    throws InstantiationException, IllegalAccessException,
3428:                    java.lang.reflect.InvocationTargetException {
3429:                return real_newInstanceFromDesc(desc);
3430:            }
3431:
3432:            // COUGAAR
3433:            protected final Object real_newInstanceFromDesc(
3434:                    ObjectStreamClass desc) throws InstantiationException,
3435:                    IllegalAccessException,
3436:                    java.lang.reflect.InvocationTargetException {
3437:                return desc.newInstance();
3438:            }
3439:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.