Search in sources :

Example 91 with ObjectInputStream

use of java.io.ObjectInputStream in project byte-buddy by raphw.

the class AgentBuilderDefaultApplicationTest method testSerializableLambda.

@Test
@JavaVersionRule.Enforce(8)
@AgentAttachmentRule.Enforce(redefinesClasses = true)
@IntegrationRule.Enforce
public void testSerializableLambda() throws Exception {
    assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class));
    ClassLoader classLoader = lambdaSamples();
    ClassFileTransformer classFileTransformer = new AgentBuilder.Default().with(poolStrategy).ignore(none()).with(AgentBuilder.LambdaInstrumentationStrategy.ENABLED).installOn(ByteBuddyAgent.getInstrumentation());
    try {
        Class<?> sampleFactory = classLoader.loadClass(LAMBDA_SAMPLE_FACTORY);
        @SuppressWarnings("unchecked") Callable<String> instance = (Callable<String>) sampleFactory.getDeclaredMethod("serializable", String.class).invoke(sampleFactory.getDeclaredConstructor().newInstance(), FOO);
        assertThat(instance.call(), is(FOO));
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(instance);
        objectOutputStream.close();
        ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(outputStream.toByteArray()));
        @SuppressWarnings("unchecked") Callable<String> deserialized = (Callable<String>) objectInputStream.readObject();
        assertThat(deserialized.call(), is(FOO));
        objectInputStream.close();
    } finally {
        ByteBuddyAgent.getInstrumentation().removeTransformer(classFileTransformer);
        AgentBuilder.LambdaInstrumentationStrategy.release(classFileTransformer, ByteBuddyAgent.getInstrumentation());
    }
}
Also used : ClassFileTransformer(java.lang.instrument.ClassFileTransformer) Instrumentation(java.lang.instrument.Instrumentation) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) Callable(java.util.concurrent.Callable) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayClassLoader(net.bytebuddy.dynamic.loading.ByteArrayClassLoader) ObjectInputStream(java.io.ObjectInputStream) Test(org.junit.Test)

Example 92 with ObjectInputStream

use of java.io.ObjectInputStream in project roboguice by roboguice.

the class MultibinderTest method testMultibinderSetIsSerializable.

public void testMultibinderSetIsSerializable() throws IOException, ClassNotFoundException {
    Injector injector = Guice.createInjector(new AbstractModule() {

        protected void configure() {
            Multibinder.newSetBinder(binder(), String.class).addBinding().toInstance("A");
        }
    });
    Set<String> set = injector.getInstance(Key.get(setOfString));
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream);
    try {
        objectOutputStream.writeObject(set);
    } finally {
        objectOutputStream.close();
    }
    ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(byteStream.toByteArray()));
    try {
        Object setCopy = objectInputStream.readObject();
        assertEquals(set, setCopy);
    } finally {
        objectInputStream.close();
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) Injector(com.google.inject.Injector) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) AbstractModule(com.google.inject.AbstractModule) ObjectInputStream(java.io.ObjectInputStream)

Example 93 with ObjectInputStream

use of java.io.ObjectInputStream in project DirectMemory by raffaeleguidi.

the class StandardSerializer method deserialize.

public Serializable deserialize(byte[] source, @SuppressWarnings({ "rawtypes", "unchecked" }) Class clazz) throws IOException, ClassNotFoundException {
    ByteArrayInputStream bis = new ByteArrayInputStream(source);
    ObjectInputStream ois = new ObjectInputStream(bis);
    Serializable obj = (Serializable) ois.readObject();
    ois.close();
    return obj;
}
Also used : Serializable(java.io.Serializable) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectInputStream(java.io.ObjectInputStream)

Example 94 with ObjectInputStream

use of java.io.ObjectInputStream in project orientdb by orientechnologies.

the class OGremlinHelper method cloneObject.

