/**
 * 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 ClusterDaemonServlet extends J2eemanagementBaseServlet {

    // ---------------------------------------------------------- Constants
    /** Parameter */
    static final String PARAM_DOMAIN = "domainName";
    /** Parameter */
    static final String PARAM_DAEMON = "daemonName";
    /** Parameter which gives the name of the server to be started by the daemon */
    static final String PARAM_SERVER = "serverName";
    /** 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 sParamDaemon = pRequest.getParameter(PARAM_DAEMON);
        String sParamServer = pRequest.getParameter(PARAM_SERVER);
        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 ((sParamDaemon == null) || (sParamDaemon.length() == 0)) {
            doViewError("Parameter <i>Daemon name</i> not found", pRequest, out);
        } else if ((sParamServer == null) || (sParamServer.length() == 0)) {
            doViewError("Parameter <i>Server name</i> not found", pRequest, out);
        } else if ((sParamView == null) || (sParamView.length() == 0) || VIEW_INIT.equals(sParamView)) {
            doViewInit(pRequest, out);
            doViewManagement(sParamDomain, sParamDaemon, sParamServer, pRequest, out);
        } else {
            doViewError("Unknown View", pRequest, out);
        }

    }

    /**
     * Do management opeartions in this view.
     * @param pDomainName Name of domain to access
     * @param pDaemonName Name of the deamon
     * @param pServerName Name of the server to be started by the daemon
     * @param pRequest Http request
     * @param pOut Printer
     */
    protected void doViewManagement(String pDomainName, String pDaemonName, String pServerName, HttpServletRequest pRequest, PrintWriter pOut) {
        Management mgmt = getMgmt();

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

        startServer(onDomain, pDaemonName, pServerName, mgmt, pOut);
        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;
    }
    /**
     * Start a server in domain
     * @param pOnDomain J2EEDomain MBean ObjectName
     * @param pDaemonName daemon name - currently not used
     * @param pServerName server name
     * @param mgmt MEJB
     * @param pOut output stream
     */
    private void startServer(ObjectName pOnDomain, String pDaemonName, String pServerName, Management mgmt, PrintWriter pOut) {
        pOut.println("<h2>Start the server " + pServerName + "</h2>");
        pOut.println("<ul>");
        try {
            String[] signature = {"java.lang.String"};
            String[] params = {pServerName};
            mgmt.invoke(pOnDomain, "startServer", params, signature);
            pOut.println("<li>Server " + pServerName + " started.</li>");
            pOut.println("</ul><br/>");
        } catch (Exception e) {
            pOut.println("<li>Cannot create cluster start the server</li>");
            pOut.println("</ul>");
        }
    }
}