import org.apache.commons.jelly.JellyContext;
import org.apache.commons.jelly.XMLOutput;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class JellyServlet extends HttpServlet
{
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        doRequest(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        doRequest(request, response);
    }

    protected void doRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {
        JellyContext context = createContext(req, res);
        String template = getTemplate(req);
        runScript(new File(template), context, res);
    }

    protected JellyContext createContext(HttpServletRequest req, HttpServletResponse res)
    {
        return new JellyContext();
    }

    protected String getTemplate(HttpServletRequest req)
    {
        return req.getParameter("template");
    }

    protected void runScript(File script, JellyContext context, HttpServletResponse res)
            throws IOException, UnsupportedEncodingException
    {
        ServletOutputStream output = res.getOutputStream();
        XMLOutput xmlOutput = XMLOutput.createXMLOutput(output);
        try
        {
            context.runScript(script, xmlOutput);
        }
        catch (Exception e)
        {
            e.printStackTrace(res.getWriter());
        }
        xmlOutput.flush();
        xmlOutput.close();
        output.flush();
    }
}
