package com.cerveza.togglefunction.serializeutil;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;


/**
 * Created by cerveza on 15/11/2016.
 */

public class SerializeUtils {

    public static <T>  byte[] convertToBytes(T object) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out = null;
        byte[] bytes;
        try {
            out = new ObjectOutputStream(bos);
            out.writeObject(object);
            out.flush();
            bytes = bos.toByteArray();
        } finally {
            try {
                bos.close();
            } catch (IOException ex) {
                throw new IOException("could not close strem", ex);
            }
        }
        return bytes;
    }

    public static <T>  T convertFromBytes(byte[] bytes) throws IOException, ClassNotFoundException {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInput in = null;
        T object;
        try {
            in = new ObjectInputStream(bis);
            object = (T) in.readObject();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                throw new IOException("could not close stream", ex);
            }
        }
        return object;
    }
}
