/**
 * 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.j2eemanagement.servlets;

//import java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.util.List;

import javax.management.MBeanException;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.j2ee.ListenerRegistration;
import javax.management.j2ee.Management;
import javax.management.j2ee.ManagementHome;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This servlet is an example which shows how to access the MEJB from a servlet.
 * @author JOnAS team
 * @author Adriana Danes
 * @author Michel-Ange Anton
 */
public class MgmtServlet extends J2eemanagementBaseServlet {

    // ---------------------------------------------------------- Constants
    /** Printing constant*/
    static final String APP_TITLE_LARGE = "J2EE Management sample with Servlet accessing the MEJB";
    /** Printing constant*/
    static final String APP_TITLE = "J2EE Management sample";
    /** Parameter */
    static final String PARAM_DOMAIN = "domainName";
    /** Parameter */
    static final String PARAM_VIEW = "view";
    /** Parameter */
    static final String VIEW_INIT = "init";
    /** Parameter */
    static final String VIEW_NOTIFICATIONS = "notifications";
    /** Parameter */
    static final String VIEW_OTHER = "other";
    /** Deploable module types */
    static final String JAR = "jar";
    /** Deploable module types */
    static final String WAR = "war";
    /** Deploable module types */
    static final String RAR = "rar";
    /** Deploable module types */
    static final String EAR = "ear";
    /**
     * Listener object
     */
    private MyListener mListener = null;

    // ---------------------------------------------------------- Public methods

    /**
     * Initialize the servlet.
     * @param pConfig See HttpServlet
     * @throws ServletException
     */
    public void init(ServletConfig pConfig) throws ServletException {
        super.init(pConfig);
        // Initialize variables
        mListener = null;
    }

    // ---------------------------------------------------------- Protected
    // methods

    /**
     * Response to the GET request.
     * @param pRequest See HttpServlet
     * @param pResponse See HttpServlet
     * @throws IOException
     * @throws ServletException
     */
    protected void doGet(HttpServletRequest pRequest, HttpServletResponse pResponse) throws IOException,
    ServletException {
        dispatch(pRequest, pResponse);
    }

    /**
     * Response to the POST request.
     * @param pRequest See HttpServlet
     * @param pResponse See HttpServlet
     * @throws IOException
     * @throws ServletException
     */
    protected void doPost(HttpServletRequest pRequest, HttpServletResponse pResponse) throws IOException,
    ServletException {
        dispatch(pRequest, pResponse);
    }

    /**
     * Dispatch the response.
     * @param pRequest Request
     * @param pResponse Response
     * @throws IOException
     */
    protected void dispatch(HttpServletRequest pRequest, HttpServletResponse pResponse) throws IOException {

        pResponse.setContentType("text/html");
        PrintWriter out = pResponse.getWriter();

        // Get parameters
        String sParamDomain = pRequest.getParameter(PARAM_DOMAIN);
        String sParamView = pRequest.getParameter(PARAM_VIEW);

        // Dispatching
        if ((sParamDomain == null) || (sParamDomain.length() == 0)) {
            doViewError("Parameter domain not found", pRequest, out);
        } else if ((sParamView == null) || (sParamView.length() == 0) || VIEW_INIT.equals(sParamView)) {
            doViewInit(sParamDomain, pRequest, out);
        } else if (VIEW_NOTIFICATIONS.equals(sParamView)) {
            doViewNotifications(out);
        } else if (VIEW_OTHER.equals(sParamView)) {
            doViewOther(sParamDomain, pRequest, out);
        } else {
            doViewError("Unknown View", pRequest, out);
        }

    }


