/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 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.deploy;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;

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

import org.ow2.jonas.lib.management.extensions.base.JonasManagementRepr;
import org.ow2.jonas.lib.management.extensions.manager.ManagementEntryPoint;
import org.ow2.jonas.lib.management.javaee.J2eeObjectName;
import org.ow2.jonas.lib.util.JonasObjectName;
import org.ow2.jonas.lib.util.JoramObjectName;
import org.ow2.jonas.webapp.jonasadmin.JonasAdminJmx;
import org.ow2.jonas.webapp.jonasadmin.JonasBaseAction;
import org.ow2.jonas.webapp.jonasadmin.JonasTreeBuilder;
import org.ow2.jonas.webapp.jonasadmin.WhereAreYou;
import org.ow2.jonas.webapp.taglib.TreeControl;
import org.ow2.jonas.webapp.taglib.TreeControlNode;


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

abstract public class BaseDeployAction extends JonasBaseAction {

// --------------------------------------------------------- Protected Methods

    protected int getCurrentJonasDeployment()
        throws Exception {
        int iRet = 0;
        iRet = m_WhereAreYou.getCurrentJonasDeploymentType();
        return iRet;
    }

    protected void setCurrentJonasDeployment(final HttpServletRequest p_Request)
        throws Exception {
        int iDeployment = 0;
        String sDeployment = p_Request.getParameter("type");
        if (sDeployment != null) {
            // Dispatch
            if (sDeployment.equals(WhereAreYou.DEPLOYMENT_STRING)) {
                iDeployment = WhereAreYou.DEPLOYMENT;
            } else if (sDeployment.equals(WhereAreYou.DEPLOYMENT_STRING_EAR)) {
                iDeployment = WhereAreYou.DEPLOYMENT_EAR;
            } else if (sDeployment.equals(WhereAreYou.DEPLOYMENT_STRING_JAR)) {
                iDeployment = WhereAreYou.DEPLOYMENT_JAR;
            } else if (sDeployment.equals(WhereAreYou.DEPLOYMENT_STRING_WAR)) {
                iDeployment = WhereAreYou.DEPLOYMENT_WAR;
            } else if (sDeployment.equals(WhereAreYou.DEPLOYMENT_STRING_RAR)) {
                iDeployment = WhereAreYou.DEPLOYMENT_RAR;
            } else if (sDeployment.equals(WhereAreYou.DEPLOYMENT_STRING_DATASOURCE)) {
                iDeployment = WhereAreYou.DEPLOYMENT_DATASOURCE;
            } else if (sDeployment.equals(WhereAreYou.DEPLOYMENT_STRING_MAILFACTORY)) {
                iDeployment = WhereAreYou.DEPLOYMENT_MAIL;
            } else if (sDeployment.equals(WhereAreYou.DOMAIN_DEPLOYMENT_STRING)) {
                iDeployment = WhereAreYou.DOMAIN_DEPLOYMENT;
            } else if (sDeployment.equals(WhereAreYou.DOMAIN_DEPLOYMENT_STRING_EAR)) {
                iDeployment = WhereAreYou.DOMAIN_DEPLOYMENT_EAR;
            } else if (sDeployment.equals(WhereAreYou.DOMAIN_DEPLOYMENT_STRING_JAR)) {
                iDeployment = WhereAreYou.DOMAIN_DEPLOYMENT_JAR;
            } else if (sDeployment.equals(WhereAreYou.DOMAIN_DEPLOYMENT_STRING_WAR)) {
                iDeployment = WhereAreYou.DOMAIN_DEPLOYMENT_WAR;
            } else if (sDeployment.equals(WhereAreYou.DOMAIN_DEPLOYMENT_STRING_RAR)) {
                iDeployment = WhereAreYou.DOMAIN_DEPLOYMENT_RAR;
            } else {
                throw new Exception("Unknown type deployment");
            }
            // Storing
            m_WhereAreYou.setCurrentJonasDeploymentType(iDeployment);
        }
    }

