import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.faceless.report.*;
import org.xml.sax.*;

/**
 * A sample servlet which loads an XML file from a URL and turns
 * it into a PDF. If you have a Servlet 2.3 container like Tomcat 4, the
 * PDFFilter is a simpler option.
 *
 * Most of the work for this is encapsulated in the PDFProxyServlet class,
 * and the only thing we absolutely have to implement is the getProxyURL()
 * method, which returns the URL of the XML report to convert.
 *
 * In this simple example, we take the report from "PathInfo" field of the
 * request - this is any part of the request URL that comes after the
 * "/servlet/SampleServlet" prefix. An example request would be:
 *
 *   http://www.company.com/servlet/SampleServlet/path/to/test.xml
 *
 * This will proxy the request to "http://www.company.com/path/to/test.xml"
 *
 * For more complex requirements, the PDFProxyServlet class can be replaced
 * with a home-grown equivalent - the source is supplied with this package.
 *
 *
 * Note that we really DO NOT recommend using this *exact* example in a live
 * environment. There are many things to consider, including:
 *
 *  * masking the URL of the final document from the customer, for security
 *
 *  * preventing the XML report from being run unless it's called from
 *    this servlet, for security (hint: Check the "X-Proxy" headers and the IP)
 *
 *  * enabling search engines (OK, just Google currently) to read and store
 *    the PDF documents - a search engine won't pick it up if the URL has
 *    a query string, like this example.
 *
 *
 * Finally, if the servlet doesn't run because it can't find the SAX parser,
 * add the "org.xml.sax.driver" parameter in it's initialization parameters
 * (in "WEB-INF/web.xml"). The value should be the classname of your SAX parser.
 *
 * $Id: SampleServlet.java 10482 2009-07-10 09:53:38Z chris $
 */
public class SampleServlet extends PDFProxyServlet
{
    public String getProxyURL(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
    {
	String dest = req.getPathInfo();
	if (req.getQueryString()!=null) dest += "?"+req.getQueryString();
	URL thisurl = new URL(HttpUtils.getRequestURL(req).toString());

        try {
            if (dest==null) throw new MalformedURLException();
            URL url = new URL(thisurl, res.encodeURL(dest));
            System.err.println("PDF REPORT: Proxying request to "+url);
	    return url.toString();
        } catch (MalformedURLException e) {
            res.sendError(404, "Illegal URL \""+dest+"\"");
	    return null;
        }
    }
}
