/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@objectweb.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.objectweb.jonas.webapp.jonasadmin.service.container;

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

import javax.management.MalformedObjectNameException;
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.objectweb.jonas.jmx.J2eeObjectName;
import org.objectweb.jonas.jmx.JonasManagementRepr;
import org.objectweb.jonas.webapp.jonasadmin.JonasAdminJmx;
import org.objectweb.jonas.webapp.jonasadmin.JonasBaseAction;
import org.objectweb.jonas.webapp.jonasadmin.WhereAreYou;
import org.objectweb.jonas.webapp.jonasadmin.service.ejb.EjbItem;
import org.objectweb.jonas.webapp.jonasadmin.service.ejb.EjbItemByNameComparator;

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

public class EditContainerAction extends JonasBaseAction {

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

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

          // Current server
        WhereAreYou oWhere = (WhereAreYou) p_Request.getSession().getAttribute(WhereAreYou.
                SESSION_NAME);
        String serverName = oWhere.getCurrentJonasServerName();

        // Selected container
        String sObjectName = p_Request.getParameter("select");
        if (sObjectName == null) {
            // Accept request attribute forced by a EditEjbAction
            sObjectName = (String) p_Request.getAttribute("select");
        }
        // Get next forward if the access is throught a ejb else by default is null
        String sNextForward = (String) p_Request.getAttribute("NextForward");

        // Determine the ObjectName of the managed container (module)
        ObjectName oObjectName = null;
        try {
            if (sNextForward != null) {
                oObjectName = getModuleObjectName(sObjectName);
            } else {
                oObjectName = new ObjectName(sObjectName);
            }
        } catch (Throwable t) {
            addGlobalError(t);
            saveErrors(p_Request, m_Errors);
            return (p_Mapping.findForward("Global Error"));
        }

        // Form used
        ContainerForm oForm = null;
        String sPath = null;
        // Build a new form
        if (oObjectName != null) {
            oForm = new ContainerForm();
            oForm.reset(p_Mapping, p_Request);
            m_Session.setAttribute("containerForm", oForm);
            sPath = getStringAttribute(oObjectName, "fileName");

            oForm.setPath(sPath);
            oForm.setFilename(JonasAdminJmx.extractFilename(sPath));

            oForm.setInEar(getBooleanAttribute(oObjectName, "inEarCase"));
            oForm.setEarPath((URL) JonasManagementRepr.getAttribute(oObjectName, "earURL", serverName));
            oForm.setEarON((String) JonasManagementRepr.getAttribute(oObjectName, "earON", serverName));
        }
        else {
            // Used last form in session
            oForm = (ContainerForm) m_Session.getAttribute("containerForm");
        }

        // Force the node selected in tree only when no next forward
        if (sNextForward == null) {
            m_WhereAreYou.selectNameNode(getTreeBranchName(DEPTH_SERVER)
                + WhereAreYou.NODE_SEPARATOR + "services" + WhereAreYou.NODE_SEPARATOR
                + "ejbContainers" + WhereAreYou.NODE_SEPARATOR + oForm.getFilename(), true);
        }

        // Populate
        if (oObjectName != null) {
            try {
                oForm.setContainerName(getStringAttribute(oObjectName, "containerName"));
                oForm.setCurrentNumberOfMDBType(getIntegerAttribute(oObjectName
                    , "currentNumberOfMDB"));
                oForm.setCurrentNumberOfSBFType(getIntegerAttribute(oObjectName
                    , "currentNumberOfSBF"));
                oForm.setCurrentNumberOfBMPType(getIntegerAttribute(oObjectName
                    , "currentNumberOfBMP"));
                oForm.setCurrentNumberOfSBLType(getIntegerAttribute(oObjectName
                    , "currentNumberOfSBL"));
                oForm.setCurrentNumberOfCMPType(getIntegerAttribute(oObjectName
                    , "currentNumberOfCMP"));
                oForm.setCurrentNumberOfBeanType(getIntegerAttribute(oObjectName
                    , "currentNumberOfEJB"));
                // Prepare Ejb list in this container
                searchEjbs(oForm, sPath, oObjectName, serverName);
            }
            catch (Throwable t) {
                addGlobalError(t);
                saveErrors(p_Request, m_Errors);
                return (p_Mapping.findForward("Global Error"));
            }
        }

        // Replace the normal forward if exists
        if (sNextForward == null) {
            sNextForward = "Container";
        }
        // Forward to the jsp
        return (p_Mapping.findForward(sNextForward));
    }

    protected void searchEjbs(ContainerForm p_Form, String p_Path, ObjectName p_ObjectName, String serverName)
        throws Exception {
        String sName;
        String sTypeResource;
        Iterator itNames;
        ArrayList al = new ArrayList();
        String p_DomainName = p_ObjectName.getDomain();
        String p_ServerName = p_ObjectName.getKeyProperty("J2EEServer");
        String p_moduleName = p_ObjectName.getKeyProperty("name");

        ObjectName on = J2eeObjectName.getEntityBeans(p_DomainName, p_moduleName, p_ServerName);
        itNames = JonasAdminJmx.getListMbean(on, serverName).iterator();
        while (itNames.hasNext()) {
            al.add(new EjbItem((ObjectName) itNames.next(), p_ServerName));
        }
        on = J2eeObjectName.getStatefulSessionBeans(p_DomainName, p_moduleName, p_ServerName);
        itNames = JonasAdminJmx.getListMbean(on, serverName).iterator();
        while (itNames.hasNext()) {
            al.add(new EjbItem((ObjectName) itNames.next(), p_ServerName));
        }
        on = J2eeObjectName.getStatelessSessionBeans(p_DomainName, p_moduleName, p_ServerName);
        itNames = JonasAdminJmx.getListMbean(on, serverName).iterator();
        while (itNames.hasNext()) {
            al.add(new EjbItem((ObjectName) itNames.next(), p_ServerName));
        }
        on = J2eeObjectName.getMessageDrivenBeans(p_DomainName, p_moduleName, p_ServerName);
        itNames = JonasAdminJmx.getListMbean(on, serverName).iterator();
        while (itNames.hasNext()) {
            al.add(new EjbItem((ObjectName) itNames.next(), p_ServerName));
        }

        // Sort by name
        Collections.sort(al, new EjbItemByNameComparator());
        // Save in form
        p_Form.setEjbs(al);
    }

    ObjectName getModuleObjectName(String ejbObjectName) throws MalformedObjectNameException {
        ObjectName o_ejbObjectName = new ObjectName(ejbObjectName);
        String domainName = o_ejbObjectName.getDomain();
        String moduleName = o_ejbObjectName.getKeyProperty("EJBModule");
        String serverName = o_ejbObjectName.getKeyProperty("J2EEServer");
        String appName = o_ejbObjectName.getKeyProperty("J2EEApplication");
        return J2eeObjectName.getEJBModule(domainName, serverName, appName, moduleName);
    }
}
