package omq.common.util.Serializers;

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

import omq.exception.SerializerException;


/**
 * 
 * @author Sergi Toda <sergi.toda@estudiants.urv.cat>
 * @author Guillermo Guerrero <guillermo.guerrero@estudiants.urv.cat>
 * 
 */
public class JavaImp implements ISerializer {

	@Override
	public byte[] serialize(Object obj) throws SerializerException {
		try {
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			ObjectOutputStream output = new ObjectOutputStream(stream);
			output.writeObject(obj);

			output.flush();
			output.close();

			byte[] bArray = stream.toByteArray();

			stream.flush();
			stream.close();

			return bArray;
		} catch (Exception e) {
			throw new SerializerException("Serialize -> " + e.getMessage(), e);
		}
	}
	
	@Override
	public byte[] serialize(Object obj, Class<?> clazz) throws SerializerException {
		return serialize(obj);
	}

	@Override
	public Object deserialize(byte[] bytes) throws SerializerException {
		try {
			ByteArrayInputStream input = new ByteArrayInputStream(bytes);
			ObjectInputStream objInput = new ObjectInputStream(input);

			Object obj = objInput.readObject();

			objInput.close();
			input.close();

			return obj;
		} catch (Exception e) {
			throw new SerializerException("Deserialize -> " + e.getMessage(), e);
		}
	}	

	@Override
	public Object deserialize(byte[] bytes, Class<?> clazz) throws SerializerException {
		return deserialize(bytes);
	}

}