    /**
     * Footer navigation.
     * @param pDomainName Name of domain
     * @param pRequest Http request
     * @param pOut Printer
     * @param pPrevious Previous view
     * @param pNext Next view
     */
    protected void printNavigationFooter(String pDomainName, HttpServletRequest pRequest, PrintWriter pOut,
            String pPrevious, String pNext) {

        // index
        String sViewIndex = pRequest.getContextPath();
        // Notifications
        String sViewNotifications = pRequest.getRequestURI() + "?" + PARAM_DOMAIN + "=" + pDomainName + "&"
        + PARAM_VIEW + "=" + VIEW_NOTIFICATIONS;
        // Previous View
        String sPrevView = null;
        if (pPrevious != null) {
            sPrevView = pRequest.getRequestURI() + "?" + PARAM_DOMAIN + "=" + pDomainName + "&" + PARAM_VIEW + "="
            + pPrevious;
        }
        // Next View
        String sNextView = null;
        if (pNext != null) {
            sNextView = pRequest.getRequestURI() + "?" + PARAM_DOMAIN + "=" + pDomainName + "&" + PARAM_VIEW + "="
            + pNext;
        }

        // Display
        pOut.print("<table border=\"1\" align=\"center\" cellspacing=\"0\" cellpadding=\"5\">");
        pOut.print("<tr>");
        pOut.print("<td align=\"center\"> <a href=\"" + sViewIndex + "\">Index</a> </td>");
        pOut.print("<td align=\"center\"> <a href=\"" + sViewNotifications
                + "\" target=\"ViewNotifications\">Notifications</a> </td>");
        if (sPrevView != null) {
            pOut.println("<td align=\"center\"> <a href=\"" + sPrevView + "\">Previous</a> </td>");
        }
        if (sNextView != null) {
            pOut.println("<td align=\"center\"> <a href=\"" + sNextView + "\">Next</a> </td>");
        }
        pOut.println("</tr></table>");
        // Footer
        printFooter(pOut);
    }