    /**
     * Return the edit forward string.
     *
     * @return The edit forward string
     */
    protected String getForwardEdit() {
        String sForward = null;
        try {
            switch (getCurrentJonasDeployment()) {
                case WhereAreYou.DEPLOYMENT:
                case WhereAreYou.DEPLOYMENT_EAR:
                case WhereAreYou.DEPLOYMENT_JAR:
                case WhereAreYou.DEPLOYMENT_WAR:
                case WhereAreYou.DEPLOYMENT_RAR:
                    sForward = "Deploy";
                    break;
                case WhereAreYou.DOMAIN_DEPLOYMENT_EAR:
                case WhereAreYou.DOMAIN_DEPLOYMENT_JAR:
                case WhereAreYou.DOMAIN_DEPLOYMENT_WAR:
                case WhereAreYou.DOMAIN_DEPLOYMENT_RAR:
                case WhereAreYou.DOMAIN_DEPLOYMENT:
                    sForward = "Domain Deploy";
                    break;
                case WhereAreYou.DEPLOYMENT_DATASOURCE:
                    sForward = "Deploy Datasource";
                    break;
                case WhereAreYou.DEPLOYMENT_MAIL:
                    sForward = "Deploy Mail Factory";
                    break;
            }
        }
        catch (Exception e) {
            // none
        }
        return sForward;
    }

    protected boolean isDomain() {
        boolean result = false;
        try {
            switch (getCurrentJonasDeployment()) {
            case WhereAreYou.DOMAIN_DEPLOYMENT_EAR:
            case WhereAreYou.DOMAIN_DEPLOYMENT_JAR:
            case WhereAreYou.DOMAIN_DEPLOYMENT_WAR:
            case WhereAreYou.DOMAIN_DEPLOYMENT_RAR:
                result = true;
                break;
            }
        } catch (Exception e) {
            // none
        }
        return result;
    }

    protected boolean isConfigurable() {
        boolean result = false;
        try {
            switch (getCurrentJonasDeployment()) {
            case WhereAreYou.DOMAIN_DEPLOYMENT_RAR:
            case WhereAreYou.DEPLOYMENT_RAR:
                result = true;
                break;
            }
        } catch (Exception e) {
            // none
        }
        return result;
    }

    protected boolean isModule() {
        boolean result = false;
        try {
            switch (getCurrentJonasDeployment()) {
            case WhereAreYou.DEPLOYMENT_JAR:
            case WhereAreYou.DEPLOYMENT_WAR:
            case WhereAreYou.DEPLOYMENT_EAR:
            case WhereAreYou.DEPLOYMENT_RAR:
            case WhereAreYou.DEPLOYMENT:
                result = true;
                break;
            }
        } catch (Exception e) {
            // none
        }
        return result;
    }

    protected String getDomainDeploymentMethodName() {
        String result = "";
        try {
            switch (getCurrentJonasDeployment()) {
            case WhereAreYou.DOMAIN_DEPLOYMENT_EAR:
                result = "deployEar";
                break;
            case WhereAreYou.DOMAIN_DEPLOYMENT_JAR:
                result = "deployJar";
                break;
            case WhereAreYou.DOMAIN_DEPLOYMENT_WAR:
                result = "deployWar";
                break;
            case WhereAreYou.DOMAIN_DEPLOYMENT_RAR:
                result = "deployRar";
                break;
            }
        } catch (Exception e) {
            // none
        }
        return result;
    }

    protected String getDomainUploadDeployMethodName() {
        String result = "";
        try {
            switch (getCurrentJonasDeployment()) {
            case WhereAreYou.DOMAIN_DEPLOYMENT_EAR:
                result = "uploadDeployEar";
                break;
            case WhereAreYou.DOMAIN_DEPLOYMENT_JAR:
                result = "uploadDeployJar";
                break;
            case WhereAreYou.DOMAIN_DEPLOYMENT_WAR:
                result = "uploadDeployWar";
                break;
            case WhereAreYou.DOMAIN_DEPLOYMENT_RAR:
                result = "uploadDeployRar";
                break;
            }
        } catch (Exception e) {
            // none
        }
        return result;
    }

