package org.ajax4jsf.portlet;

import java.io.IOException;

import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AjaxFacesServlet extends AbstractAjaxBridge implements Servlet {

	private ServletConfig config;

	@Override
	protected Object getContext() {
		return config.getServletContext();
	}

	@Override
	protected String getInitParameter(String name) {
		// TODO Auto-generated method stub
		return config.getServletContext().getInitParameter(name);
	}

	public ServletConfig getServletConfig() {
		return config;
	}

	public String getServletInfo() {
		return (this.getClass().getName());
	}

	public void init(ServletConfig config) throws ServletException {
		this.config = config;
		try {
			init();
		} catch (FacesException e) {
			throw new ServletException(e);
		}
	}

	public void service(ServletRequest req, ServletResponse res)
			throws ServletException, IOException {
		HttpServletRequest httpRequest = (HttpServletRequest) req;
		String pathInfo = httpRequest.getPathInfo();
		// Protect hidden directories
        if (pathInfo != null) {
            pathInfo = pathInfo.toUpperCase();
            if (pathInfo.startsWith("/WEB-INF/")
                || pathInfo.equals("/WEB-INF")
                || pathInfo.startsWith("/META-INF/")
                || pathInfo.equals("/META-INF")) {
                ((HttpServletResponse) res).
                      sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        }    
        FacesContext context = getFacesContext(req, res);
        // Execute the request processing lifecycle for this request
        try {
            execute(context);
            // Save request - scope information for a portlet render phase.
            render(context);
        } catch (FacesException e) {
            Throwable t = e.getCause();
            if (t == null) {
                throw new ServletException(e.getMessage(), e);
            } else {
                if (t instanceof ServletException) {
                    throw ((ServletException) t);
                } else if (t instanceof IOException) {
                    throw ((IOException) t);
                } else {
                    throw new ServletException(t.getMessage(), t);
                }
            }
        }
        finally {
            // Release the FacesContext instance for this request
            context.release();
        }
	}

}
