/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *     "Apache Jetspeed" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache" or
 *    "Apache Jetspeed", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
package org.apache.jetspeed.portal.portlets.viewprocessor;

// Ecs
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;

// Jetspeed portal
import org.apache.jetspeed.portal.Portlet;
import org.apache.jetspeed.portal.portlets.GenericMVCContext;
import org.apache.jetspeed.services.TemplateLocator;
import org.apache.jetspeed.services.Registry;
import org.apache.jetspeed.om.registry.PortletEntry;
import org.apache.jetspeed.util.servlet.EcsServletElement;
import org.apache.jetspeed.util.ServiceUtil;

// Turbine stuff
import org.apache.turbine.services.jsp.JspService;
import org.apache.turbine.util.Log;

// Turbine util
import org.apache.turbine.util.RunData;

//java stuff
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.RequestDispatcher;

/**
 * <b>JspViewProcessor</b> - MVC processor for serving jsp files.
 * <p>
 * The .jsp file location may be specified in two different ways:
 * <li><b>using the "template" parameter</b> - the JspTemplateService will search portlets and then screens 
 * folder to locate the appropriate template. The template must be specifed in the "template" 
 * portlet parameter.
 * <li><b>using relative url</b> - the .jsp template will be served directly bypassing the 
 * JspTemplateService. The template must be specifed in the portlet url property. 
 * Example: /html/welcome.jsp.
 * <P>
 * 
 * @author <a href="mailto:tkuebler@cisco.com">Tod Kuebler</a>
 * @author <a href="mailto:weaver@apache.org">Scott Weaver</a>
 * @author <a href="mailto:morciuch@apache.org">Mark Orciuch</a>
 * @version $Id: $
 */
public class JSPViewProcessor
implements ViewProcessor
{

    /** Creates a new instance of JSPViewProcessor */
    public JSPViewProcessor()
    {
    }

    public Object processView(GenericMVCContext context)
    {

        Portlet portlet = (Portlet) context.get("portlet");
        RunData data = (RunData) context.get("data");
        HttpServletRequest request = data.getRequest();
        String template = (String) context.get("template");
        Log.info("JSPViewProcessor - processing template " + template);

        try
        {

            // Allow access to portlet from .jsp template
            request.setAttribute("portlet", portlet);

            // put context in attribute so you can get to it from .jsp template
            request.setAttribute("context", context);

            // Add js_peid out of convenience
            request.setAttribute("js_peid", portlet.getID());

            // Add rundata out of convenience (JspService.RUNDATA differs from GenericMVCPortlet.RUNDATA)
            request.setAttribute(JspService.RUNDATA, data);

            // Retrieve the URL. For backward compatibility, use the URL first 
            // and then fallback to "template" parameter
            PortletEntry pe = (PortletEntry) Registry.getEntry(Registry.PORTLET, portlet.getName());

            // Files referenced from default templates folder will be processed
            // using JspService. Otherwise, they will be loaded using EcsServletElement
            // from where ever they came from.
            if (pe.getURL() == null || pe.getURL().trim().length() == 0)
            {

                if (template != null && -1 == template.indexOf(".jsp"))
                {
                    template = template + ".jsp";
                }

                Log.info("JSPViewProcessor - locating template - " + data.toString() 
                         + " - " + template);

                //we use the template locator to translate the template
                String locatedTemplate = TemplateLocator.locatePortletTemplate(data, template);
                Log.info("JSPViewProcessor - located template: " + locatedTemplate);

                /*if (locatedTemplate == null)
                {
                    locatedTemplate = TemplateLocator.locateScreenTemplate(data, template);
                    if (locatedTemplate != null)
                    {
                        locatedTemplate = "/screens" + locatedTemplate;
                    }
                    Log.debug("JSPViewProcessor - located screen template: " + locatedTemplate);
                } */

                JspService service = (JspService) ServiceUtil.getServiceByName(JspService.SERVICE_NAME);

                // this is only necessary if we don't run in a JSP page environment
                // but better be safe than sorry...
                service.addDefaultObjects(data);

                // handle request
                service.handleRequest(data, locatedTemplate);

            }
            else
            {
                // Build parameter list to be passed with the jsp
                Iterator names = portlet.getPortletConfig().getInitParameterNames();
                while (names.hasNext()) 
                {
                    String name = (String) names.next();
                    String value = (String) portlet.getPortletConfig().getInitParameter(name);
                    data.getParameters().setString(name, value);
                }

                template = pe.getURL();

                if (Log.getLogger().isDebugEnabled())
                {
                    Log.debug("JSPViewProcessor - serving jsp directly using: " + template);
                }

                // get the RequestDispatcher for the JSP
                RequestDispatcher dispatcher = data.getServletContext().getRequestDispatcher(template);
                data.getOut().flush();
                dispatcher.include(data.getRequest(), data.getResponse());
            }

        }
        catch (Exception e)
        {

            String message = "JSPViewProcessor: Could not include the following JSP Page:  [" + template + "] :\n\t" 
                             + e.getMessage();
            Log.error(message, e);

            return new StringElement(message);
        }

        return new ElementContainer();
    }

    /** Process the template passed in the context
     * (context.get("template")).  Invoked by the GenericMVCPortlet
     * after action handling to process the template type
     * in question.
     *
     */
    public void init(Portlet portlet)
    {
    }
}
