/**
 * 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.jms.Topic;
import javax.management.MalformedObjectNameException;
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.
 * The MEJB is used to invoke JoramAdmin Bean operations.
 * @author JOnAS team
 * @author Adriana Danes
 */
public class JmsAdminServlet extends J2eemanagementBaseServlet {
    /** Parameter */
    static final String PARAM_TOPIC = "topicName";
    /** Parameter */
    static final String PARAM_SERVER_ID = "serverId";
    /** 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 initialize servlet
     */
    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 Could not execute request
     * @throws ServletException An input or output error is detected when the servlet handles the 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 sParamTopic = pRequest.getParameter(PARAM_TOPIC);
        String sParamServerId = pRequest.getParameter(PARAM_SERVER_ID);
        String sParamView = pRequest.getParameter(PARAM_VIEW);

        // Dispatching
        if ((sParamTopic == null) || (sParamTopic.length() == 0)) {
            doViewError("Parameter <i>Topic name</i> not found", pRequest, out);
        } else if ((sParamServerId == null) || (sParamServerId.length() == 0)) {
            doViewError("Parameter <i>Joram server id</i> not found", pRequest, out);
        } else if ((sParamView == null) || (sParamView.length() == 0) || VIEW_INIT.equals(sParamView)) {
            doViewInit(pRequest, out);
            doViewManagement(sParamTopic, sParamServerId, pRequest, out);
        } else {
            doViewError("Unknown View", pRequest, out);
        }

    }



    /**
     * View init MEJB and access to MBEans J2EEDomain and J2EEServer.
     * @param pTopicName Name of topic to create
     * @param pServerId Joram server Id
     * @param pRequest Http request
     * @param pOut Printer
     */
    protected void doViewManagement(String pTopicName, String pServerId, HttpServletRequest pRequest, PrintWriter pOut) {

        // -------------------------------------------------------------
        // Use the Joram MBean via the MEJB to make jms admin operations
        // -------------------------------------------------------------
        pOut.println("<h2>Get Joram admin MBean</h2>");
        pOut.println("<ul>");
        Management mgmt = getMgmt();

        String joramON = getInitParameter("mbeanName");
        if (joramON == null) {
            joramON = "joramClient:type=JoramAdmin";
        } else {
            pOut.println("<li>Use servlet init param 'mbeanName': " + joramON + "</li>");
        }
        ObjectName joramOn = null;
        try {
            joramOn = ObjectName.getInstance(joramON);
        } catch (MalformedObjectNameException e1) {
            pOut.println("<li>Couldn't get Joram MBean</li>" + e1);
            pOut.println("</ul>");
            printNavigationFooter(pRequest, pOut);
            return;
        }
        pOut.println("</ul><br/>");
        pOut.println("<h2>Use Joram admin MBean</h2>");
        pOut.println("<ul>");

        try {
            if (mgmt.isRegistered(joramOn)) {
                Object[] asParam = {new Integer(pServerId), pTopicName };
                String[] asSignature = {
                        "int", "java.lang.String"
                };
                String op = "createTopic";
                Topic topic = (Topic) mgmt.invoke(joramOn, op, asParam, asSignature);
                getInitialContext().rebind(pTopicName, topic);
                pOut.println("<li>Topic " + pTopicName + " created on server " + pServerId + "</li>");
            }
        } catch (Exception e) {
            pOut.println("<li>Could not use use Joram MBean to administer jms</li>" + e);
            pOut.println("</ul>");
            printNavigationFooter(pRequest, pOut);
            return;
        }

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

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

        // Footer
        printNavigationFooter(pRequest, pOut);
    }

}