package demo.transformers;

import java.io.StringReader;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractTransformer;

import demo.domain.LogMessage;

public class XmlStringToLogMessage extends AbstractTransformer {

	@Override
	protected Object doTransform(Object src, String encoding)
			throws TransformerException {

		logger.debug("transforming XML message to LogMessage:\n"+src);

		Document doc = null;
		LogMessage lm = null;

		try {
			StringReader sr = new StringReader((String) src);
			doc = new SAXBuilder().build(sr);
			Element root = doc.getRootElement();
			String appName = root.getChildText("appName");
			String timeStamp = root.getChildText("timeStamp");
			String logLevel = root.getChildText("logLevel");
			String shortMsg = root.getChildText("shortMsg");
			String longMsg = root.getChildText("longMsg");

			lm = new LogMessage(appName, timeStamp, logLevel, shortMsg, longMsg);
			logger.info("transformed XML message to LogMessage:\n"+lm);

		} catch (Exception e) {
			logger.error("caught exception building LogMessage from String", e);
		}

		return lm;
	}

}
