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

com.base4j.cache.serializer.SerializerTools Maven / Gradle / Ivy

There is a newer version: 1.3.1
Show newest version
package com.base4j.cache.serializer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

/**
 * 序列化工具类
 */
public class SerializerTools {
    private static final Logger log = LoggerFactory.getLogger(SerializerTools.class);

    private static final StringSerializer KEY_SERIALIZER = new StringSerializer();
    private static final FstSnappySerializer VALUE_SERIALIZER = new FstSnappySerializer();

    static boolean isEmpty(byte[] data) {
        return (data == null || data.length == 0);
    }

    /**
     * 序列化KEY
     * @param key {Object}
     * @return byte
     */
    public static byte[] serializeKey(final Object key) {
        return KEY_SERIALIZER.serialize(key.toString());
    }

    /**
     * 反序列化KEY
     * @param key {byte[]}
     * @return byte
     */
    public static Object deserializeKey(final byte[] key) {
        return KEY_SERIALIZER.deserialize(key);
    }

    /**
     * 序列化VALUE
     * @param value {Object}
     * @return byte
     */
    public static byte[] serializeValue(final Object value) {
        try {
            return VALUE_SERIALIZER.serialize(value);
        } catch (Exception e) {
            log.warn("value 序列化失败. value = {}", value, e);
            return null;
        }
    }

    /**
     * 反序列化VALUE
     * @param value {byte[]}
     * @return Object
     */
    public static Object deserializeValue(final byte[] value) {
        return VALUE_SERIALIZER.deserialize(value);
    }

    /**
     * 返回序列Collection的值
     * @param values {Collection}
     * @param clazz {Class}
     * @param serializer {Serializer} 序列化工具
     * @param  返回类型
     * @return T
     */
    @SuppressWarnings("unchecked")
    private static > T deserializeValues(Collection values,
        Class clazz, Serializer serializer) {
        if (values == null) {
            return null;
        }

        int valueCount = values.size();
        Collection theValues =
                List.class.isAssignableFrom(clazz)
                        ? new ArrayList(valueCount)
                        : new HashSet(valueCount);

        for (byte[] bs : values) {
            theValues.add(serializer.deserialize(bs));
        }
        return (T) theValues;
    }

}