    /**
     * View init MEJB and access to MBeans J2EEDomain and J2EEServer.
     * @param pDomainName Name of domain to access
     * @param pRequest Http request
     * @param pOut Printer
     */
    protected void doViewInit(String pDomainName, HttpServletRequest pRequest, PrintWriter pOut) {

        // Header
        //printHeader(pOut, APP_TITLE_LARGE, "Init");

        // -----------------------------
        // Get initial context
        // -----------------------------
        pOut.println("<h2>Initial context</h2>");
        pOut.println("<ul>");
        Context initialContext = null;
        try {
            initialContext = new InitialContext();
            pOut.println("<li>Initial context OK</li>");
        } catch (Exception e) {
            pOut.print("<li>Cannot get initial context for JNDI: ");
            pOut.println(e + "</li>");
            pOut.println("</ul>");
            return;
        }
        pOut.println("</ul><br>");

        // -----------------------------
        // Access to the MEJB
        // -----------------------------
        pOut.println("<h2>Create MEJB</h2>");
        pOut.println("<ul>");

        // Connecting to the MEJB home through JNDI
        ManagementHome mgmtHome = null;
        try {
            mgmtHome = (ManagementHome) PortableRemoteObject.narrow(initialContext.lookup("java:comp/env/ejb/mgmt/MEJB"),
                    ManagementHome.class);
        } catch (Exception e) {
            pOut.println("<li>Cannot lookup java:comp/env/ejb/mgmt/MEJB: " + e + "</li>");
            pOut.println("</ul>");
            return;
        }

        // Management bean creation
        Management mgmt = null;

        try {
            mgmt = mgmtHome.create();
            pOut.println("<li>MEJB created</li>");
        } catch (Exception e) {
            pOut.println("<li>Cannot create MEJB: " + e + "</li>");
            return;
        }
        pOut.println("</ul><br/>");
        // ------------------------------
        // Access to the J2EEDomain MBean
        // ------------------------------

        ObjectName onDomain = accessJ2EEDomain(pDomainName, mgmt, pOut);
        if (onDomain == null) {
            return;
        }

        boolean master = checkIfMaster(onDomain, mgmt, pOut);

        // -----------------------------------------------------
        // Check for J2EEServer MBeans in the current J2EEDomain
        // -----------------------------------------------------
        ObjectName onServer = accessJ2EEServer(onDomain, mgmt, pOut);
        if (onServer == null) {
            return;
        }

        // ------------------------------
        // Test domain deployment
        // ------------------------------
        if (master) {
            pOut.println("<h2>Try to manage the current domain: deploy/undeploy on all servers in the domain</h2>");
            pOut.println("<ul>");
            pOut.println("<li>Use the J2EEDomain object name: \"" + onDomain.toString() + "\"</li>");
            String[] serverNames = null;
            try {
                serverNames = (String[]) mgmt.getAttribute(onDomain, "serverNames");
            } catch (Exception e) {
                pOut.println("<li>Can't get serverNames attribute: " + e + "</li>");
            }
            if (serverNames.length > 1) {
                String fileName = null;
                // Use deploy, undeploy
                // (suppose sb.jar was installed under JONAS_BASE/ejbjars directory)
                fileName = "sb.jar";
                deployModuleWithTarget(JAR, onDomain, serverNames, mgmt, fileName, pOut);

                // Use deploy, undeploy
                // (suppose earsample.ear was installed under JONAS_BASE/apps directory)
                fileName = "earsample.ear";
                deployModuleWithTarget(EAR, onDomain, serverNames, mgmt, fileName, pOut);
            } else {
                pOut.println("<li>Can't find server names in this domain</li>");
            }
            pOut.println("</ul><br>");
        } else {
            // ------------------------------
            // Test current server management
            // ------------------------------
            pOut.println("<h2>Try to manage the current server</h2>");
            pOut.println("<ul>");
            pOut.println("<li>Using the J2EEServer object name: \"" + onServer.toString() + "\"</li>");

            // Use deployJar, unDeployJar, isJarDeployed management opearations
            // (suppose sb.jar was installed under JONAS_BASE/ejbjars directory)
            String jarFileName = System.getProperty("jonas.base")+"/ejbjars/"+"sb.jar";
            deployJarModule(onServer, mgmt, jarFileName, pOut);

            // Use deployEar, unDeployEar, isEarDeployed management opearations
            // (suppose earsample.ear was installed under JONAS_BASE/apps directory)
            String earFileName = System.getProperty("jonas.base")+"/apps/"+"earsample.ear";
            deployEarModule(onServer, mgmt, earFileName, pOut);

            // (suppose autoload/earsample.ear was installed under JONAS_BASE/apps directory)
            earFileName = "autoload/earsample.ear";
            deployEarModule(onServer, mgmt, earFileName, pOut);

            // Use deployRar, unDeployRar, isRarDeployed
            // (suppose JDBC connection rar files installed under JONAS_BASE/rars directory)
            /*
            String rarFileName = "autoload/JOnAS_jdbcCP.rar";
            deployRarModule(onServer, mgmt, rarFileName, pOut);
             */
            pOut.println("</ul><br>");
        }
        // -----------------------------
        // Test Event Listener support
        // -----------------------------

        pOut.println("<h2>Register an event listener</h2>");
        pOut.println("<ul>");

        // Test Monolog JMXHandler notifications
        // -------------------------------------
        // Set this to true if you test the JMXHandler notifications !
        boolean testLogNotifs = true;

        String logServName = new String(pDomainName + ":type=service,name=log");
        ObjectName logServOn = null;
        try {
            logServOn = ObjectName.getInstance(logServName);
        } catch (MalformedObjectNameException e1) {
            pOut.println("<li><b>Can't create ObjectName for log service MBean</b>: " + e1 + "</li>");
            testLogNotifs = false;
            pOut.println("</ul>");
        }
        if (testLogNotifs) {
            boolean existsLog;
            try {
                existsLog = mgmt.isRegistered(logServOn);
                if (existsLog) {
                    pOut.println("<li>Found log service MBean</li>");
                } else {
                    pOut.println("<li><b>Can't find log service MBean</b></li>");
                    testLogNotifs = existsLog;
                }
            } catch (RemoteException e) {
                pOut.println("<li>Failed to find the log service MBean</li>");
            }
        }

        if (mListener == null) {
            if (!testLogNotifs) {
                mListener = new MyListener();
                pOut.println("<li>MyListener created</li>");
            } else {
                mListener = new MonologListener();
                pOut.println("<li>MonologListener created</li>");
            }
        }

        String sHandler = "MEJBTester";
        // Get the ListenerRegistration object
        try {
            pOut.println("<li>Create ListenerRegistration</li>");
            ListenerRegistration lr = mgmt.getListenerRegistry();
            pOut.println("<li>ListenerRegistration created</li>");
            if (lr != null) {
                if (testLogNotifs) {
                    pOut.println("<li>Add listener for Monolog notifications (" + logServOn.toString() + ")</li>");
                    lr.addNotificationListener(logServOn, mListener, null, sHandler);
                } else {
                    pOut.println("<li>Add listener on J2EEServer (" + onServer.toString() + ")</li>");
                    lr.addNotificationListener(onServer, mListener, null, sHandler);
                }
                pOut.println("<li>Notification Listener added</li>");
                String sViewNotifications = pRequest.getRequestURI() + "?" + PARAM_DOMAIN + "=" + pDomainName + "&"
                + PARAM_VIEW + "=" + VIEW_NOTIFICATIONS;
                pOut.println("<a href=\"" + sViewNotifications
                        + "\" target=\"ViewNotifications\">See list of notifications</a>");
                pOut.println("</ul>");
            } else {
                pOut.println("<li>Can't add remote listener for the moment</li>");
                pOut.println("</ul>");
            }
        } catch (Exception e) {
            pOut.println("<li>Can't add notification listener on " + onServer.toString() + " : " + e + "</li>");
        }

        pOut.println("<h2>Application is OK </h2>");

        // Footer
        printNavigationFooter(pDomainName, pRequest, pOut, null, VIEW_OTHER);
    }

