package com.ejie.ab04b.parse;

import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import com.ejie.ab04b.exception.AB04BException;

/**
 * Clase para obtener el XML a partir de un objeto
 * 
 * @author GFI-NORTE
 * 
 <I>
 */
public class MessageUnparser<I> {

	/**
	 * Metodo que genera un String con el XML que representa un objeto de
	 * negocio.
	 * 
	 *  object
	 *            I Clase a partir de la que se intentará generar el XML
	 *  String
	 *
	 * @param object the object
	 * @return the string
	 * @throws AB04BException the AB 04 B exception
	 */
	public String parse(I object) throws AB04BException {
		try {

			if (object == null) {
				return null;
			}

			JAXBContext context = JAXBContext.newInstance(object.getClass());
			Marshaller marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "ISO-8859-1");

			StringWriter stringWriter = new StringWriter();

			marshaller.marshal(object, stringWriter);

			return stringWriter.getBuffer().toString();
		} catch (Exception e) {
			throw new AB04BException(e, e.getMessage());
		}
	}

}