    /**
     * Return the list of deployable files in using the type of current
     * deployment storing in WhereAreYou instance in session.
     *
     * @return The list of deployable files
     * @throws Exception
     */
    protected ArrayList getListDeployableFiles()
        throws Exception {
        ArrayList al = null;
        String serverName = m_WhereAreYou.getCurrentJonasServerName();
        String domainName = m_WhereAreYou.getCurrentDomainName();
        switch (getCurrentJonasDeployment()) {
            case WhereAreYou.DEPLOYMENT:
                al = JonasAdminJmx.getFilesDeployable(domainName, serverName);
                break;
            case WhereAreYou.DEPLOYMENT_EAR:
                al = JonasAdminJmx.getEarFilesDeployable(domainName, serverName);
                break;
            case WhereAreYou.DEPLOYMENT_RAR:
                al = JonasAdminJmx.getRarFilesDeployable(domainName, serverName);
                break;
            case WhereAreYou.DEPLOYMENT_JAR:
                al = JonasAdminJmx.getJarFilesDeployable(domainName, serverName);
                break;
            case WhereAreYou.DEPLOYMENT_WAR:
                al = JonasAdminJmx.getWarFilesDeployable(domainName, serverName);
                break;
            case WhereAreYou.DOMAIN_DEPLOYMENT:
                al = JonasAdminJmx.getFilesDeployable(domainName, serverName);
                break;
            case WhereAreYou.DOMAIN_DEPLOYMENT_EAR:
                al = JonasAdminJmx.getEarFilesDeployable(domainName, serverName);
                al.addAll(JonasAdminJmx.getEarFilesDeployed(domainName, serverName));
                break;
            case WhereAreYou.DOMAIN_DEPLOYMENT_JAR:
                al = JonasAdminJmx.getJarFilesDeployable(domainName, serverName);
                al.addAll(JonasAdminJmx.getJarFilesDeployed(domainName, serverName));
                break;
            case WhereAreYou.DOMAIN_DEPLOYMENT_WAR:
                al = JonasAdminJmx.getWarFilesDeployable(domainName, serverName);
                al.addAll(JonasAdminJmx.getWarFilesDeployed(domainName, serverName));
                break;
            case WhereAreYou.DOMAIN_DEPLOYMENT_RAR:
                al = JonasAdminJmx.getRarFilesDeployable(domainName, serverName);
                al.addAll(JonasAdminJmx.getRarFilesDeployed(domainName, serverName));
                break;
            case WhereAreYou.DEPLOYMENT_DATASOURCE:
                al = JonasAdminJmx.getDatasourceFilesDeployable(domainName, serverName);
                break;
            case WhereAreYou.DEPLOYMENT_MAIL:
                al = JonasAdminJmx.getMailFilesDeployable(domainName, serverName);
                break;
        }
        return al;
    }

    /**
     * Return the list of deployed files in using the type of current deployment
     * storing in WhereAreYou instance in session.
     *
     * @return The list of deployed files
     * @throws Exception
     */
    protected ArrayList getListDeployedFiles()
        throws Exception {
        String serverName = m_WhereAreYou.getCurrentJonasServerName();
        String domainName = m_WhereAreYou.getCurrentDomainName();
        ArrayList al = null;
        switch (getCurrentJonasDeployment()) {
            case WhereAreYou.DEPLOYMENT:
                al = JonasAdminJmx.getFilesDeployed(domainName, serverName);
                break;
            case WhereAreYou.DEPLOYMENT_EAR:
                al = JonasAdminJmx.getEarFilesDeployed(domainName, serverName);
                break;
            case WhereAreYou.DEPLOYMENT_RAR:
                al = JonasAdminJmx.getRarFilesDeployed(domainName, serverName);
                break;
            case WhereAreYou.DEPLOYMENT_JAR:
                al = JonasAdminJmx.getJarFilesDeployed(domainName, serverName);
                break;
            case WhereAreYou.DEPLOYMENT_WAR:
                al = JonasAdminJmx.getWarFilesDeployed(domainName, serverName);
                break;
            case WhereAreYou.DOMAIN_DEPLOYMENT:
                al = JonasAdminJmx.getFilesDeployed(domainName, serverName);
                break;
            case WhereAreYou.DOMAIN_DEPLOYMENT_EAR:
                al = JonasAdminJmx.getEarFilesDeployed(domainName, serverName);
                break;
            case WhereAreYou.DOMAIN_DEPLOYMENT_JAR:
                al = JonasAdminJmx.getJarFilesDeployed(domainName, serverName);
                break;
            case WhereAreYou.DOMAIN_DEPLOYMENT_WAR:
                al = JonasAdminJmx.getWarFilesDeployed(domainName, serverName);
                break;
            case WhereAreYou.DOMAIN_DEPLOYMENT_RAR:
                al = JonasAdminJmx.getRarFilesDeployed(domainName, serverName);
                break;
            case WhereAreYou.DEPLOYMENT_DATASOURCE:
                al = JonasAdminJmx.getDatasourceFilesDeployed(domainName, serverName);
                break;
            case WhereAreYou.DEPLOYMENT_MAIL:
                al = JonasAdminJmx.getMailFilesDeployed(m_WhereAreYou);
                break;
        }
        return al;
    }