/*
   * Tries to clone any Java object by using 3 techniques: - instanceof (most verbose but faster performance) - reflection (medium
   * performance) - serialization (applies for any object type but has a performance overhead)
   */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object cloneObject(final Object objectToClone, final Object previousClone) {
    // Clone any Map (shallow clone should be enough at this level)
    if (objectToClone instanceof Map) {
        Map recycledMap = (Map) previousClone;
        if (recycledMap == null)
            recycledMap = new HashMap();
        else
            recycledMap.clear();
        recycledMap.putAll((Map<?, ?>) objectToClone);
        return recycledMap;
    // Clone any collection (shallow clone should be enough at this level)
    } else if (objectToClone instanceof Collection) {
        Collection recycledCollection = (Collection) previousClone;
        if (recycledCollection == null)
            recycledCollection = new ArrayList();
        else
            recycledCollection.clear();
        recycledCollection.addAll((Collection<?>) objectToClone);
        return recycledCollection;
    // Clone String
    } else if (objectToClone instanceof String) {
        return objectToClone;
    } else if (objectToClone instanceof Number) {
        return objectToClone;
    // Clone Date
    } else if (objectToClone instanceof Date) {
        return (Date) ((Date) objectToClone).clone();
    } else {
        // ***************************************************************************************************************************************
        try {
            Object newClone;
            for (Class<?> obj = objectToClone.getClass(); !obj.equals(Object.class); obj = obj.getSuperclass()) {
                Method[] m = obj.getDeclaredMethods();
                for (int i = 0; i < m.length; i++) {
                    if (m[i].getName().equals("clone")) {
                        m[i].setAccessible(true);
                        newClone = m[i].invoke(objectToClone);
                        System.out.println(objectToClone.getClass() + " cloned by Reflection. Performance can be improved by adding the class to the list of known types");
                        return newClone;
                    }
                }
            }
            throw new Exception("Method clone not found");
        // ***************************************************************************************************************************************
        // 3. Polymorphic clone (Deep cloning by Serialization)
        // ***************************************************************************************************************************************
        } catch (Throwable e1) {
            try {
                final ByteArrayOutputStream bytes = new ByteArrayOutputStream() {

                    public synchronized byte[] toByteArray() {
                        return buf;
                    }
                };
                final ObjectOutputStream out = new ObjectOutputStream(bytes);
                out.writeObject(objectToClone);
                out.close();
                final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()));
                System.out.println(objectToClone.getClass() + " cloned by Serialization. Performance can be improved by adding the class to the list of known types");
                return in.readObject();
            // ***************************************************************************************************************************************
            // 4. Impossible to clone
            // ***************************************************************************************************************************************
            } catch (Throwable e2) {
                OLogManager.instance().error(null, "[GremlinHelper] error on cloning object %s, previous %s", e2, objectToClone, previousClone);
                return null;
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) Date(java.util.Date) OException(com.orientechnologies.common.exception.OException) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) ByteArrayInputStream(java.io.ByteArrayInputStream) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map) ObjectInputStream(java.io.ObjectInputStream)

Example 95 with ObjectInputStream

use of java.io.ObjectInputStream in project robovm by robovm.

the class AnnotationMember method rethrowError.

/**
     * Throws contained error (if any) with a renewed stack trace.
     */
public void rethrowError() throws Throwable {
    if (tag == ERROR) {
        // first check for expected types
        if (value instanceof TypeNotPresentException) {
            TypeNotPresentException tnpe = (TypeNotPresentException) value;
            throw new TypeNotPresentException(tnpe.typeName(), tnpe.getCause());
        } else if (value instanceof EnumConstantNotPresentException) {
            EnumConstantNotPresentException ecnpe = (EnumConstantNotPresentException) value;
            throw new EnumConstantNotPresentException(ecnpe.enumType(), ecnpe.constantName());
        } else if (value instanceof ArrayStoreException) {
            ArrayStoreException ase = (ArrayStoreException) value;
            throw new ArrayStoreException(ase.getMessage());
        }
        // got some other error, have to go with deep cloning
        // via serialization mechanism
        Throwable error = (Throwable) value;
        StackTraceElement[] ste = error.getStackTrace();
        ByteArrayOutputStream bos = new ByteArrayOutputStream(ste == null ? 512 : (ste.length + 1) * 80);
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(error);
        oos.flush();
        oos.close();
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        error = (Throwable) ois.readObject();
        ois.close();
        throw error;
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) ObjectInputStream(java.io.ObjectInputStream)

Aggregations

ObjectInputStream (java.io.ObjectInputStream)1041 ByteArrayInputStream (java.io.ByteArrayInputStream)667 ObjectOutputStream (java.io.ObjectOutputStream)427 ByteArrayOutputStream (java.io.ByteArrayOutputStream)354 IOException (java.io.IOException)341 FileInputStream (java.io.FileInputStream)152 Test (org.junit.Test)128 File (java.io.File)89 InputStream (java.io.InputStream)85 BufferedInputStream (java.io.BufferedInputStream)47 Serializable (java.io.Serializable)40 HashMap (java.util.HashMap)35 ArrayList (java.util.ArrayList)31 FileNotFoundException (java.io.FileNotFoundException)27 FileOutputStream (java.io.FileOutputStream)27 Test (org.testng.annotations.Test)26 Map (java.util.Map)25 EOFException (java.io.EOFException)21 GZIPInputStream (java.util.zip.GZIPInputStream)21 ObjectInput (java.io.ObjectInput)20