/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2006 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 javax.management.ObjectName;
import javax.management.j2ee.Management;
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
 */
public class ClustMgmtServlet extends J2eemanagementBaseServlet {

    // ---------------------------------------------------------- Constants
    /** Parameter */
    static final String PARAM_DOMAIN = "domainName";
    /** Parameter */
    static final String PARAM_CLUSTER = "clusterName";
    /** Parameter */
    static final String PARAM_VIEW = "view";
    /** Parameter */
    static final String VIEW_INIT = "init";

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

    /**
     * Initialize the servlet.
     * @param pConfig See HttpServlet
     * @throws ServletException Could not execute request
     */
    public void init(ServletConfig pConfig) throws ServletException {
        super.init(pConfig);
    }

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

    /**
     * Response to the GET request.
     * @param pRequest See HttpServlet
     * @param pResponse See HttpServlet
     * @throws IOException An input or output error is detected when the servlet handles the request
     * @throws ServletException Could not execute request
     */
    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 An input or output error is detected when the servlet handles the request
     * @throws ServletException Could not execute request
     */
    protected void doPost(HttpServletRequest pRequest, HttpServletResponse pResponse) throws IOException,
            ServletException {
        dispatch(pRequest, pResponse);
    }

    /**
     * Dispatch the response.
     * @param pRequest Request
     * @param pResponse Response
     * @throws IOException An input or output error is detected when the servlet handles the request
     */
    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 sParamCluster = pRequest.getParameter(PARAM_CLUSTER);
        String sParamView = pRequest.getParameter(PARAM_VIEW);

        // Dispatching
        if ((sParamDomain == null) || (sParamDomain.length() == 0)) {
            doViewError("Parameter <i>Domain name</i> not found", pRequest, out);
        } else if ((sParamCluster == null) || (sParamCluster.length() == 0)) {
            doViewError("Parameter <i>Cluster name</i> not found", pRequest, out);
        } else if ((sParamView == null) || (sParamView.length() == 0) || VIEW_INIT.equals(sParamView)) {
            doViewInit(pRequest, out);
            doViewManagement(sParamDomain, sParamCluster, pRequest, out);
        } else {
            doViewError("Unknown View", pRequest, out);
        }

    }

    /**
     * Do management opeartions in this view.
     * @param pDomainName Name of domain to access
     * @param pClusterName Name of the cluster to manage in the domain
     * @param pRequest Http request
     * @param pOut Printer
     */
    protected void doViewManagement(String pDomainName, String pClusterName, HttpServletRequest pRequest, PrintWriter pOut) {
        Management mgmt = getMgmt();

        // ------------------------------
        // Access to the J2EEDomain MBean
        // ------------------------------
        ObjectName onDomain = accessJ2EEDomain(pDomainName, mgmt, pOut);
        if (onDomain == null) {
            return;
        }

        // Create a cluster in the domain
        // -------------------------------
        ObjectName onCluster = createCluster(onDomain, pClusterName, mgmt, pOut);
        if (onCluster == null) {
            return;
        }

        // -----------------------------------------------------
        // Using the domain management EJB to list servers and clusters
        // -----------------------------------------------------
        String[] serverNames = null;
        String[] serverNamesDom = null;
        String[] servers = null;
        String[] clusters = null;
        try {

            pOut.println("<h2>Getting the list of cluster MBeans</h2>");
            clusters = (String[]) mgmt.getAttribute(onDomain, "clusters");
            pOut.println("<ul>");
            for (int i = 0; i < clusters.length; i++) {
                pOut.println("<li>" + clusters[i] + "</li>");
            }
            pOut.println("</ul>");
        } catch (Exception e) {
            pOut.println("<li>Could not make MEJB list servers or clusters. </li>" + e);
            e.printStackTrace(pOut);
            return;
        }

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

        // Footer
        printNavigationFooter(pRequest, pOut);
    }

    /**
     * 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 \"" + name.toString() + "\" created.</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>");
                pOut.println("</ul><br/>");
            } 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;
    }

    private ObjectName createCluster(ObjectName pOnDomain, String pClusterName, Management mgmt, PrintWriter pOut) {
        ObjectName on = null;
        String domainName = pOnDomain.getDomain();
        pOut.println("<h2>Create cluster " + pClusterName + " in domain " + domainName + "</h2>");
        pOut.println("<ul>");
        try {
            String[] signature = new String[1];
            signature[0] = "java.lang.String";
            Object[] params = new Object[1];
            params[0] = pClusterName;
            String clusterOn = (String) mgmt.invoke(pOnDomain, "createCluster", params, signature);
            on = ObjectName.getInstance(clusterOn);
            pOut.println("<li>Cluster " + pClusterName + " created.</li>");
            pOut.println("</ul><br/>");
        } catch (Exception e) {
            pOut.println("<li>Cannot create cluster " + pClusterName + ": " + e + "</li>");
            pOut.println("</ul>");
        }
        return on;
    }
}