    /**
     * Undeploy a file in using the type of current deployment
     * storing in WhereAreYou instance in session.
     *
     * @param p_Filename Name of file to undeploy
     * @throws Exception could not undeploy
     */
    protected void undeploy(final String p_Filename)
        throws Exception {
        String[] asParam = new String[1];
        asParam[0] = p_Filename;
        String serverName = m_WhereAreYou.getCurrentJonasServerName();
        String op = "undeploy";
        switch (getCurrentJonasDeployment()) {
            case WhereAreYou.DEPLOYMENT_EAR:
            case WhereAreYou.DEPLOYMENT_JAR:
            case WhereAreYou.DEPLOYMENT_WAR:
            case WhereAreYou.DEPLOYMENT_RAR:
            case WhereAreYou.DEPLOYMENT:
                undeployModule(p_Filename, serverName);
                break;
            case WhereAreYou.DEPLOYMENT_DATASOURCE:
                undeployDataSource(p_Filename);
                break;
            case WhereAreYou.DEPLOYMENT_MAIL:
                undeployMailFactory(m_WhereAreYou.getCurrentDomainName(), p_Filename);
                break;
        }
    }

    protected boolean isDeployment(final String p_Filename) throws Exception {
        switch (getCurrentJonasDeployment()) {
            case WhereAreYou.DEPLOYMENT:
                return true;
        }
        return false;
    }
    /**
     * Undeploy a datasource file.
     *
     * @param p_Filename Name of file to undeploy
     * @throws Exception
     */
    protected void undeployDataSource(final String p_Filename)
        throws Exception {
        String serverName = m_WhereAreYou.getCurrentJonasServerName();
        String domainName = m_WhereAreYou.getCurrentDomainName();
        ArrayList al = JonasAdminJmx.getDatasourceDependences(p_Filename
                , m_WhereAreYou.getCurrentDomainName()
                , m_WhereAreYou.getCurrentJonasServerName());
        if (al.size() == 0) {
            String[] asParam = new String[1];
            asParam[0] = p_Filename;
            String[] asSignature = new String[1];
            asSignature[0] = "java.lang.String";
            JonasManagementRepr.invoke(JonasObjectName.databaseService(domainName), "unloadDataSource"
                , asParam, asSignature, serverName);
        }
        else {
            throw new Exception(m_Resources.getMessage("error.undeploy.datasource.dependences"
                , al.toString()));
        }
    }

    /**
     * Undeploy a mail factory.
     *
     * @param p_Filename Name of the factory (same as the props file name configuring it)
     * @throws Exception
     */
    protected void undeployMailFactory(final String domainName, final String p_Filename)
        throws Exception {
        String serverName = m_WhereAreYou.getCurrentJonasServerName();
        ArrayList al = JonasAdminJmx.getMailFactoryDependences(p_Filename, m_WhereAreYou);
        if (al.size() == 0) {
            String[] asParam = new String[1];
            asParam[0] = p_Filename;
            String[] asSignature = new String[1];
            asSignature[0] = "java.lang.String";
            JonasManagementRepr.invoke(JonasObjectName.mailService(domainName), "unbindMailFactoryMBean"
                , asParam, asSignature, serverName);
        }
        else {
            throw new Exception(m_Resources.getMessage("error.undeploy.mailfactory.dependences"
                , al.toString()));
        }
    }

    /**
     * Deploy a file in using the type of current deployment
     * storing in WhereAreYou instance in session.
     *
     * @param p_Filename Name of file to deploy
     * @throws Exception could not deploy
     */
    protected void deploy(final String p_Filename)
        throws Exception {
        String[] asParam = new String[1];
        asParam[0] = p_Filename;
        String[] asSignature = new String[1];
        asSignature[0] = "java.lang.String";

        String serverName = m_WhereAreYou.getCurrentJonasServerName();
        switch (getCurrentJonasDeployment()) {
        case WhereAreYou.DEPLOYMENT_EAR:
        case WhereAreYou.DEPLOYMENT_JAR:
        case WhereAreYou.DEPLOYMENT_WAR:
        case WhereAreYou.DEPLOYMENT_RAR:
        case WhereAreYou.DEPLOYMENT:
            deployModule(p_Filename, serverName);
            break;
        case WhereAreYou.DEPLOYMENT_DATASOURCE:
            deployDataSource(p_Filename);
            break;
        case WhereAreYou.DEPLOYMENT_MAIL:
            deployMailFactory(m_WhereAreYou.getCurrentDomainName(), p_Filename);
            break;
        }
    }
    
