/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2006-2008 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.io.PrintWriter;

import javax.management.ObjectName;
import javax.management.j2ee.Management;
import javax.management.j2ee.ManagementHome;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Adriana Danes
 *
 * Base classe containing common code for the j2eeManagement servlets
 */
public class J2eemanagementBaseServlet extends HttpServlet {
     /** Printing constant*/
    static final String APP_TITLE = "J2EE Management sample";
    /**
     * Standard J2EEManagement Bean
      */
    private Management mgmt = null;
    /**
     * Naming context
     */
    private Context initialContext = null;

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

        pOut.println("<html>");
        pOut.println("<head>");
        pOut.println("<title>" + pTitle);
        if (pSubTitle != null) {
            pOut.println(" - " + pSubTitle);
        }
        pOut.println("</title>");
        pOut.println("</head>");
        pOut.println("<body style=\"background : white; color : black;\">");
        printHeaderTitle(pOut, pTitle, pSubTitle);
    }
    /**
     * Header title.
     * @param pOut Printer
     * @param pTitle Title to display
     * @param pSubTitle Subtitle to display or null if not
     */
    protected void printHeaderTitle(PrintWriter pOut, String pTitle, String pSubTitle) {

        pOut.println("<table width=\"100%\" border=\"0\">");
        pOut.println("<tr>");
        pOut.println("<td rowspan=\"2\"><img src=\"img/logo_jonas.jpg\" alt=\"JOnAS Logo\"></td>");
        pOut.println("<td align=\"center\"><h1>" + pTitle + "</h1></td>");
        pOut.println("</tr>");
        pOut.println("<tr>");
        if (pSubTitle != null) {
            pOut.println("<td align=\"center\"><h1>" + pSubTitle + "</h1></td>");
        }
        pOut.println("</tr>");
        pOut.println("</table>");
    }

    /**
     * Footer navigation.
     * @param pRequest Http request
     * @param pOut Printer
     */
    protected void printNavigationFooter(HttpServletRequest pRequest, PrintWriter pOut) {

        // index
        String sViewIndex = pRequest.getContextPath();

        // 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.println("</tr></table>");
        // Footer
        printFooter(pOut);
    }
    /**
     * Footer.
     * @param pOut Printer
     */
    protected void printFooter(PrintWriter pOut) {
        pOut.println("</body>");
        pOut.println("</html>");
    }

    /**
     * @param pRequest Client request
     * @param pOut  Writer for output
     */
    protected void doViewInit(HttpServletRequest pRequest, PrintWriter pOut) {
        // -----------------------------
        // Get initial context
        // -----------------------------
        pOut.println("<h2>Create Initial naming context</h2>");
        pOut.println("<ul>");
        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>");
            printNavigationFooter(pRequest, pOut);
            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>");
            printNavigationFooter(pRequest, pOut);
            return;
        }

        // Management bean creation
        try {
            mgmt = mgmtHome.create();
            pOut.println("<li>MEJB created</li>");
        } catch (Exception e) {
            pOut.println("<li>Cannot create MEJB: " + e + "</li>");
            pOut.println("</ul>");
            printNavigationFooter(pRequest, pOut);
            return;
        }

        pOut.println("</ul><br/>");
    }

    /**
     * Simply View error.
     * @param pError Message error
     * @param pRequest Http request
     * @param pOut Printer
     */
    protected void doViewError(String pError, HttpServletRequest pRequest, PrintWriter pOut) {

        // Header
        printHeader(pOut, APP_TITLE, "Error");
        // Error message
        pOut.println("<h2>" + pError + "</h2>");
        // Return
        pOut.println("<a href=\"" + pRequest.getContextPath() + "\">Return</a>");
        // Footer
        printFooter(pOut);
    }
    /**
     * @return The management bean
     */
    public Management getMgmt() {
        return mgmt;
    }
    /**
     * @return The initial naming context
     */
    public Context getInitialContext() {
        return initialContext;
    }

    /**
     * Check if the current server is a master
     * @param pOnDomain J2EEDomain MBean's ObjectName
     * @return true if the server is a master, false otherwise
     */
    protected boolean isMaster(ObjectName pOnDomain, Management mgmt, PrintWriter pOut) {
        pOut.println("<h2>Use the J2EEDomain MBean to check if the current server is a master</h2>");
        pOut.println("<ul>");
        boolean result = false;
        try {
            result = ((Boolean) mgmt.getAttribute(pOnDomain, "master")).booleanValue();
        } catch (Exception e) {
            pOut.println("<li>Error when using this J2EEDomain MBean: " + e + "</li>");
            pOut.println("</ul>");
            return false;
        }
        if (result) {
            pOut.println("<li>This is a Master server.</li>");
        } else {
            pOut.println("<li><b>This server is not a Master !</b></li>");
        }
        pOut.println("</ul>");
        return result;
    }
}
