
import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;

public class XsltServlet extends HttpServlet
{
	TransformerFactory tFactory        = null;
	Transformer        htmlTransformer = null;
	String             htmlXslFile     = null;

	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);
		try
		{
			tFactory = TransformerFactory.newInstance();
			htmlXslFile          = getServletContext().getRealPath("/") + "/test_HTML.xsl";
			File   htmlFile      = new File(htmlXslFile);
			Source htmlXslSource = new StreamSource(htmlFile);
			htmlTransformer      = tFactory.newTransformer(htmlXslSource);
		}
		catch (Exception e)
		{
			System.err.println("Exception in init:  " + e.toString());
			e.printStackTrace();
		}
	}


	public void doGet(HttpServletRequest req, HttpServletResponse res)
			 throws ServletException, IOException
	{
		doHtml(req, res);
	}

	private void doHtml(HttpServletRequest req, HttpServletResponse res)
			 throws ServletException, IOException
	{
		res.setContentType("text/html; charset=UTF-8");
		PrintWriter out = res.getWriter();
		try
		{
			Source xmlSource = new StreamSource(new StringReader(getXmlString()));
			htmlTransformer.transform(xmlSource, new StreamResult(out));
		}
		catch (Exception e)
		{
			NSAuditTrail.logException(e, req, this);
			out.println("Exception in doGet" + e.toString());
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			 throws ServletException, IOException
	{
		doGet(req, res);
	}

	private String getXmlString()
	{
		String xml = new String("<?xml version=\"1.0\"?>\n" +
				"<DOCUMENT_BODY>\n" +
				"   <USER>\n" +
				"      <USER_ID>harmpits</USER_ID>\n" +
				"      <USER_FIRST_NAME>Harry</USER_FIRST_NAME>\n" +
				"      <USER_LAST_NAME>Armpits</USER_LAST_NAME>\n" +
				"   </USER>\n" +
				"</DOCUMENT_BODY>\n");
		return xml;
	}

}

