package com.docus.server.common.util.io;

import com.baomidou.mybatisplus.extension.api.Assert;
import com.docus.core.util.pdf.util.IOUtils;
import com.docus.server.common.util.LogUtil;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializableMsgCodec {

    public Serializable decode(byte[] bytes) {
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new ByteArrayInputStream(bytes));

            return (Serializable) ois.readObject();
        } catch (Exception e) {
            Assert.fail(LogUtil.exceptionMsg("对象序列化异常，异常消息", e));
            return null;
        } finally {
            IOUtils.close(ois);
        }

    }

    public byte[] encode(Serializable obj) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {
            Assert.fail(LogUtil.exceptionMsg("对象序列化异常，异常消息", e));
            return null;
        } finally {
            IOUtils.close(baos);
            IOUtils.close(oos);
        }
    }
}