    /**
     * Header.
     * @param pOut Printer
     * @param pTitle Title to display
     * @param pSubTitle Subtitle to display or null if not
     */
    protected void printHeaderAutoRefresh(PrintWriter pOut, String pTitle, String pSubTitle) {

        pOut.println("<html>");
        pOut.println("<head>");
        pOut.println("<title>" + pTitle + "</title>");
        pOut.println("<script language=\"JavaScript\">");
        pOut.println("function startRefresh(){ setTimeout(\"refresh()\",30000); self.focus(); }");
        pOut.println("function refresh(){ window.location.reload(); }");
        pOut.println("</script>");
        pOut.println("</head>");
        pOut.println("<body onload=\"startRefresh()\" style=\"background : white; color : black;\">");
        printHeaderTitle(pOut, pTitle, pSubTitle);
    }
    /**
     * View notifications.
     * @param pOut Printer
     */
    protected void doViewNotifications(PrintWriter pOut) {

        // Header
        printHeaderAutoRefresh(pOut, APP_TITLE, "Notifications");
        pOut.println("<h2>List of notifications</h2>");

        // Verify listener
        if (mListener == null) {
            pOut.println("Listener not found !");
        } else {
            // Display notifications
            List list = mListener.getListNotifications();
            if (list.size() > 0) {
                pOut.println("<ol>");
                for (int i = 0; i < list.size(); i++) {
                    pOut.println("<li>" + list.get(i) + "</li>");
                }
                pOut.println("</ol>");
            } else {
                pOut.println("No notifications, the list is empty");
            }
        }

        // Footer
        printFooter(pOut);
    }

    /**
     * View example.
     * @param pDomainName Name of domain to access
     * @param pRequest Http request
     * @param pOut Printer
     */
    protected void doViewOther(String pDomainName, HttpServletRequest pRequest, PrintWriter pOut) {

        // Header
        printHeader(pOut, APP_TITLE, "Other");

        pOut.println("<h2>Other</h2>");

        // Footer
        printNavigationFooter(pDomainName, pRequest, pOut, VIEW_INIT, null);
    }

