/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.webapp.jonasadmin.service.container;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;

import javax.management.ObjectName;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.ow2.jonas.lib.management.extensions.base.JonasManagementRepr;
import org.ow2.jonas.lib.management.javaee.J2eeObjectName;
import org.ow2.jonas.lib.util.JonasObjectName;
import org.ow2.jonas.webapp.jonasadmin.JettyObjectName;
import org.ow2.jonas.webapp.jonasadmin.JonasAdminJmx;
import org.ow2.jonas.webapp.jonasadmin.JonasBaseAction;
import org.ow2.jonas.webapp.jonasadmin.WhereAreYou;


/**
 * @author Michel-Ange ANTON
 */

public class ListWebContainersAction extends JonasBaseAction {

// --------------------------------------------------------- Public Methods

    @Override
    public ActionForward executeAction(final ActionMapping p_Mapping, final ActionForm p_Form
        , final HttpServletRequest p_Request, final HttpServletResponse p_Response)
        throws IOException, ServletException {

        // Force the node selected in tree
        m_WhereAreYou.selectNameNode(getTreeBranchName(DEPTH_SERVER) + WhereAreYou.NODE_SEPARATOR
            + "services" + WhereAreYou.NODE_SEPARATOR + "web", true);
        // Force the deployment type to use the refreshing method
        m_WhereAreYou.setCurrentJonasDeploymentType(WhereAreYou.DEPLOYMENT_WAR);
        // Delete last list if used
        m_Session.removeAttribute("itemsWebContainersForm");

        String s_refresh = (String) p_Request.getParameter("refresh");
        boolean refresh = Boolean.valueOf(s_refresh).booleanValue();
        
        // no Form used
        try {
            String domainName = m_WhereAreYou.getCurrentDomainName();
            String serverName = m_WhereAreYou.getCurrentJonasServerName();

            if (refresh) {
                refreshServicesTree(p_Request);
            }
            
            ArrayList al = new ArrayList();
            ObjectName on;
            String sPathContext;
            HashMap hWebAppItems = new HashMap();

            // Get the list of Catalina contexts
            if (m_WhereAreYou.isCatalinaServer()) {
                WebAppItem oItem;
                //String p_serverName = m_WhereAreYou.getAdminJonasServerName();
                ObjectName onContainers = J2eeObjectName.getWebModules(domainName, serverName);
                Iterator itOns = JonasAdminJmx.getListMbean(onContainers, serverName).iterator();
                while (itOns.hasNext()) {
                    ObjectName onWebModule = (ObjectName) itOns.next();
                    oItem = new WebAppItem(onWebModule, m_WhereAreYou.getCurrentCatalinaDefaultHostName());
                    try {
                        String webModulePath = ((URL) JonasManagementRepr.getAttribute(onWebModule, "warURL", serverName)).toString();
                        String sFile = JonasAdminJmx.extractFilename(webModulePath);
                        oItem.setFile(sFile);
                        oItem.setPath(webModulePath);
                    } catch(Exception e) {
                        oItem.setFile("");
                        oItem.setPath("");
                    }
                    hWebAppItems.put(oItem.getLabelPathContext(), oItem);
                }
            } else if (m_WhereAreYou.isJettyServer()) {
                // Get the list of Jetty contexts
                Iterator itOnContexts = JonasAdminJmx.getListMbean(JettyObjectName.jettyContexts(domainName), serverName).
                    iterator();
                while (itOnContexts.hasNext()) {
                    on = (ObjectName) itOnContexts.next();
                    sPathContext = on.getKeyProperty("context");
                    if (sPathContext != null) {
                        if (!hWebAppItems.containsKey(sPathContext) && on.getKeyProperty("WebApplicationContext") != null &&
                            on.getKeyProperty("WebApplicationHandler") == null && on.getKeyProperty("config") == null) {
                            hWebAppItems.put(sPathContext, new WebAppItem(sPathContext, on.toString()));
                        }
                    }
                }

                // Get the list of JOnAS War
                /* This code is only executed with Jetty because the transfere
                * of management attributes from 'War' MBeans to JettyMBeans is
                * not done yet
                */
                String sPath;
                String sFile;
                WebAppItem oWeb;
                Iterator itOnWars = JonasAdminJmx.getListMbean(JonasObjectName.allWars(domainName), serverName).iterator();
                while (itOnWars.hasNext()) {
                    on = (ObjectName) itOnWars.next();
                    sPath = on.getKeyProperty("fname");
                    sFile = JonasAdminJmx.extractFilename(sPath);
                    sPathContext = getStringAttribute(on, "ContextRoot");
                    if (sPathContext.charAt(0) != '/') {
                        sPathContext = "/" + sPathContext;
                    }
                    oWeb = (WebAppItem) hWebAppItems.get(sPathContext);
                    if (oWeb != null) {
                        oWeb.setFile(sFile);
                        oWeb.setPath(sPath);
                    }
                }
            }

            // Prepare to display and sort
            al.addAll(hWebAppItems.values());
            Collections.sort(al, new WebAppItemByPathContext());

            // Set list in the request
            p_Request.setAttribute("listWebContainers", al);
        } catch (Throwable t) {
            addGlobalError(t);
            saveErrors(p_Request, m_Errors);
            return (p_Mapping.findForward("Global Error"));
        }
        // Forward to the jsp.
        return (p_Mapping.findForward("Web Containers"));
    }
}
