package demo.transformers;

import org.apache.commons.lang.text.StrTokenizer;
import org.jdom.Document;
import org.jdom.Element;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractTransformer;

public class CsvToXml extends AbstractTransformer {

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

		logger.debug("doTransform: src = "+src);

		// TODO: add error handling - exercise for reader :-)

		// parse csv string into tokens and create xml
		StrTokenizer tokenizer = StrTokenizer.getCSVInstance((String) src);
		
		Element root = new Element("LogMessage");
		root.addContent(new Element("appName").setText(tokenizer.nextToken()));
		root.addContent(new Element("timeStamp").setText(tokenizer.nextToken()));
		root.addContent(new Element("logLevel").setText(tokenizer.nextToken()));
		root.addContent(new Element("shortMsg").setText(tokenizer.nextToken()));
		root.addContent(new Element("longMsg").setText(tokenizer.nextToken()));
		
		Document doc = new Document(root);

		String xml = XmlUtils.convertJdomToString(doc);
		logger.info("transformed CSV message to XML String");

		return xml;
	}

}