    /**
     * Create J2EEDomain MBean's ObjectName and test if MBean registered
     * @param pDomainName the name provided by the user
     * @param mgmt MEJB
     * @param pOut output stream
     * @return true if management operation succeeded
     */
    private ObjectName accessJ2EEDomain(String pDomainName, Management mgmt, PrintWriter pOut) {
        ObjectName onDomain = null;
        pOut.println("<h2>Access the J2EEDomain MBean</h2>");
        pOut.println("<ul>");

        // Get the J2EEDomain MBean's ObjectName
        try {
            String name = pDomainName + ":j2eeType=J2EEDomain,name=" + pDomainName;
            onDomain = ObjectName.getInstance(name);
            pOut.println("<li>J2EEDomain object name created: \"" + name.toString() + "\"</li>");
        } catch (Exception e) {
            pOut.println("<li>Cannot create object name for J2EEDomain managed object: " + e + "</li>");
            pOut.println("</ul>");
            return null;
        }
        // Check that the J2EEDomain MBean registered
        try {
            boolean exists = mgmt.isRegistered(onDomain);
            if (exists) {
                pOut.println("<li>Found this J2EEDomain MBean in the current MBean server</li>");
            } else {
                pOut.println("<li><b>Can't find this J2EEDomain MBean in the current MBean server</b></li>");
                pOut.println("</ul>");
                return null;
            }
        } catch (Exception e) {
            pOut.println("<li>Error when using this J2EEDomain MBean: " + e + "</li>");
            pOut.println("</ul>");
            return null;
        }
        return onDomain;
    }

    /**
     *
     * @param onDomain J2EEDomain MBean ObjectName
     * @param mgmt Management EJB
     * @param pOut output stream
     * @return true if the current server is a master
     */
    private boolean checkIfMaster(ObjectName onDomain, Management mgmt, PrintWriter pOut) {
        try {
            Boolean master = (Boolean) mgmt.getAttribute(onDomain, "master");
            if (master.booleanValue()) {
                pOut.println("<li>The current server is a management master</li>");
            }
            pOut.println("</ul>");
            return master.booleanValue();
        } catch (Exception e) {
            pOut.println("<li>Error when using this J2EEDomain MBean: " + e + "</li>");
        }
        pOut.println("</ul>");
        return false;
    }

