package com.community.commom.redis;

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

/**
 * redis json 序列化工具
 * @author gengxiang
 * @create 2017-09-06 18:04
 *
 **/
public class RedisObjectSerializer implements RedisSerializer {

    @Override
    public <T> T deserialize(byte[] source, Class<T> tClass) throws SerializationFailedException {
        if (source == null)
            return null;
        if (tClass == String.class)
            return tClass.cast(new String(source));
        try (ByteArrayInputStream byteStream = new ByteArrayInputStream(source);
             ObjectInputStream objectInputStream = new ObjectInputStream(byteStream)) {
            return tClass.cast(objectInputStream.readObject());
        } catch (Exception e) {
            throw new SerializationFailedException("Deserialize failed:" + e, e);
        }
    }

    @Override
    public byte[] serialize(Object object) throws SerializationFailedException {
        if (!(object instanceof Serializable)) {
            throw new IllegalArgumentException("Serializer requires a Serializable payload " + "but received an object of type [" + object.getClass().getName() + "]");
        }
        if (object instanceof String)
            return object.toString().getBytes();
        try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream)) {
            objectOutputStream.writeObject(object);
            objectOutputStream.flush();
            return byteStream.toByteArray();
        } catch (Exception e) {
            throw new SerializationFailedException("Serialize failed:" + object.getClass(), e);
        }
    }
}
