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

wang.moshu.message.ConvertUtil Maven / Gradle / Ivy

Go to download

message-trunk is a lightweight high performance message bus (queue) based on redis.

The newest version!
package wang.moshu.message;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtobufIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;

public class ConvertUtil
{

	private static Map, Schema> cachedSchema = new ConcurrentHashMap<>();

	@SuppressWarnings("unchecked")
	private static  Schema getSchema(Class cls)
	{
		Schema schema = (Schema) cachedSchema.get(cls);
		if (schema == null)
		{
			schema = RuntimeSchema.createFrom(cls);
			if (schema != null)
			{
				cachedSchema.put(cls, schema);
			}
		}
		return schema;
	}

	@SuppressWarnings("unchecked")
	public static  byte[] serialize(T obj)
	{
		Class cls = (Class) obj.getClass();
		LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
		try
		{
			Schema schema = getSchema(cls);
			return ProtobufIOUtil.toByteArray(obj, schema, buffer);
		}
		catch (Exception e)
		{
			throw new IllegalStateException(e.getMessage(), e);
		}
		finally
		{
			buffer.clear();
		}
	}

	public static  T unserialize(byte[] data, Class cls)
	{
		try
		{
			T message = cls.newInstance();
			Schema schema = getSchema(cls);
			ProtobufIOUtil.mergeFrom(data, message, schema);
			return message;
		}
		catch (Exception e)
		{
			throw new IllegalStateException(e.getMessage(), e);
		}
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy