All Downloads are FREE. Search and download functionalities are using the official Maven repository.

br.com.anteros.nosql.persistence.mongodb.converters.NoSQLSerializer Maven / Gradle / Ivy

There is a newer version: 1.0.6
Show newest version
package br.com.anteros.nosql.persistence.mongodb.converters;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.bson.types.Binary;


public final class NoSQLSerializer {
    private NoSQLSerializer() {
    }


    public static byte[] serialize(final Object o, final boolean zip) throws IOException {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStream os = baos;
        ObjectOutputStream oos = null;
        try {
            if (zip) {
                os = new GZIPOutputStream(os);
            }
            oos = new ObjectOutputStream(os);
            oos.writeObject(o);
            oos.flush();
        } finally {
            if (oos != null) {
                oos.close();
            }
            os.close();
        }

        return baos.toByteArray();
    }


    public static Object deserialize(final Object data, final boolean zipped) throws IOException, ClassNotFoundException {
        final ByteArrayInputStream bais;
        if (data instanceof Binary) {
            bais = new ByteArrayInputStream(((Binary) data).getData());
        } else {
            bais = new ByteArrayInputStream((byte[]) data);
        }

        InputStream is = bais;
        try {
            if (zipped) {
                is = new GZIPInputStream(is);
            }

            final ObjectInputStream ois = new ObjectInputStream(is);
            return ois.readObject();
        } finally {
            is.close();
        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy