package com.mycompany.webapps.gi2spring.view;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.view.AbstractView;

import com.mycompany.webapps.gi2spring.controller.Constants;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * Retrieve the model delivered by the controller and render it as xml.
 * 
 * @author bwalsh
 */
public class XMLView extends AbstractView {

	/** Logger for this class */
	static Logger logger = Logger.getLogger(XMLView.class);

	/**
	 * @param map -
	 *            Map with name Strings as keys and corresponding model objects
	 *            as values (Map can also be null in case of empty model)
	 * @param request -
	 *            current HTTP request
	 * @param response -
	 *            HTTP response we are building
	 */
	protected void renderMergedOutputModel(Map map, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		logger.info("Starting rendering of " + this.getBeanName());

		// -------------------------------- create xml via xstream
		XStream xstream = new XStream(new DomDriver());

		// get the model from the map passed created by the controller
		Object model = map.get(Constants.MODELNAME);

		// if the model is null, we have an exception
		String xml = null;
		if (model != null) {
			xml = xstream.toXML(model);
		} else {
			// so render entire map
			xml = xstream.toXML(map);
		}

		// -------------------------------- write the bytes to the response
		response.getOutputStream().write(xml.getBytes());

		// -------------------------------- set header info default to text/xml
		if (StringUtils.isEmpty(getContentType())) {
			setContentType("text/xml; charset=ISO-8859-1");
		}
		response.setContentType(getContentType());
		// tell browser not to cache response
		response.setHeader("Cache-Control", "no-cache");
		logger.info("xml=" + xml);
	}

}