    /**
     * Get a registered J2EEServer MBean
     * @param onDomain J2EEDomain MBean's ObjectName
     * @param mgmt MEJB
     * @param pOut output stream
     * @return true if management operation succeeded
     */
    private ObjectName accessJ2EEServer(ObjectName onDomain, Management mgmt, PrintWriter pOut) {
        pOut.println("<h2>Access the J2EEServer MBeans</h2>");
        pOut.println("<ul>");
        ObjectName onServer = null;
        String[] listServers = null;
        try {
            listServers = (String[]) mgmt.getAttribute(onDomain, "servers");
        } catch (Exception e) {
            pOut.println("<li>Cant' access the " + onDomain + " MBean's <i>servers</i> attribute</li>");
            pOut.println("</ul><br>");
            return null;
        }
        int nbServers = listServers.length;
        if (nbServers == 0) {
            pOut.println("<li>No J2EEServer MBeans in the " + onDomain + " MBean's <i>servers</i> list (problem with domain management !!)</li>");
            pOut.println("</ul><br>");
            return null;
        } else {
            if (nbServers == 1) {
                String serverOn = (String) listServers[0];
                try {
                    onServer = ObjectName.getInstance(serverOn);
                    if (mgmt.isRegistered(onServer)) {
                        pOut.println("<li>Found one J2EEServer MBean registered in the current MBean server. Its OBJECT_NAME is: \"" + serverOn + "\"</li>");
                        pOut.println("</ul><br>");
                        return onServer;
                    } else {
                        pOut.println("<li><b>Can't find the J2EEServer MBean having OBJECT_NAME: " + serverOn + " in the current MBean server</b></li>");
                        pOut.println("</ul><br>");
                        return null;
                    }
                } catch (Exception e) {
                    pOut.println("<li>Error witht OBJECT_NAME " + serverOn + ": " + e + "</li>");
                    pOut.println("</ul><br>");
                    return null;
                }
            } else {
                pOut.println("<li>List of J2EEServer MBeans in the \"" + onDomain + "\" MBean's <i>servers</i> list:</li>");
                pOut.println("<ol>");
                for (int i = 0; i < nbServers; i++) {
                    String serverOn = listServers[i];
                    ObjectName on = null;
                    try {
                        on = ObjectName.getInstance(serverOn);
                    } catch (MalformedObjectNameException e) {
                        pOut.print("<li>Error witht OBJECT_NAME " + serverOn + ": " + e + "</li>");
                        continue;
                    }
                    pOut.print("<li>\"" + serverOn + "\". ");
                    boolean isRegisterdServer = false;
                    try {
                        isRegisterdServer = mgmt.isRegistered(on);
                    } catch (RemoteException e) {
                        pOut.println("<ul>");
                        pOut.println("<li>Error witht OBJECT_NAME " + serverOn + ": " + e + "</li>");
                        pOut.println("</ul>");
                        pOut.println("</li>");
                        continue;
                    }
                    if (isRegisterdServer) {
                        pOut.print("This MBean is registered in the current MBean server. It should correspond to the current server.");
                        pOut.println("</li>");
                        onServer = on;
                    } else {
                        pOut.println("This MBean is not registered in the current MBean server. It could correspond to a remote server.");
                        pOut.println("</li>");
                        pOut.println("<ul>");
                        String name = on.getKeyProperty("name");
                        String[] signature = {"java.lang.String"};
                        String[] params = new String[1];
                        params[0] = name;
                        String[] urls = null;
                        try {
                            urls = (String[]) mgmt.invoke(onDomain, "getConnectorServerURLs", params, signature);
                        } catch (Exception e) {
                            pOut.println("<li>Could not found a connector server URL for server " + name + ".</li>");
                            pOut.println("</ul>");
                            pOut.println("</li>");
                            continue;
                        }
                        if (urls == null) {
                            pOut.println("<li>Could not found a connector server URL for server " + name + "</li>");
                            pOut.println("</ul>");
                            pOut.println("</li>");
                            continue;
                        }
                        for (int j = 0; j < urls.length; j++) {
                            String url = urls[j];
                            pOut.print("<li>Try to connect to server " + name + " using connector server URL: " + url + "</li>");
                            MBeanServerConnection connection = createConnection(url);
                            if (connection != null) {
                                // Use connection directly instead of using MEJB
                                try {
                                    if (connection.isRegistered(on)) {
                                        pOut.print("<li>Found MBean having OBJECT_NAME \"" + serverOn + "\"  registered in the connected MBean server.");
                                    } else {
                                        pOut.print("<li>The MBean having OBJECT_NAME \"" + serverOn + "\" is not registered in the connected MBean server.");
                                    }
                                } catch (IOException ioe) {
                                    pOut.print("<li>Exception when trying to use connection: " + ioe.toString());
                                }
                            } else {
                                pOut.print("<li>Could not establish connection with server " + name + ". Server may be stopped or URL not valid.</li>");
                            }
                        }
                        pOut.println("</ul>");
                        pOut.println("</li>");
                    }
                }
                pOut.println("</ol>");
                pOut.println("</ul><br>");
                return onServer;
            }
        }
    }

    private MBeanServerConnection createConnection(String connectorServerURL) {
        MBeanServerConnection connection;
        // create a connector client for the connector server at the given url
        JMXConnector connector = null;
        try {
            JMXServiceURL url = new JMXServiceURL(connectorServerURL);
            connector = JMXConnectorFactory.newJMXConnector(url, null);
            connector.connect(null);
            connection = connector.getMBeanServerConnection();
        } catch (MalformedURLException e) {
            // there is no provider for the protocol in url
            connection = null;
        } catch (IOException e) {
            // connector client or connection cannot be made because of a communication problem.
            connection = null;
        } catch (java.lang.SecurityException e) {
            // connection cannot be made for security reasons
            connection = null;
        }
        return connection;
    }

