use of java.io.ObjectStreamClass in project revapi by revapi.
the class SUIDGeneratorTest method testHandlingEmptyClass.
@Test
public void testHandlingEmptyClass() throws Exception {
try {
ObjectStreamClass s = ObjectStreamClass.lookup(Empty.class);
long officialSUID = s.getSerialVersionUID();
SUIDGeneratingAnnotationProcessor ap = new SUIDGeneratingAnnotationProcessor();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
JavaCompiler.CompilationTask task = compiler.getTask(null, null, null, null, Arrays.asList(TestClass.class.getName()), Arrays.asList(new SourceInClassLoader("suid/Empty.java")));
task.setProcessors(Arrays.asList(ap));
task.call();
Assert.assertEquals(officialSUID, ap.generatedSUID);
MessageDigest md = MessageDigest.getInstance("SHA");
byte[] hashBytes = md.digest("".getBytes("UTF-8"));
long hash = 0;
for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
hash = (hash << 8) | (hashBytes[i] & 0xFF);
}
Assert.assertEquals(hash, ap.generatedStructuralId);
} finally {
new File("Empty.class").delete();
}
}
use of java.io.ObjectStreamClass in project ovirt-engine by oVirt.
the class CopyOnAccessMap method clone.
@SuppressWarnings("unchecked")
private <O> O clone(O originalKey) {
// We use an intermediate buffer to hold the serialized form of the
// object:
byte[] buffer = null;
// Serialize the object to an array of bytes:
ByteArrayOutputStream bufferOut = null;
ObjectOutputStream objectOut = null;
try {
bufferOut = new ByteArrayOutputStream(512);
objectOut = new ObjectOutputStream(bufferOut);
objectOut.writeObject(originalKey);
buffer = bufferOut.toByteArray();
} catch (IOException exception) {
throw new RuntimeException(exception);
} finally {
if (objectOut != null) {
try {
objectOut.close();
} catch (IOException exception) {
// Ignored.
}
}
}
// Create a new instance of the object deserializing it from the
// buffer:
ByteArrayInputStream bufferIn = null;
ObjectInputStream objectIn = null;
try {
bufferIn = new ByteArrayInputStream(buffer);
objectIn = new ObjectInputStream(bufferIn) {
@Override
protected Class<?> resolveClass(ObjectStreamClass description) throws IOException, ClassNotFoundException {
// then just call the overridden method:
try {
return Class.forName(description.getName(), false, Thread.currentThread().getContextClassLoader());
} catch (ClassNotFoundException exception) {
return super.resolveClass(description);
}
}
};
return (O) objectIn.readObject();
} catch (IOException | ClassNotFoundException exception) {
throw new RuntimeException(exception);
} finally {
if (objectIn != null) {
try {
objectIn.close();
} catch (IOException exception) {
// Ignored.
}
}
}
}
use of java.io.ObjectStreamClass in project wicket by apache.
the class CheckingObjectOutputStream method internalCheck.
private void internalCheck(Object obj) {
final Object original = obj;
Class<?> cls = obj.getClass();
nameStack.add(simpleName);
traceStack.add(new TraceSlot(obj, fieldDescription));
for (IObjectChecker checker : checkers) {
IObjectChecker.Result result = checker.check(obj);
if (result.status == IObjectChecker.Result.Status.FAILURE) {
String prettyPrintMessage = toPrettyPrintedStack(Classes.name(cls));
String exceptionMessage = result.reason + '\n' + prettyPrintMessage;
throw new ObjectCheckException(exceptionMessage, result.cause);
}
}
ObjectStreamClass desc;
for (; ; ) {
try {
desc = (ObjectStreamClass) LOOKUP_METHOD.invoke(null, cls, Boolean.TRUE);
Class<?> repCl;
if (!(Boolean) HAS_WRITE_REPLACE_METHOD_METHOD.invoke(desc, (Object[]) null) || (obj = INVOKE_WRITE_REPLACE_METHOD.invoke(desc, obj)) == null || (repCl = obj.getClass()) == cls) {
break;
}
cls = repCl;
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
if (cls.isPrimitive()) {
// skip
} else if (cls.isArray()) {
checked.put(original, null);
Class<?> ccl = cls.getComponentType();
if (!(ccl.isPrimitive())) {
Object[] objs = (Object[]) obj;
for (int i = 0; i < objs.length; i++) {
CharSequence arrayPos = new StringBuilder(4).append('[').append(i).append(']');
simpleName = arrayPos;
fieldDescription += arrayPos;
check(objs[i]);
}
}
} else if (obj instanceof Externalizable && (!Proxy.isProxyClass(cls))) {
Externalizable extObj = (Externalizable) obj;
try {
extObj.writeExternal(new ObjectOutputAdaptor() {
private int count = 0;
@Override
public void writeObject(Object streamObj) throws IOException {
// Check for circular reference.
if (checked.containsKey(streamObj)) {
return;
}
CharSequence arrayPos = new StringBuilder(10).append("[write:").append(count++).append(']');
simpleName = arrayPos;
fieldDescription += arrayPos;
check(streamObj);
checked.put(streamObj, null);
}
});
} catch (Exception e) {
if (e instanceof ObjectCheckException) {
throw (ObjectCheckException) e;
}
log.warn("Error delegating to Externalizable : {}, path: {}", e.getMessage(), currentPath());
}
} else {
Method writeObjectMethod = null;
if (writeObjectMethodMissing.contains(cls) == false) {
try {
writeObjectMethod = cls.getDeclaredMethod("writeObject", java.io.ObjectOutputStream.class);
} catch (SecurityException | NoSuchMethodException e) {
// we can't access / set accessible to true
writeObjectMethodMissing.add(cls);
}
}
if (writeObjectMethod != null) {
class InterceptingObjectOutputStream extends ObjectOutputStream {
private int counter;
InterceptingObjectOutputStream() throws IOException {
super(DUMMY_OUTPUT_STREAM);
enableReplaceObject(true);
}
@Override
protected Object replaceObject(Object streamObj) throws IOException {
if (streamObj == original) {
return streamObj;
}
counter++;
// Check for circular reference.
if (checked.containsKey(streamObj)) {
return null;
}
CharSequence arrayPos = new StringBuilder(10).append("[write:").append(counter).append(']');
simpleName = arrayPos;
fieldDescription += arrayPos;
check(streamObj);
checked.put(streamObj, null);
return streamObj;
}
}
try {
InterceptingObjectOutputStream ioos = new InterceptingObjectOutputStream();
ioos.writeObject(obj);
} catch (Exception e) {
if (e instanceof ObjectCheckException) {
throw (ObjectCheckException) e;
}
log.warn("error delegating to writeObject : {}, path: {}", e.getMessage(), currentPath());
}
} else {
Object[] slots;
try {
slots = (Object[]) GET_CLASS_DATA_LAYOUT_METHOD.invoke(desc, (Object[]) null);
} catch (Exception e) {
throw new RuntimeException(e);
}
for (Object slot : slots) {
ObjectStreamClass slotDesc;
try {
Field descField = slot.getClass().getDeclaredField("desc");
descField.setAccessible(true);
slotDesc = (ObjectStreamClass) descField.get(slot);
} catch (Exception e) {
throw new RuntimeException(e);
}
checked.put(original, null);
checkFields(obj, slotDesc);
}
}
}
traceStack.removeLast();
nameStack.removeLast();
}
use of java.io.ObjectStreamClass in project hale by halestudio.
the class OSerializationHelper method convertFromDB.
/**
* Convert a value received from the database, e.g. {@link ODocument}s to
* {@link Instance}s, {@link Group}s or unwraps contained values.
*
* @param value the value
* @param parent the parent group
* @param childName the name of the child the value is associated to
* @return the converted object
*/
public static Object convertFromDB(Object value, OGroup parent, QName childName) {
if (value instanceof ODocument) {
ODocument doc = (ODocument) value;
if (doc.containsField(BINARY_WRAPPER_FIELD) || doc.containsField(OSerializationHelper.FIELD_SERIALIZATION_TYPE)) {
// extract wrapped ORecordBytes
return OSerializationHelper.deserialize(doc, parent, childName);
} else {
ChildDefinition<?> child = parent.getDefinition().getChild(childName);
if (child.asProperty() != null) {
return new OInstance((ODocument) value, child.asProperty().getPropertyType(), parent.getDb(), // no data set necessary for
null);
// nested instances
} else if (child.asGroup() != null) {
return new OGroup((ODocument) value, child.asGroup(), parent.getDb());
} else {
throw new IllegalStateException("Field " + childName + " is associated neither with a property nor a group.");
}
}
}
// TODO objects that are not supported inside document
if (value instanceof ORecordBytes) {
// XXX should not be reached as every ORecordBytes should be
// contained in a wrapper
// TODO try conversion first?!
// object deserialization
ORecordBytes record = (ORecordBytes) value;
ByteArrayInputStream bytes = new ByteArrayInputStream(record.toStream());
try {
ObjectInputStream in = new ObjectInputStream(bytes) {
@Override
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
Class<?> result = resolved.get(desc.getName());
if (result == null) {
result = OsgiUtils.loadClass(desc.getName(), null);
if (resolved.size() > 200) {
resolved.entrySet().iterator().remove();
}
resolved.put(desc.getName(), result);
}
return result;
}
};
return in.readObject();
} catch (Exception e) {
throw new IllegalStateException("Could not deserialize field value.", e);
}
}
return value;
}
use of java.io.ObjectStreamClass in project j2objc by google.
the class SerializationTest method testSerializeFieldMadeTransient.
// http://b/4471249
public void testSerializeFieldMadeTransient() throws Exception {
// Does ObjectStreamClass have the right idea?
ObjectStreamClass osc = ObjectStreamClass.lookup(FieldMadeTransient.class);
ObjectStreamField[] fields = osc.getFields();
assertEquals(1, fields.length);
assertEquals("nonTransientInt", fields[0].getName());
assertEquals(int.class, fields[0].getType());
// this was created by serializing a FieldMadeTransient with a non-0 transientInt
String s = "aced0005737200346c6962636f72652e6a6176612e696f2e53657269616c697a6174696f6e54657" + "374244669656c644d6164655472616e7369656e74000000000000000002000149000c7472616e736" + "9656e74496e747870abababab";
FieldMadeTransient deserialized = (FieldMadeTransient) SerializationTester.deserializeHex(s);
assertEquals(0, deserialized.transientInt);
}
Aggregations