    /**
     * Deploy a datasource file.
     *
     * @param p_Filename Name of file to deploy
     * @throws Exception
     */
    protected void deployDataSource(final String p_Filename)
        throws Exception {

        String serverName = m_WhereAreYou.getCurrentJonasServerName();
        String domainName = m_WhereAreYou.getCurrentDomainName();
        String[] asParam = new String[1];
        String[] asSignature = new String[1];
        asParam[0] = p_Filename;
        asSignature[0] = "java.lang.String";

        ObjectName onDb = JonasObjectName.databaseService(domainName);
        // Verify if datasource already loaded
        Boolean oLoaded = (Boolean) JonasManagementRepr.invoke(onDb, "isLoadedDataSource", asParam
            , asSignature, serverName);
        if (oLoaded.booleanValue() == false) {
            // Get Datasource properties file
            Properties oProps = (Properties) JonasManagementRepr.invoke(onDb
                , "getDataSourcePropertiesFile", asParam, asSignature, serverName);
            // Load Datasource
            Object[] aoParam = {
                p_Filename, oProps, new Boolean(true)};
            String[] asSign_3 = {
                "java.lang.String", "java.util.Properties", "java.lang.Boolean"};
            JonasManagementRepr.invoke(onDb, "loadDataSource", aoParam, asSign_3, serverName);
        }
        else {
            throw new Exception(m_Resources.getMessage("error.deploy.datasource.isloaded"));
        }
    }

    /**
     * Deploy a mail factory.
     *
     * @param p_Filename Name of the mail factory whch is also the name of the file
     * @throws Exception
     */
    protected void deployMailFactory(final String domainName, final String p_Filename)
        throws Exception {
        String serverName = m_WhereAreYou.getCurrentJonasServerName();
        String[] asParam = new String[1];
        String[] asSignature = new String[1];
        asParam[0] = p_Filename;
        asSignature[0] = "java.lang.String";

        ObjectName onMail = JonasObjectName.mailService(domainName);
        // Get mail factory properties file
        Properties oProps = (Properties) JonasManagementRepr.invoke(onMail
            , "getMailFactoryPropertiesFile", asParam, asSignature, serverName);
        // Load mail factory
        Object[] aoParam = {
            p_Filename, oProps, new Boolean(true)};
        String[] asSign_3 = {
            "java.lang.String", "java.util.Properties", "java.lang.Boolean"};
        JonasManagementRepr.invoke(onMail, "createMailFactoryMBean", aoParam, asSign_3, serverName);
    }

    /**
     * Run garbage collector.
     *
     * @throws Exception
     */
    protected void runGC()
        throws Exception {String serverName = m_WhereAreYou.getCurrentJonasServerName();
        ObjectName oObjectName = J2eeObjectName.J2EEServer(m_WhereAreYou.getCurrentDomainName()
            , m_WhereAreYou.getCurrentJonasServerName());
        JonasManagementRepr.invoke(oObjectName, "runGC", null, null, m_WhereAreYou.getCurrentJonasServerName());
    }