    /**
     * Deploy if not already deployed, undeploy otherwise, a given jar file.
     * @param onServer ObjectName of the J2EEServer MBean on which the mananagement operation has to be applied
     * @param mgmt MEJB
     * @param jarFileName name of the file to be deployed/undeployed
     * @param pOut output stream
     */
    private void deployJarModule(ObjectName onServer, Management mgmt, String jarFileName, PrintWriter pOut) {
        String[] signature = {"java.lang.String"};
        String[] params = new String[1];
        params[0] = jarFileName;
        pOut.println("<li>Test if " + jarFileName + " deployed</li>");
        boolean isDeployed = false;
        try {
            isDeployed = ((Boolean) mgmt.invoke(onServer, "isDeployed", params, signature)).booleanValue();
        } catch (Exception e) {
            pOut.println("<li>Problem when invoking isDeployed management operation: " + e.toString());
        }
        if (!isDeployed) {
            pOut.println("<li>Try to deploy " + jarFileName + " !</li>");
            try {
                String deployedObjectName = (String) mgmt.invoke(onServer, "deploy", params, signature);
                pOut.println("<li>The Object Name of the deployed J2EEModule is: \"" + deployedObjectName + "\". </li>");
            } catch (MBeanException mbe) {
                pOut.println("<li>Could not deploy " + jarFileName + " because of exception: "
                        + mbe.getTargetException().toString());
            } catch (Exception e) {
                pOut.println("<li>Could not deploy " + jarFileName + " because of exception: " + e.toString() + " </li>");
            }
        } else {
            pOut.println("<li>Try to un-deploy " + jarFileName + " !</li>");
            try {
                mgmt.invoke(onServer, "undeploy", params, signature);
                pOut.println("<li>Done undeploy.>");
            } catch (MBeanException mbe) {
                pOut.println("<li>Could not undeploy " + jarFileName + " because of exception: "
                        + mbe.getTargetException().toString());
            } catch (Exception e) {
                pOut.println("<li>Could not undeploy " + jarFileName + " because of exception: " + e.toString() + " </li>");
            }
        }
    }
    /**
     * Deploy if not already deployed, undeploy otherwise, a given ear file.
     * @param onServer ObjectName of the J2EEServer MBean on which the mananagement operation has to be applied
     * @param mgmt MEJB
     * @param earFileName name of the file to be deployed/undeployed
     * @param pOut output stream
     */
    private void deployEarModule(ObjectName onServer, Management mgmt, String earFileName, PrintWriter pOut) {
        String[] signature = {"java.lang.String"};
        String[] params = new String[1];
        params[0] = earFileName;
        pOut.println("<li>Test if " + earFileName + " deployed</li>");
        boolean isDeployed = false;
        try {
            isDeployed = ((Boolean) mgmt.invoke(onServer, "isDeployed", params, signature)).booleanValue();
        } catch (Exception e) {
            pOut.println("<li>Problem when invoking isEarDeployed management operation: " + e.toString());
        }
        if (!isDeployed) {
            pOut.println("<li>Try to deploy " + earFileName + " !</li>");
            try {
                String deployedObjectName = (String) mgmt.invoke(onServer, "deploy", params, signature);
                pOut.println("<li>The Object Name of the deployed J2EEModule is: \"" + deployedObjectName + "\". </li>");
            } catch (MBeanException mbe) {
                pOut.println("<li>Could not deploy " + earFileName + " because of exception: "
                        + mbe.getTargetException().toString());
            } catch (Exception e) {
                pOut.println("<li>Could not deploy " + earFileName + " because of exception: " + e.toString() + " </li>");
            }
        } else {
            pOut.println("<li>Try to un-deploy " + earFileName + " !</li>");
            try {
                mgmt.invoke(onServer, "undeploy", params, signature);
                pOut.println("<li>Done undeploy.>");
            } catch (MBeanException mbe) {
                pOut.println("<li>Could not undeploy " + earFileName + " because of exception: "
                        + mbe.getTargetException().toString());
            } catch (Exception e) {
                pOut.println("<li>Could not undeploy " + earFileName + " because of exception: " + e.toString() + " </li>");
            }
        }
    }

