package com.ejie.ab39a.parse;

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

/**
 * Clase para obtener el XML a partir de un objeto
 * 
 *  
 * 
 * @param <I>
 *            i i
 */
public class MessageUnparser<I> {

	/**
	 * Metodo que genera un String con el XML que representa un objeto de
	 * negocio
	 * 
	 * @param object
	 *            clase object
	 * @return String objeto
	 * @throws JAXBException
	 *             e e
	 * 
	 */
	public String parse(I object) throws JAXBException {

		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, "UTF-8");
		marshaller.setProperty(Marshaller.JAXB_ENCODING, "ISO-8859-1");

		StringWriter stringWriter = new StringWriter();

		marshaller.marshal(object, stringWriter);

		return stringWriter.getBuffer().toString();
	}

	/**
	 * parset Object NoRoot
	 * 
	 * @param object
	 *            Object object
	 * @param objNoroot
	 *            JAXBElement<I> objNoroot
	 * @return String String
	 * @throws JAXBException
	 *             e e
	 * 
	 */
	public String parsetObjectNoRoot(I object, JAXBElement<I> objNoroot) throws JAXBException {

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

		JAXBContext context = JAXBContext.newInstance(object.getClass());
		JAXBElement<I> wrapper = objNoroot;
		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(wrapper, stringWriter);

		return stringWriter.getBuffer().toString();

	}
}