    /**
     * Refresh the tree.
     *
     * @param pRequest The current HTTP Request
     * @throws Exception
     */
    protected void refreshTree(final HttpServletRequest pRequest) throws Exception {
        String serverName = m_WhereAreYou.getCurrentJonasServerName();
        String domainName = m_WhereAreYou.getCurrentDomainName();
        // Refresh Service Tree
        switch (getCurrentJonasDeployment()) { 
            case WhereAreYou.DEPLOYMENT:
                break;
            case WhereAreYou.DEPLOYMENT_EAR:
                refreshServiceTree(WhereAreYou.DEPLOYMENT_EAR, pRequest);
                if (JonasAdminJmx.hasMBeanName(JonasObjectName.ejbService(domainName), serverName)) {
                    refreshServiceTree(WhereAreYou.DEPLOYMENT_JAR, pRequest);
                    String localJoramServerId = (String) pRequest.getSession().getAttribute("localId");
                    refreshJoramTree(pRequest, localJoramServerId);
                }
                if (JonasAdminJmx.hasMBeanName(JonasObjectName.webContainerService(domainName), serverName)) {
                    refreshServiceTree(WhereAreYou.DEPLOYMENT_WAR, pRequest);
                }
                if (JonasAdminJmx.hasMBeanName(JonasObjectName.resourceService(domainName), serverName)) {
                    refreshServiceTree(WhereAreYou.DEPLOYMENT_RAR, pRequest);
                }
                break;
            case WhereAreYou.DEPLOYMENT_JAR:
                refreshServiceTree(WhereAreYou.DEPLOYMENT_JAR, pRequest);
                String localJoramServerId = (String) pRequest.getSession().getAttribute("localId");
                refreshJoramTree(pRequest, localJoramServerId);
                break;
            case WhereAreYou.DEPLOYMENT_WAR:
                refreshServiceTree(WhereAreYou.DEPLOYMENT_WAR, pRequest);
                break;
            case WhereAreYou.DEPLOYMENT_RAR:
                refreshServiceTree(WhereAreYou.DEPLOYMENT_RAR, pRequest);
                refreshJoramTree(pRequest, null);
                break;
            case WhereAreYou.DEPLOYMENT_DATASOURCE:
                refreshServiceTree(WhereAreYou.DEPLOYMENT_DATASOURCE, pRequest);
                break;
            case WhereAreYou.DEPLOYMENT_MAIL:
                refreshServiceTree(WhereAreYou.DEPLOYMENT_MAIL, pRequest);
                break;
        }
        // Refresh MBeans Tree
        refreshMBeansTree(pRequest);
        // Force display to refresh
        m_WhereAreYou.setTreeToRefresh(true);
    }

    /**
     * Refresh the service tree.
     *
     * @param p_Deployment The type of deployment
     * @param p_Request The current HTTP Request
     * @throws Exception
     */
    protected void refreshServiceTree(final int p_Deployment, final HttpServletRequest p_Request)
        throws Exception {
        // Get the domain and server name
        String sDomainLabel = "domain";
        String sServerName = m_WhereAreYou.getCurrentJonasServerName();
        // Get the service name
        String sCurrentNodeNameServiceItem = null;
        switch (p_Deployment) {
            case WhereAreYou.DEPLOYMENT_EAR:
                sCurrentNodeNameServiceItem = sDomainLabel + WhereAreYou.NODE_SEPARATOR
                    + sServerName + WhereAreYou.NODE_SEPARATOR + "services"
                    + WhereAreYou.NODE_SEPARATOR + "ear";
                break;
            case WhereAreYou.DEPLOYMENT_JAR:
                sCurrentNodeNameServiceItem = sDomainLabel + WhereAreYou.NODE_SEPARATOR
                    + sServerName + WhereAreYou.NODE_SEPARATOR + "services"
                    + WhereAreYou.NODE_SEPARATOR + "ejbContainers";
                break;
            case WhereAreYou.DEPLOYMENT_RAR:
                sCurrentNodeNameServiceItem = sDomainLabel + WhereAreYou.NODE_SEPARATOR
                    + sServerName + WhereAreYou.NODE_SEPARATOR + "services"
                    + WhereAreYou.NODE_SEPARATOR + "resourceAdapter";
                break;
            case WhereAreYou.DEPLOYMENT_WAR:
                sCurrentNodeNameServiceItem = sDomainLabel + WhereAreYou.NODE_SEPARATOR
                    + sServerName + WhereAreYou.NODE_SEPARATOR + "services"
                    + WhereAreYou.NODE_SEPARATOR + "web";
                break;
            case WhereAreYou.DEPLOYMENT_DATASOURCE:
                sCurrentNodeNameServiceItem = sDomainLabel + WhereAreYou.NODE_SEPARATOR
                    + sServerName + WhereAreYou.NODE_SEPARATOR + "services"
                    + WhereAreYou.NODE_SEPARATOR + "database";
                break;
            case WhereAreYou.DEPLOYMENT_MAIL:
                sCurrentNodeNameServiceItem = sDomainLabel + WhereAreYou.NODE_SEPARATOR
                    + sServerName + WhereAreYou.NODE_SEPARATOR + "services"
                    + WhereAreYou.NODE_SEPARATOR + "mail";
                break;
            case WhereAreYou.DEPLOYMENT_JMS:
                sCurrentNodeNameServiceItem = sDomainLabel + WhereAreYou.NODE_SEPARATOR
                    + sServerName + WhereAreYou.NODE_SEPARATOR + "services"
                    + WhereAreYou.NODE_SEPARATOR + "jms";
                break;
        }
        // Get current tree
        TreeControl oControl = m_WhereAreYou.getTreeControl();
        // Get service node
        TreeControlNode oServiceNode = oControl.findNode(sCurrentNodeNameServiceItem);
        // Enable auto-refresh mode
        oControl.enableAutoRefresh();
        // Remove old children
        TreeControlNode[] aoNodes = oServiceNode.findChildren();
        for (int i = 0; i < aoNodes.length; i++) {
            aoNodes[i].remove();
        }
        // Build node for the Service
        JonasTreeBuilder oBuilder = new JonasTreeBuilder();
        String sDomainName = m_WhereAreYou.getCurrentDomainName();

        switch (p_Deployment) {
            case WhereAreYou.DEPLOYMENT_EAR:
                oBuilder.getAppContainers(oServiceNode, m_Resources, sDomainName, sServerName);
                refreshWebServiceTree(p_Request);
                break;
            case WhereAreYou.DEPLOYMENT_JAR:
                oBuilder.getContainers(oServiceNode, m_Resources, sDomainName, sServerName);
                break;
            case WhereAreYou.DEPLOYMENT_RAR:
                oBuilder.getResourceAdapters(oServiceNode, m_Resources, sDomainName, sServerName);
                break;
            case WhereAreYou.DEPLOYMENT_WAR:
                oBuilder.getWebContainers(oServiceNode, m_Resources, p_Request);
                refreshWebServiceTree(p_Request);
                break;
            case WhereAreYou.DEPLOYMENT_DATASOURCE:
                oBuilder.getDatasources(oServiceNode, m_Resources, sDomainName, sServerName);
                break;
            case WhereAreYou.DEPLOYMENT_MAIL:
                oBuilder.getAllSessionMailFactories(oServiceNode, m_Resources, p_Request);
                oBuilder.getAllMimePartDSMailFactories(oServiceNode, m_Resources, p_Request);
                break;
        }
        // Disable auto-refresh mode
        oControl.disableAutoRefresh();
    }

