
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.net.URL;

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;

/**
 * Simple demo XSLT transformation servlet
 * CS 433
 * 10/30/01
 */

public class JTrans extends HttpServlet
{
	// initialize the servlet
	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);
	}

	// when someone requests this servlet, it will return any outputed response
	public void doGet (HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException, java.net.MalformedURLException
	{
		// The servlet returns HTML
		response.setContentType("text/html; charset=UTF-8");    
		
		// Output goes in the response stream.
		PrintWriter out = response.getWriter();
		    
		String xmlString = new String();
		
		/**
			Here you would need to fill the string 'xmlString' with valid Xml
		**/ 
		
		// transform some xml using xmlString and some stylesheet stored on the server
		out.println(TransformXml(xmlString, "http://egret/g45/toHtml.xsl"));
			
		out.close();
	}
  
	/**
	 * TransformXml(String xmlString, String xslURL)
	 * 
	 * @param	xmlString - an input string containing valid Xml
	 * @param	xslURL - a URL to the location of the XSLT stylesheet
	 * 
	 * @return	the result of applying the stylesheet to the given Xml
	 */
	private static String TransformXml (String xmlString, String xslURL)	{
		String result;		
				
		try
		{
			TransformerFactory tFactory = TransformerFactory.newInstance();

			//1. load the input Xml
			StringReader xmlReader = new StringReader(xmlString);
			Source xmlSource = new StreamSource(xmlReader);
		     
			// if you also want your Xml input to come from a file, you can use this line:
			//Source xmlSource = new StreamSource(new URL(xmlString).openStream());
			
			//2. load the xslt stylesheet
			Source xslSource = new StreamSource(new URL(xslURL).openStream());
					
			//3. prepare the output buffer
			StringWriter resultBuffer = new StringWriter();
			StreamResult xmlResult = new StreamResult(resultBuffer);
					
			//4. do the transformation
			Transformer transformer = tFactory.newTransformer(xslSource);
			transformer.transform(xmlSource, xmlResult);
			
			//5. gather the result
			result = resultBuffer.toString();
		}
		catch(Exception e)
		{
			// some error occured!  oh no!
			result = e.toString();
		}		
		return RemoveCR(result);
	}
	
	private static String RemoveCR (String target)
	{
		target = target.replace('\n', ' ');
		target = target.replace('\r', ' ');		return target;
	}
  
}
