/** * 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; }
/** java.io.ObjectStreamClass#getName() */ public void test_getName() { ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class); assertEquals( "getName returned incorrect name: " + osc.getName(), "org.apache.harmony.tests.java.io.ObjectStreamClassTest$DummyClass", osc.getName()); }
/** * 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; }
/** java.io.ObjectStreamClass#forClass() */ public void test_forClass() { // Need to test during serialization to be sure an instance is // returned ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class); assertEquals( "forClass returned an object: " + osc.forClass(), DummyClass.class, osc.forClass()); }
/** * Provides a special handling for renaming of serialized classes. * * <p>Often, as the time goes the serialized classes evolve. They can be moved to new packages, * renamed or changed (by a mistake) to not reflect the version of class stored in previous * sessions. * * <p>This method deals with some of this incompatibilites and provides the module owners a way * how to fix some of them. * * <p>When a class is read, the <link>Utilities.translate</link> is consulted to find out what * whether the name of the class is listed there and what new value is assigned to it. This allows * complete rename of the serialized class. For example: <code>org.netbeans.core.NbMainExplorer * </code> can be renamed to <code>org.netbeans.core.ui.NbExp</code> - of course supposing that * the new class is able to read the serialized fields of the old one. * * <p>Another useful feature of this method is the ability to supress wrong <code>serialVersionUID * </code>. This was causing us a lot of problems, because people were forgetting to specify the * <code>serialVersionUID</code> field in their sources and then it was hard to recover from it. * Right now we have a solution: Just use <link>Utilities.translate</link> framework to assing * your class <code>org.yourpackage.YourClass</code> the same name as it had e.g. <code> * org.yourpackage.YourClass</code>. This will be interpreted by this method as a hit to suppress * <code>serialVersionUID</code> and the <code>NbObjectInputStream</code> will ignore its value. * * <p>Please see <link>Utilities.translate</link> to learn how your module can provide list of * classes that changed name or want to suppress <code>serialVersionUID</code>. */ protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { ObjectStreamClass ose = super.readClassDescriptor(); String name = ose.getName(); String newN = Utilities.translate(name); if (name == newN) { // no translation return ose; } // otherwise reload the ObjectStreamClass to contain the local copy ClassLoader cl = getNBClassLoader(); Class clazz = Class.forName(newN, false, cl); ObjectStreamClass newOse = ObjectStreamClass.lookup(clazz); // #28021 - it is possible that lookup return null. In that case the conversion // table contains class which is not Serializable or Externalizable. if (newOse == null) { throw new java.io.NotSerializableException(newN); } return newOse; }
/** java.io.ObjectStreamClass#lookup(java.lang.Class) */ public void test_lookupLjava_lang_Class() { ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class); assertEquals( "lookup returned wrong class: " + osc.getName(), "org.apache.harmony.tests.java.io.ObjectStreamClassTest$DummyClass", osc.getName()); }
/** java.io.ObjectStreamClass#getFields() */ public void test_getFields() { ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class); ObjectStreamField[] osfArray = osc.getFields(); assertTrue( "Array of fields should be of length 2 but is instead of length: " + osfArray.length, osfArray.length == 2); }
@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; }
public static String getSerialVersionUID(final Class<?> cls) { final ObjectStreamClass osc = ObjectStreamClass.lookup(cls); if (osc == null) { return ""; } return String.valueOf(osc.getSerialVersionUID()); }
/** java.io.ObjectStreamClass#getSerialVersionUID() */ public void test_getSerialVersionUID() { ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class); assertTrue( "getSerialversionUID returned incorrect uid: " + osc.getSerialVersionUID() + " instead of " + DummyClass.getUID(), osc.getSerialVersionUID() == DummyClass.getUID()); }
/** java.io.ObjectStreamClass#toString() */ public void test_toString() { ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class); String oscString = osc.toString(); // The previous test was more specific than the spec so it was replaced // with the test below assertTrue( "toString returned incorrect string: " + osc.toString(), oscString.indexOf("serialVersionUID") >= 0 && oscString.indexOf("999999999999999L") >= 0); }
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); } } }
public void test_specialTypes() { Class<?> proxyClass = Proxy.getProxyClass(this.getClass().getClassLoader(), new Class[] {Runnable.class}); ObjectStreamClass proxyStreamClass = ObjectStreamClass.lookup(proxyClass); assertEquals( "Proxy classes should have zero serialVersionUID", 0, proxyStreamClass.getSerialVersionUID()); ObjectStreamField[] proxyFields = proxyStreamClass.getFields(); assertEquals("Proxy classes should have no serialized fields", 0, proxyFields.length); ObjectStreamClass enumStreamClass = ObjectStreamClass.lookup(Thread.State.class); assertEquals( "Enum classes should have zero serialVersionUID", 0, enumStreamClass.getSerialVersionUID()); ObjectStreamField[] enumFields = enumStreamClass.getFields(); assertEquals("Enum classes should have no serialized fields", 0, enumFields.length); }
protected void updateOptions() { if (m_clusterer instanceof OptionHandler) { m_clustererOptions = Utils.joinOptions(((OptionHandler) m_clusterer).getOptions()); } else { m_clustererOptions = ""; } if (m_clusterer instanceof Serializable) { ObjectStreamClass obs = ObjectStreamClass.lookup(m_clusterer.getClass()); m_clustererVersion = "" + obs.getSerialVersionUID(); } else { m_clustererVersion = ""; } }
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()); } }
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; }
/** * java.io.ObjectStreamClass#lookupAny(java.lang.Class) * * @since 1.6 */ public void test_lookupAnyLjava_lang_Class() { // Test for method java.io.ObjectStreamClass // java.io.ObjectStreamClass.lookupAny(java.lang.Class) ObjectStreamClass osc = ObjectStreamClass.lookupAny(DummyClass.class); assertEquals( "lookup returned wrong class: " + osc.getName(), "org.apache.harmony.tests.java.io.ObjectStreamClassTest$DummyClass", osc.getName()); osc = ObjectStreamClass.lookupAny(NonSerialzableClass.class); assertEquals( "lookup returned wrong class: " + osc.getName(), "org.apache.harmony.tests.java.io.ObjectStreamClassTest$NonSerialzableClass", osc.getName()); osc = ObjectStreamClass.lookupAny(ExternalizableClass.class); assertEquals( "lookup returned wrong class: " + osc.getName(), "org.apache.harmony.tests.java.io.ObjectStreamClassTest$ExternalizableClass", osc.getName()); osc = ObjectStreamClass.lookup(NonSerialzableClass.class); assertNull(osc); }
private long serialVersionUIDFor(Object memberIsAvailable) { return ObjectStreamClass.lookup(memberIsAvailable.getClass()).getSerialVersionUID(); }
/** java.io.ObjectOutputStream#replaceObject(java.lang.Object) */ public void test_replaceObject() throws Exception { // Regression for HARMONY-1429 ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStreamWithReplace oos = new ObjectOutputStreamWithReplace(baos); oos.writeObject(new NotSerializable()); oos.flush(); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); Object obj = ois.readObject(); oos.close(); ois.close(); assertTrue("replaceObject has not been called", (obj instanceof Long)); // Regression for HARMONY-2239 Object replaceObject = int.class; baos = new ByteArrayOutputStream(); ObjectOutputStreamWithReplace2 oos2 = new ObjectOutputStreamWithReplace2(baos); oos2.writeObject(new WriteReplaceObject(replaceObject)); oos2.flush(); ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); obj = ois.readObject(); oos.close(); ois.close(); assertTrue("replaceObject has not been called", (obj instanceof Long)); replaceObject = ObjectStreamClass.lookup(Integer.class); baos = new ByteArrayOutputStream(); oos2 = new ObjectOutputStreamWithReplace2(baos); oos2.writeObject(new WriteReplaceObject(replaceObject)); oos2.flush(); ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); obj = ois.readObject(); oos.close(); ois.close(); assertTrue("replaceObject has not been called", (obj instanceof Long)); replaceObject = WriteReplaceObject.Color.red; baos = new ByteArrayOutputStream(); oos2 = new ObjectOutputStreamWithReplace2(baos); oos2.writeObject(new WriteReplaceObject(replaceObject)); oos2.flush(); ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); obj = ois.readObject(); oos.close(); ois.close(); assertTrue("replaceObject has not been called", (obj instanceof Long)); // Regression for HARMONY-3158 Object obj1; Object obj2; Object obj3; baos = new ByteArrayOutputStream(); oos = new ObjectOutputStreamWithReplace(baos); oos.writeObject(new Integer(99)); oos.writeObject(Integer.class); oos.writeObject(ObjectStreamClass.lookup(Integer.class)); oos.flush(); ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); obj1 = ois.readObject(); obj2 = ois.readObject(); obj3 = ois.readObject(); oos.close(); ois.close(); assertTrue("1st replaceObject worked incorrectly", obj1 instanceof Long); assertEquals("1st replaceObject worked incorrectly", 99, ((Long) obj1).longValue()); assertEquals("2nd replaceObject worked incorrectly", Integer.class, obj2); assertEquals("3rd replaceObject worked incorrectly", ObjectStreamClass.class, obj3.getClass()); }
protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { hookCalled = true; return ObjectStreamClass.lookup(Class.forName(readUTF())); }
/** * 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."); }
/** * Serializes the given class to the getCurrentDirectory() directory. The static * serializedInstance() method of clazz will be called to get an examplar of clazz. This examplar * will then be serialized out to a file stored in getCurrentDirectory(). * * @param clazz the class to serialize. * @throws RuntimeException if clazz cannot be serialized. This exception has an informative * message and wraps the originally thrown exception as root cause. * @see #getCurrentDirectory() */ private void serializeClass(Class clazz, Map<String, List<String>> classFields) throws RuntimeException { File current = new File(getCurrentDirectory()); if (!current.exists() || !current.isDirectory()) { throw new IllegalStateException( "There is no " + current.getAbsolutePath() + " directory. " + "\nThis is where the serialized classes should be. " + "Please run serializeCurrentDirectory() first."); } try { Field field = clazz.getDeclaredField("serialVersionUID"); int modifiers = field.getModifiers(); boolean _static = Modifier.isStatic(modifiers); boolean _final = Modifier.isFinal(modifiers); field.setAccessible(true); if (!_static || !_final || !(23L == field.getLong(null))) { throw new RuntimeException( "Class " + clazz + " does not define static final " + "long serialVersionUID = 23L"); } int numFields = getNumNonSerialVersionUIDFields(clazz); if (numFields > 0) { Method method = clazz.getMethod("serializableInstance"); Object object = method.invoke(null); File file = new File(current, clazz.getName() + ".ser"); boolean created = file.createNewFile(); FileOutputStream out = new FileOutputStream(file); ObjectOutputStream objOut = new ObjectOutputStream(out); objOut.writeObject(object); out.close(); } // Make entry in list of class fields. ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(clazz); String className = objectStreamClass.getName(); ObjectStreamField[] fields = objectStreamClass.getFields(); @SuppressWarnings("Convert2Diamond") List<String> fieldList = new ArrayList<>(); for (ObjectStreamField objectStreamField : fields) { String fieldName = objectStreamField.getName(); fieldList.add(fieldName); } classFields.put(className, fieldList); } catch (NoSuchFieldException e) { throw new RuntimeException( ("There is no static final long field " + "'serialVersionUID' in " + clazz + ". Please make one and set it " + "to 23L.")); } catch (NoSuchMethodException e) { throw new RuntimeException( "Class " + clazz + "does not " + "have a public static serializableInstance constructor.", e); } catch (IllegalAccessException e) { throw new RuntimeException( "The method serializableInstance() of " + "class " + clazz + " is not public.", e); } catch (InvocationTargetException e) { throw new RuntimeException( "Unable to statically call the " + "serializableInstance() method of class " + clazz + ".", e); } catch (IOException e) { throw new RuntimeException( "Could not create a new, writeable file " + "in " + getCurrentDirectory() + " when trying to serialize " + clazz + ".", e); } }
public void testSerialization() { ObjectStreamClass osc = ObjectStreamClass.lookup(ObjectStreamClass.class); assertEquals(0, osc.getFields().length); }
/** java.io.ObjectStreamClass#getField(java.lang.String) */ public void test_getFieldLjava_lang_String() { ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class); assertEquals("getField did not return correct field", 'J', osc.getField("bam").getTypeCode()); assertNull("getField did not null for non-existent field", osc.getField("wham")); }