    /**
     * @param pRequest request
     * @throws Exception could not refresh
     */
    protected void refreshWebServiceTree(final HttpServletRequest pRequest) throws Exception {
        String sServerName = m_WhereAreYou.getCurrentJonasServerName();
        String sDomainName = m_WhereAreYou.getCurrentDomainName();
        // Get current tree
        TreeControl oControl = m_WhereAreYou.getTreeControl();
        // Build node and his children
        JonasTreeBuilder oBuilder = new JonasTreeBuilder();

        // Since (un)deployment of ears and wars can add/remove webservices,
        // this part of the tree needs to be recreated.
        String sServicesNodeName = "domain" + WhereAreYou.NODE_SEPARATOR + sServerName + WhereAreYou.NODE_SEPARATOR + "services";
        // The node representing services in the jonasAdmin tree.
        TreeControlNode services = oControl.findNode(sServicesNodeName);
        // If any web services are deployed and services node is present in tree.
        if (JonasAdminJmx.hasMBeanName(JonasObjectName.wsService(sDomainName), sServerName) && services != null) {
            // Rebuild the webservices tree.
            oBuilder.getServiceWebService(services, m_Resources, pRequest, sDomainName, sServerName);
        } else {
            TreeControlNode ws = oControl.findNode(sServicesNodeName + WhereAreYou.NODE_SEPARATOR + "WebService");
            // If a web service node exists in tree already, remove it from there.
            if (ws != null) {
                ws.remove();
            }
        }
    }

    /**
     * Refresh the MBeans tree.
     *
     * @throws Exception
     */
    protected void refreshMBeansTree(final HttpServletRequest p_Request) throws Exception {
        // Get current tree
        TreeControl oControl = m_WhereAreYou.getTreeControl();
        // MBeans node present ?
        TreeControlNode oMBeansNode = oControl.findNode("domain*mbeans");
        TreeControlNode oDomainNode= oMBeansNode.getParent();
        if (oMBeansNode != null) {
            // Enable auto-refresh mode
            oControl.enableAutoRefresh();
            // Remove node
            oMBeansNode.remove();
            // Build node and his children
            JonasTreeBuilder oBuilder = new JonasTreeBuilder();
            oBuilder.getMBeans(oDomainNode, m_Resources, p_Request);
            // Disable auto-refresh mode
            oControl.disableAutoRefresh();
        }
    }

