/** Create a named field with the specified type. */ ObjectStreamField(String n, Class<?> clazz) { name = n; this.clazz = clazz; // Compute the typecode for easy switching if (clazz.isPrimitive()) { if (clazz == Integer.TYPE) { type = 'I'; } else if (clazz == Byte.TYPE) { type = 'B'; } else if (clazz == Long.TYPE) { type = 'J'; } else if (clazz == Float.TYPE) { type = 'F'; } else if (clazz == Double.TYPE) { type = 'D'; } else if (clazz == Short.TYPE) { type = 'S'; } else if (clazz == Character.TYPE) { type = 'C'; } else if (clazz == Boolean.TYPE) { type = 'Z'; } } else if (clazz.isArray()) { type = '['; typeString = ObjectStreamClass.getSignature(clazz); } else { type = 'L'; typeString = ObjectStreamClass.getSignature(clazz); } if (typeString != null) signature = typeString; else signature = String.valueOf(type); }
public static void writeObject(Object obj, SerializationInfo info) { try { boolean replaced = false; Class cl = obj.getClass(); ObjectStreamClass desc; for (; ; ) { Class repCl; desc = ObjectStreamClass.lookup(cl, true); if (!desc.hasWriteReplaceMethod() || (obj = desc.invokeWriteReplace(obj)) == null || (repCl = obj.getClass()) == cl) { break; } cl = repCl; replaced = true; } if (replaced) { info.AddValue("obj", obj); info.SetType(ikvm.runtime.Util.getInstanceTypeFromClass(ReplaceProxy.class)); } else { new InteropObjectOutputStream(info, obj, cl, desc); } } catch (IOException x) { ikvm.runtime.Util.throwException(new SerializationException(x.getMessage(), x)); } }
static void print(ObjectStreamClass desc) { System.out.println("Class name : " + desc.getName()); System.out.println("SerialVersionUID: " + desc.getSerialVersionUID()); System.out.println("ObjectStreamFields"); ObjectStreamField[] fields = desc.getFields(); int numPrim = 0; int numObj = 0; for (int i = 0; i < fields.length; i++) { ObjectStreamField f = fields[i]; String fieldName = "<fieldName unknown>"; try { fieldName = f.getName(); } catch (NoSuchMethodError e) { // ignore. ObjectStreamField.getName did not exist in JDK 1.1 } if (f.isPrimitive()) { numPrim++; System.out.println("" + i + ". " + f.getType().getName() + " " + fieldName); } else { numObj++; String ts = "<unknown>"; try { ts = f.getTypeString(); } catch (NoSuchMethodError e) { // ignore. ObjectStreamField.getTypeString did not exist in JDK 1.1 ts = "<field type unknown>"; } System.out.println("" + i + ". " + ts + " " + fieldName); } } System.out.println("# primitive fields:" + numPrim + " # object ref fields:" + numObj); }
@Override protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { ObjectStreamClass classDesc = super.readClassDescriptor(); String className = classDesc.getName(); return renamedClasses.containsKey(className) ? ObjectStreamClass.lookup(renamedClasses.get(className)) : classDesc; }
private void writeOrdinaryObject(Object obj, ObjectStreamClass desc) throws IOException { desc.checkSerialize(); writeObject(desc); if (desc.isExternalizable() && !desc.isProxy()) { writeExternalData((Externalizable) obj); } else { writeSerialData(obj, desc); } }
private void writeProxyDesc(ObjectStreamClass desc) throws IOException { writeByte(TC_PROXYCLASSDESC); Class cl = desc.forClass(); Class[] ifaces = cl.getInterfaces(); writeInt(ifaces.length); for (int i = 0; i < ifaces.length; i++) { writeObject(ifaces[i]); } writeObject(desc.getSuperDesc()); }
private void defaultWriteFields(Object obj, ObjectStreamClass desc) throws IOException { desc.checkDefaultSerialize(); byte[] primVals = new byte[desc.getPrimDataSize()]; desc.getPrimFieldValues(obj, primVals); write(primVals); Object[] objVals = new Object[desc.getNumObjFields()]; desc.getObjFieldValues(obj, objVals); for (int i = 0; i < objVals.length; i++) { writeObject(objVals[i]); } }
/** * Returns offset of field with given name and type. A specified type of null matches all types, * Object.class matches all non-primitive types, and any other non-null type matches assignable * types only. Throws IllegalArgumentException if no matching field found. */ private int getFieldOffset(String name, Class type) { ObjectStreamField field = desc.getField(name, type); if (field == null) { throw new IllegalArgumentException("no such field " + name + " with type " + type); } return field.getOffset(); }
// deprecated in ObjectOutputStream.PutField public void write(ObjectOutput out) throws IOException { /* * Applications should *not* use this method to write PutField * data, as it will lead to stream corruption if the PutField * object writes any primitive data (since block data mode is not * unset/set properly, as is done in OOS.writeFields()). This * broken implementation is being retained solely for behavioral * compatibility, in order to support applications which use * OOS.PutField.write() for writing only non-primitive data. * * Serialization of unshared objects is not implemented here since * it is not necessary for backwards compatibility; also, unshared * semantics may not be supported by the given ObjectOutput * instance. Applications which write unshared objects using the * PutField API must use OOS.writeFields(). */ if (InteropObjectOutputStream.this != out) { throw new IllegalArgumentException("wrong stream"); } out.write(primVals, 0, primVals.length); ObjectStreamField[] fields = desc.getFields(false); int numPrimFields = fields.length - objVals.length; // REMIND: warn if numPrimFields > 0? for (int i = 0; i < objVals.length; i++) { if (fields[numPrimFields + i].isUnshared()) { throw new IOException("cannot write unshared object"); } out.writeObject(objVals[i]); } }
/** Use the given ClassLoader rather than using the system class */ protected Class resolveClass(ObjectStreamClass classDesc) throws IOException, ClassNotFoundException { String cname = classDesc.getName(); if (cname.startsWith("[")) { // An array Class component; // component class int dcount; // dimension for (dcount = 1; cname.charAt(dcount) == '['; dcount++) ; if (cname.charAt(dcount) == 'L') { component = loader.loadClass(cname.substring(dcount + 1, cname.length() - 1)); } else { if (cname.length() != dcount + 1) { throw new ClassNotFoundException(cname); // malformed } component = primitiveType(cname.charAt(dcount)); } int dim[] = new int[dcount]; for (int i = 0; i < dcount; i++) { dim[i] = 1; } return Array.newInstance(component, dim).getClass(); } else { return loader.loadClass(cname); } }
/* */ public String[] bases(String paramString) /* */ { /* */ try /* */ { /* 163 */ if (this.vhandler == null) { /* 164 */ this.vhandler = ValueHandlerImpl.getInstance(false); /* */ } /* */ /* 167 */ Stack localStack = new Stack(); /* 168 */ Class localClass = ObjectStreamClass.lookup(this.vhandler.getClassFromType(paramString)) .forClass() .getSuperclass(); /* */ /* 170 */ while (!localClass.equals(Object.class)) { /* 171 */ localStack.push(this.vhandler.createForAnyType(localClass)); /* 172 */ localClass = localClass.getSuperclass(); /* */ } /* */ /* 175 */ String[] arrayOfString = new String[localStack.size()]; /* 176 */ for (int i = arrayOfString.length - 1; i >= 0; i++) { /* 177 */ arrayOfString[i] = ((String) localStack.pop()); /* */ } /* 179 */ return arrayOfString; /* */ } catch (Throwable localThrowable) { /* 181 */ throw this.wrapper.missingLocalValueImpl( CompletionStatus.COMPLETED_MAYBE, localThrowable); /* */ } /* */ }
/** * Computes the serial version UID value for the given class. The code is taken from {@link * ObjectStreamClass#computeDefaultSUID(Class)}. * * @param cls A class. * @return A serial version UID. * @throws IOException If failed. */ static long computeSerialVersionUid(Class cls) throws IOException { if (Serializable.class.isAssignableFrom(cls) && !Enum.class.isAssignableFrom(cls)) { return ObjectStreamClass.lookup(cls).getSerialVersionUID(); } MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new IOException("Failed to get digest for SHA.", e); } md.update(cls.getName().getBytes(UTF_8)); for (Field f : getFieldsForSerialization(cls)) { md.update(f.getName().getBytes(UTF_8)); md.update(f.getType().getName().getBytes(UTF_8)); } byte[] hashBytes = md.digest(); long hash = 0; // Composes a single-long hash from the byte[] hash. for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) hash = (hash << 8) | (hashBytes[i] & 0xFF); return hash; }
/** * Compare the types of two class descriptors. The match if they have the same primitive types. or * if they are both objects and the object types match. */ public boolean typeEquals(ObjectStreamField other) { if (other == null || type != other.type) return false; /* Return true if the primitive types matched */ if (typeString == null && other.typeString == null) return true; return ObjectStreamClass.compareClassNames(typeString, other.typeString, '/'); }
private static Map<String, Long> getMessageSVUID(Type messageType) throws SJIOException, ClassNotFoundException // SJCompilerUtils has a simpler version of this routine. { HashMap<String, Long> ours = new HashMap<String, Long>(); if (messageType instanceof SJSessionType) // Should come before ordinary class cases? (But SJSessionType shouldn't be a // class type). { ours.putAll(getClassSVUIDs((SJSessionType) messageType)); } else if (messageType.isPrimitive()) { // No SVUID needed for primitive types. } else if (messageType.isClass()) // Duplicated from above. { String className = messageType.toClass().fullName(); Class<?> c = Class.forName(className); if (c.isInterface()) { // Interfaces don't have SVUIDs (so what should we do here?). // This encourages use of // abstract classes rather than interfaces for message types? } else { ObjectStreamClass osc = ObjectStreamClass.lookup(c); if (osc == null) { throw new SJIOException("Class not serializable: " + c); } ours.put( className, osc .getSerialVersionUID()); // Not possible to find a different SVUID for the same // (name) class here? // SVUIDs could be recorded in the // session type objects. // Put currently problems working // with these values at compilation time if the class // binary is not available a priori (SVUID value not built // yet?). } } else if (messageType.isArray()) { throw new SJIOException("Array types not done yet: " + messageType); } return ours; }
/** Writes buffered primitive data and object fields to stream. */ void writeFields() throws IOException { InteropObjectOutputStream.this.write(primVals, 0, primVals.length); ObjectStreamField[] fields = desc.getFields(false); int numPrimFields = fields.length - objVals.length; for (int i = 0; i < objVals.length; i++) { writeObject(objVals[i]); } }
@Override public Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { ClassLoader currentTccl = null; try { currentTccl = Thread.currentThread().getContextClassLoader(); return currentTccl.loadClass(desc.getName()); } catch (Exception e) { } return super.resolveClass(desc); }
protected void annotateClass(Class cl) throws IOException { super.annotateClass(cl); if (verbose) { ObjectStreamClass desc = ObjectStreamClass.lookup(cl); System.out.println("******************"); System.out.println("annotateClass(" + cl.getName() + ")"); System.out.println("******************"); SerialBox.print(desc); } }
class TestObjectOutputStream extends ObjectOutputStream { static ObjectStreamClass fooDesc = ObjectStreamClass.lookup(Foo.class); static ObjectStreamClass integerDesc = ObjectStreamClass.lookup(Integer.class); TestObjectOutputStream(OutputStream out) throws IOException { super(out); } protected void writeClassDescriptor(ObjectStreamClass desc) throws IOException { if (desc == fooDesc) { super.writeClassDescriptor(integerDesc); } else if (desc == integerDesc) { super.writeClassDescriptor(fooDesc); } else { super.writeClassDescriptor(desc); } } }
private InteropObjectOutputStream( SerializationInfo info, Object obj, Class cl, ObjectStreamClass desc) throws IOException { dos = new ObjectDataOutputStream(info); if (obj instanceof ObjectStreamClass) { ObjectStreamClass osc = (ObjectStreamClass) obj; if (osc.isProxy()) { writeProxyDesc(osc); } else { writeNonProxyDesc(osc); } } else if (obj instanceof Serializable) { if (desc.isDynamicClass()) { info.SetType(ikvm.runtime.Util.getInstanceTypeFromClass(DynamicProxy.class)); } writeOrdinaryObject(obj, desc); } else { throw new NotSerializableException(cl.getName()); } dos.close(); }
private void writeSerialData(Object obj, ObjectStreamClass desc) throws IOException { ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout(); for (int i = 0; i < slots.length; i++) { ObjectStreamClass slotDesc = slots[i].desc; if (slotDesc.hasWriteObjectMethod()) { Object oldObj = curObj; ObjectStreamClass oldDesc = curDesc; PutFieldImpl oldPut = curPut; curObj = obj; curDesc = slotDesc; curPut = null; slotDesc.invokeWriteObject(obj, this); dos.writeMarker(); curObj = oldObj; curDesc = oldDesc; curPut = oldPut; } else { defaultWriteFields(obj, slotDesc); } } }
/* */ public FullValueDescription meta(String paramString) /* */ { /* */ try { /* 117 */ FullValueDescription localFullValueDescription = (FullValueDescription) fvds.get(paramString); /* */ /* 119 */ if (localFullValueDescription == null) /* */ { /* 122 */ if (this.vhandler == null) { /* 123 */ this.vhandler = ValueHandlerImpl.getInstance(false); /* */ } /* */ try /* */ { /* 127 */ localFullValueDescription = ValueUtility.translate( _orb(), ObjectStreamClass.lookup(this.vhandler.getAnyClassFromType(paramString)), this.vhandler); /* */ } /* */ catch (Throwable localThrowable2) { /* 130 */ if (this.orb == null) /* 131 */ this.orb = ORB.init(); /* 132 */ localFullValueDescription = ValueUtility.translate( this.orb, ObjectStreamClass.lookup(this.vhandler.getAnyClassFromType(paramString)), this.vhandler); /* */ } /* */ /* 136 */ if (localFullValueDescription != null) /* 137 */ fvds.put(paramString, localFullValueDescription); /* */ else { /* 139 */ throw this.wrapper.missingLocalValueImpl(CompletionStatus.COMPLETED_MAYBE); /* */ } /* */ } /* */ /* 143 */ return localFullValueDescription; /* */ } catch (Throwable localThrowable1) { /* 145 */ throw this.wrapper.incompatibleValueImpl( CompletionStatus.COMPLETED_MAYBE, localThrowable1); /* */ } /* */ }
/** * Override coverts old class names into new class names to preserve compatibility with * pre-Apache namespaces. */ @Override protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { ObjectStreamClass read = super.readClassDescriptor(); if (read.getName().startsWith("com.fs.pxe.")) { return ObjectStreamClass.lookup( Class.forName(read.getName().replace("com.fs.pxe.", "org.apache.ode."))); } if (read.getName().startsWith("com.fs.utils.")) { return ObjectStreamClass.lookup( Class.forName(read.getName().replace("com.fs.utils.", "org.apache.ode.utils."))); } return read; }
protected Class resolveClass(ObjectStreamClass v) throws ClassNotFoundException, IOException { if (verbose) { System.out.println("*******************************BEGIN"); System.out.println("**Stream ObjectStreamClass Descriptor"); SerialBox.print(v); } Class cl = super.resolveClass(v); if (verbose) { ObjectStreamClass localDesc = ObjectStreamClass.lookup(cl); if (localDesc != null) { System.out.println("**Local JVM ObjectStreamClass Descriptor"); SerialBox.print(localDesc); } System.out.println("*******************************END "); } return cl; }
public static void main(String args[]) throws Exception { File f = new File("tmp.ser"); if (args[0].compareTo("-s") == 0) { FileOutputStream of = new FileOutputStream(f); ObjectOutputStream oos = new ObjectOutputStream(of); Class cl = Class.forName(args[1]); oos.writeObject(cl); if (ObjectStreamClass.lookup(cl) != null) oos.writeObject(cl.newInstance()); oos.close(); System.out.println("Serialized Class " + cl.getName()); } else if (args[0].compareTo("-de") == 0) { FileInputStream inf = new FileInputStream(f); ObjectInputStream ois = new ObjectInputStream(inf); Class cl = null; try { cl = (Class) ois.readObject(); throw new Error("Expected InvalidClassException to be thrown"); } catch (InvalidClassException e) { System.out.println("Caught expected exception DeSerializing class " + e.getMessage()); } ois.close(); } else if (args[0].compareTo("-doe") == 0) { FileInputStream inf = new FileInputStream(f); ObjectInputStream ois = new ObjectInputStream(inf); Class cl = null; cl = (Class) ois.readObject(); try { ois.readObject(); throw new Error("Expected InvalidClassException to be thrown"); } catch (InvalidClassException e) { System.out.println("Caught expected exception DeSerializing class " + e.getMessage()); } ois.close(); } else if (args[0].compareTo("-d") == 0) { FileInputStream inf = new FileInputStream(f); ObjectInputStream ois = new ObjectInputStream(inf); Class cl = (Class) ois.readObject(); try { ois.readObject(); } catch (EOFException e) { } ois.close(); System.out.println("DeSerialized Class " + cl.getName()); } }
/** {@collect.stats} Use the given ClassLoader rather than using the system class */ protected Class resolveClass(ObjectStreamClass objectstreamclass) throws IOException, ClassNotFoundException { String s = objectstreamclass.getName(); if (s.startsWith("[")) { int i; for (i = 1; s.charAt(i) == '['; i++) ; Class class1; if (s.charAt(i) == 'L') { class1 = loader.loadClass(s.substring(i + 1, s.length() - 1)); } else { if (s.length() != i + 1) throw new ClassNotFoundException(s); class1 = primitiveType(s.charAt(i)); } int ai[] = new int[i]; for (int j = 0; j < i; j++) ai[j] = 0; return Array.newInstance(class1, ai).getClass(); } else { return loader.loadClass(s); } }
/** {@inheritDoc} */ @Override protected void writeClassDescriptor(ObjectStreamClass desc) throws IOException { writeClass(desc.forClass()); }
protected Class resolveClass(ObjectStreamClass desc) throws ClassNotFoundException { return Class.forName(desc.getName(), false, RJavaClassLoader.getPrimaryLoader()); }
/** * Deserializes examplars stored in archives in getArchiveDirectory(). * * @throws RuntimeException if clazz cannot be serialized. This exception has an informative * message and wraps the originally thrown exception as root cause. * @see #getArchiveDirectory() */ public void deserializeArchivedVersions() throws RuntimeException { System.out.println("Deserializing archived instances in " + getArchiveDirectory() + "."); File archive = new File(getArchiveDirectory()); if (!archive.exists() || !archive.isDirectory()) { return; } String[] listing = archive.list(); for (String archiveName : listing) { if (!(archiveName.endsWith(".zip"))) { continue; } try { File file = new File(getArchiveDirectory(), archiveName); ZipFile zipFile = new ZipFile(file); ZipEntry entry = zipFile.getEntry("class_fields.ser"); InputStream inputStream = zipFile.getInputStream(entry); ObjectInputStream objectIn = new ObjectInputStream(inputStream); Map<String, List<String>> classFields = (Map<String, List<String>>) objectIn.readObject(); zipFile.close(); for (String className : classFields.keySet()) { // if (classFields.equals("HypotheticalGraph")) continue; List<String> fieldNames = classFields.get(className); Class<?> clazz = Class.forName(className); ObjectStreamClass streamClass = ObjectStreamClass.lookup(clazz); if (streamClass == null) { System.out.println(); } for (String fieldName : fieldNames) { assert streamClass != null; ObjectStreamField field = streamClass.getField(fieldName); if (field == null) { throw new RuntimeException( "Field '" + fieldName + "' was dropped from class '" + className + "' as a serializable field! Please " + "put it back!!!" + "\nIt used to be in " + className + " in this archive: " + archiveName + "."); } } } } catch (ClassNotFoundException e) { throw new RuntimeException( "Could not read class_fields.ser in archive + " + archiveName + " .", e); } catch (IOException e) { throw new RuntimeException("Problem reading archive" + archiveName + "; see cause.", e); } System.out.println("...Deserializing instances in " + archiveName + "..."); ZipEntry zipEntry = null; try { File file = new File(getArchiveDirectory(), archiveName); FileInputStream in = new FileInputStream(file); ZipInputStream zipinputstream = new ZipInputStream(in); while ((zipEntry = zipinputstream.getNextEntry()) != null) { if (!zipEntry.getName().endsWith(".ser")) { continue; } ObjectInputStream objectIn = new ObjectInputStream(zipinputstream); objectIn.readObject(); zipinputstream.closeEntry(); } zipinputstream.close(); } catch (ClassNotFoundException e) { throw new RuntimeException( "Could not read object zipped file " + zipEntry.getName() + " in archive " + archiveName + ". " + "Perhaps the class was renamed, moved to another package, or " + "removed. In any case, please put it back where it was.", e); } catch (IOException e) { throw new RuntimeException("Problem reading archive" + archiveName + "; see cause.", e); } } System.out.println("Finished deserializing archived instances."); }
protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { hookCalled = true; return ObjectStreamClass.lookup(Class.forName(readUTF())); }
protected void writeClassDescriptor(ObjectStreamClass desc) throws IOException { writeUTF(desc.getName()); hookCalled = true; }