package jp.sourceforge.glad.io;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import jp.sourceforge.glad.reflect.ClassNotFoundRuntimeException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class IOUtils {

    static final Log log = LogFactory.getLog(IOUtils.class);

    public static byte[] serialize(Object object) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            oos.close();
            return baos.toByteArray();
        } catch (IOException e) {
            throw new IORuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T deserialize(byte[] binary) {
        ByteArrayInputStream bais = new ByteArrayInputStream(binary);
        try {
            ObjectInputStream ois = new ObjectInputStream(bais);
            Object object = ois.readObject();
            ois.close();
            return (T) object;
        } catch (IOException e) {
            throw new IORuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new ClassNotFoundRuntimeException(e);
        }
    }

    public static void close(Closeable closeable) {
        close(closeable, false);
    }

    public static void close(Closeable closeable, boolean rethrow) {
        try {
            closeable.close();
        } catch (IOException e) {
            if (rethrow) {
                throw new IORuntimeException(e);
            }
            log.warn(e);
        }
    }

}