    /**
     * Refresh the Joram tree after creating / removing a Joram destination.
     * or after deploying / undeploying the Joram RAR
     * @param pRequest initiator request
     * @param serverId Id of the Joram server which was updated
     * @throws Exception
     */
    protected void refreshJoramTree(final HttpServletRequest pRequest, final String serverId) throws Exception {
        m_WhereAreYou.setTreeToRefresh(true);
        String serverName = m_WhereAreYou.getCurrentJonasServerName();
        // Get current tree
        TreeControl oControl = m_WhereAreYou.getTreeControl();
        // selected node
        TreeControlNode selectedNode = oControl.getSelected();
        // Joram node
        String sJoramNodeName = "domain" + WhereAreYou.NODE_SEPARATOR + "joramplatform";
        TreeControlNode oJoramNode = oControl.findNode(sJoramNodeName);
        // Root node
        TreeControlNode oDomainNode = oControl.findNode("domain");
        TreeControlNode oNode = null;
        // check if this is a Joram tree update case
        if (selectedNode.getName().indexOf(sJoramNodeName) < 0) {
            // the selected node is not a Joram node, select the Joram node or a Joram server node
            oNode = oJoramNode;
            if (serverId != null) {
                TreeControlNode[] aoNodes = oNode.findChildren();
                for (int i = 0; i < aoNodes.length; i++) {
                    String serverNodeLabel = aoNodes[i].getLabel();
                    int indexBefore = serverNodeLabel.indexOf("(");// (
                    int indexAfter = serverNodeLabel.indexOf(")", indexBefore + 1);// )
                    String id = serverNodeLabel.substring(indexBefore + 1, indexAfter);
                    if (id.equals(serverId)) {
                        oNode = aoNodes[i];
                        break;
                    }
                }
            }
        } else {
            // refreshJoramTree was called after a Joram platform configuration operation
            // which created or removed a Joram destination
            oNode = selectedNode;
            if (serverId == null) {
                return;
            }
        }
        // Enable auto-refresh mode
        oControl.enableAutoRefresh();
        if (oNode != null) {
            // Remove old children
            TreeControlNode[] aoNodes = oNode.findChildren();
            for (int i = 0; i < aoNodes.length; i++) {
                aoNodes[i].remove();
            }

            if (JonasManagementRepr.queryNames(JoramObjectName.joramAdapter(), serverName).isEmpty()) {
                // Remove node
                oNode.remove();
                // Un-register joramClient MBeans
                ObjectName joramClients = JoramObjectName.joramClientMBeans();
                Iterator it = JonasManagementRepr.queryNames(joramClients, serverName).iterator();
                ObjectName joramClient = null;
                while (it.hasNext()) {
                    joramClient = (ObjectName) it.next();
                    JonasManagementRepr.unregisterMBean(joramClient, serverName);
                }
            } else {
                JonasTreeBuilder oBuilder = new JonasTreeBuilder();
                if (serverId != null) {
                    oBuilder.getJoramResources(oNode, serverName, serverId, m_Resources, pRequest);
                } else {
                    oBuilder.getJoramServers(oJoramNode, serverName, null, m_Resources, pRequest);
                }
            }
        } else {
            // Construct tree if necessary
            // Build node and his children
            JonasTreeBuilder oBuilder = new JonasTreeBuilder();
            oBuilder.getJoramPlatform(oDomainNode, serverName, m_Resources, pRequest);
        }
        // Disable auto-refresh mode
        oControl.disableAutoRefresh();
    }

    /**
     * Remove a given file.
     * @param fileName Name of file to remove
     * @return true if file has been removed
     * @throws Exception if remove fails
     */
    protected boolean removeFile(final String fileName) throws Exception {
        return removeModule(fileName, m_WhereAreYou.getCurrentJonasServerName());
    }
    

    
    protected void deployModule(final String filename, final String serverName)
    throws Exception {
        ManagementEntryPoint mgmt = ManagementEntryPoint.getInstance();
        mgmt.deploy(filename, serverName);
    }

    protected void undeployModule(final String filename, final String serverName)
    throws Exception {
        ManagementEntryPoint mgmt = ManagementEntryPoint.getInstance();
        mgmt.undeploy(filename, serverName);
        // Check if depmonitor is in development mode
        if (mgmt.developmentMode("depmonitor", serverName)) {
            // remove the file
            mgmt.remove(filename, serverName);
        }
    }

    protected boolean removeModule(final String filename, final String serverName)
    throws Exception {
        ManagementEntryPoint mgmt = ManagementEntryPoint.getInstance();
        return mgmt.remove(filename, serverName);
    }
}