    /**
     * Deploy if not already deployed, undeploy otherwise, a given rar file.
     * @param onServer ObjectName of the J2EEServer MBean on which the mananagement operation has to be applied
     * @param mgmt MEJB
     * @param rarFileName name of the file to be deployed/undeployed
     * @param pOut output stream
     */
    private void deployRarModule(ObjectName onServer, Management mgmt, String rarFileName, PrintWriter pOut) {
        String[] signature = {"java.lang.String"};
        String[] params = new String[1];
        params[0] = rarFileName;
        pOut.println("<li>Test if " + rarFileName + " deployed</li>");
        boolean isDeployed = false;
        try {
            isDeployed = ((Boolean) mgmt.invoke(onServer, "isDeployed", params, signature)).booleanValue();
        } catch (Exception e) {
            pOut.println("<li>Problem when invoking isRarDeployed management operation: " + e.toString());
        }
        if (!isDeployed) {
            pOut.println("<li>Try to deploy " + rarFileName + " !</li>");
            try {
                String deployedObjectName = (String) mgmt.invoke(onServer, "deploy", params, signature);
                pOut.println("<li>The Object Name of the deployed J2EEModule is: \"" + deployedObjectName + "\". </li>");
            } catch (MBeanException mbe) {
                pOut.println("<li>Could not deploy " + rarFileName + " because of exception: "
                        + mbe.getTargetException().toString());
            } catch (Exception e) {
                pOut.println("<li>Could not deploy " + rarFileName + " because of exception: " + e.toString() + " </li>");
            }
        } else {
            pOut.println("<li>Try to un-deploy " + rarFileName + " !</li>");
            try {
                mgmt.invoke(onServer, "undeploy", params, signature);
                pOut.println("<li>Done undeploy.>");
            } catch (MBeanException mbe) {
                pOut.println("<li>Could not undeploy " + rarFileName + " because of exception: "
                        + mbe.getTargetException().toString());
            } catch (Exception e) {
                pOut.println("<li>Could not undeploy " + rarFileName + " because of exception: " + e.toString() + " </li>");
            }
        }
    }

    /**
     * Deploy if not already deployed, undeploy otherwise, a given jar file.
     * @param moduleType can be JAR, WAR, RAR or EAR
     * @param onDomain J2EEDomain MBean ObjectName
     * @param target names of the servers on which the mananagement operation has to be applied
     * @param mgmt MEJB
     * @param fileName name of the file to be deployed/undeployed
     * @param pOut output stream
     */
    private void deployModuleWithTarget(String moduleType, ObjectName onDomain, String[] target, Management mgmt, String fileName, PrintWriter pOut) {
        String[] signature = {"[Ljava.lang.String;", "java.lang.String"};
        Object[] params = new Object[2];
        params[0] = target;
        params[1] = fileName;
        try {
            String operationName = "deploy";
            pOut.println("<li>Try to " + operationName + " " + fileName + " on multiple target !</li>");
            mgmt.invoke(onDomain, operationName, params, signature);
            operationName = "undeploy";
            pOut.println("<li>Try to " + operationName + " " + fileName + " on multiple target !</li>");
            mgmt.invoke(onDomain, operationName, params, signature);
        } catch (MBeanException mbe) {
            pOut.println("<li>Could not deploy/undeploy " + fileName + " because of exception: "
                    + mbe.getTargetException().toString());
        } catch (Exception e) {
            pOut.println("<li>Could not deploy " + fileName + " because of exception: " + e.toString() + " </li>");
        }
    }
}
