/*
 * 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
 *
 * Initial developer(s): ____________________________________.
 * Contributor(s): ______________________________________.
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.jmx.vjadmin.servlet;

// servlet imports
import javax.servlet.*;
import javax.servlet.http.*;

// standard imports
import java.util.Date;
import java.util.Properties;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

// velocity imports
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.servlet.VelocityServlet;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;

// JOnAS JMX imports
import org.objectweb.jonas.jmx.*;
// JMX
import javax.management.ObjectName;
import javax.management.MalformedObjectNameException;

// Jadmin imports
import org.objectweb.jonas.jmx.vjadmin.*;

// monolog imports
import org.objectweb.util.monolog.api.Logger;
import org.objectweb.util.monolog.api.BasicLevel;

// JOnAS log imports
import org.objectweb.jonas.common.Log;

public class MdbServlet extends VelocityServlet {
    static private Logger logger = null;

    public void init(ServletConfig config ) throws ServletException {
	super.init(config);
	logger = Log.getLogger(ServletLog.JONAS_VELO_SERVLET_PREFIX);
    }

    /** 
     * Creates a VelocityContext. 
     */
    protected Context createContext( HttpServletRequest request, HttpServletResponse response) { 
	HttpSession session = request.getSession();
	// Try to get the initial VelocityContext
	VelocityContext initialContext = (VelocityContext)session.getAttribute("initialContext");
	if (initialContext == null) {
	    // initial context lost, recreate it
	    initialContext = InitVeloContext.doIt(session);
	    logger.log(BasicLevel.DEBUG, "Initial VelocityContext lost. Create, initialize and attach to the session a new initial VelocityContext");
	}
	VelocityContext context = new VelocityContext(initialContext);
	logger.log(BasicLevel.DEBUG, "Create a new VelocityContext containing the initial one");
	return context;
    }

    /**
     *
     *
     *  @param ctx a Velocity Context object to be filled with
     *             data.  Will be used for rendering this 
     *             template
     *  @return Template to be used for request
     */   

    public Template handleRequest( HttpServletRequest request, 
				   HttpServletResponse response, 
				   Context context ) { 

	// Exception treatement
	String alertException = null;

 	// Get Date
	String date = java.text.DateFormat.getInstance().format(new Date());
	context.put("date", date);

	// Get request parameters
	String fileName = null;
	String ejbName = null;
	try {
	    for (Enumeration e = request.getParameterNames() ; e.hasMoreElements() ;) {
		String paramName = (String)e.nextElement();
		if (paramName.equals("fileName")) {
		    fileName = request.getParameter("fileName");
		    context.put("fileName", fileName);
		} else if (paramName.equals("ejbName")) {
		    ejbName = request.getParameter("ejbName");
		    context.put("ejbName", ejbName);
		}
	    }
	} catch (ManagementException e) {
	    alertException = Script.alert(e.getMessage());
	    context.put("alertException", alertException);
	}

	// Get the container's name
	String cont_error = "";
	try {
	    String contName = (String)JonasManagementRepr.getAttribute(JonasObjectName.container(fileName), "ContainerName");
	    context.put("contName", contName);
	} catch (Exception e) {
	    cont_error = "Error while getting attribute:" + e.getMessage();
	}
	context.put("cont_error", cont_error);
	
	// Get specific information about the MDB bean
	String info_error = "";
	String mdbName_error = "";
	ObjectName MBeanName = null;
	try {
	    // Get the name of the associated MBean
	    MBeanName = JonasObjectName.ejbmdb(fileName, ejbName);
	    logger.log(BasicLevel.DEBUG, "MBeanName = " + MBeanName.toString());

	    // Get the EJB's class name
	    String ejbClass = (String)JonasManagementRepr.getAttribute(MBeanName, "EJBClass");
	    context.put("ejbClass", ejbClass);

	    // Get the associated Jms Destination 
	    String destName = (String)JonasManagementRepr.getAttribute(MBeanName, "MdbJMSAssociateDestinationName");
	    context.put("destName", destName);
	} catch (MalformedObjectNameException me) {
	    mdbName_error = me.getMessage();
	} catch (Exception e) {
	    info_error = e.getMessage();
	}
	context.put("info_error", info_error);
	context.put("mdbName_error", mdbName_error);

	String datasource_error = "";
	try {
	    // Get data sources
	    Vector dataSources = new Vector();
	    //java.util.Set allDataSources = (java.util.Set)JonasManagementRepr.getAttribute(MBeanName_bean, "AllDataSourceName");
	    java.util.Set allDataSources = (java.util.Set)JonasManagementRepr.getAttribute(MBeanName, "AllDataSourceName");
	    context.put("nbDatasources", new Integer(allDataSources.size()));
	    String dataSourceName = null;
	    for (Iterator i = allDataSources.iterator(); i.hasNext() ;) {
		dataSourceName = (String)i.next();
		dataSources.add(dataSourceName);
	    }
	    context.put("dataSources", dataSources);
	} catch (Exception e) {
	    datasource_error = "Error while getting attribute:" + e.getMessage();
	}
	context.put("datasource_error", datasource_error);

	String jmsConnFact_error = "";
	try {
	    // Get JMS Connection Factories
	    Vector jmsConnFactories = new Vector();
	    //java.util.Set allJmsConnFactories = (java.util.Set)JonasManagementRepr.getAttribute(MBeanName_bean, "AllJMSConnectionFactoryName");
	    java.util.Set allJmsConnFactories = (java.util.Set)JonasManagementRepr.getAttribute(MBeanName, "AllJMSConnectionFactoryName");
	    context.put("nbConnFactories", new Integer(allJmsConnFactories.size()));
	    String jmsConnFactoryName = null;
	    for (Iterator i = allJmsConnFactories.iterator(); i.hasNext() ;) {
		jmsConnFactoryName = (String)i.next();
		jmsConnFactories.add(jmsConnFactoryName);
	    }
	    context.put("jmsConnFactories", jmsConnFactories);
	} catch (Exception e) {
	    jmsConnFact_error = "Error while getting attribute:" + e.getMessage();
	}
	context.put("jmsConnFact_error", jmsConnFact_error);

	String jmsDest_error = "";
	try {
	    // Get JMS Destinations
	    Vector destinations = new Vector();
	    //java.util.Set allDestinations = (java.util.Set)JonasManagementRepr.getAttribute(MBeanName_bean, "AllJMSDestinationName");
	    java.util.Set allDestinations = (java.util.Set)JonasManagementRepr.getAttribute(MBeanName, "AllJMSDestinationName");
	    if (allDestinations.isEmpty())
		logger.log(BasicLevel.DEBUG, "Found no destinations for this bean");
	    else
		logger.log(BasicLevel.DEBUG, "Found " + allDestinations.size() + " destinations");	    
	    context.put("nbDestinations", new Integer(allDestinations.size()));
	    String destinationName = null;
	    for (Iterator i = allDestinations.iterator(); i.hasNext() ;) {
		destinationName = (String)i.next();
		destinations.add(destinationName);
	    }
	    context.put("destinations", destinations);
	} catch (Exception e) {
	    jmsDest_error = "Error while getting attribute:" + e.getMessage();
	}
	context.put("jmsDest_error", jmsDest_error);	

	// Return template
	Template template = null;
	try {
	    template = getTemplate("MDB.vm"); 
	} catch (ParseErrorException pee ) {
            logger.log(BasicLevel.ERROR, "Parse error for template " + pee);
        } catch( ResourceNotFoundException rnfe) {
            logger.log(BasicLevel.ERROR, "Template not found " + rnfe);
        } catch( Exception e) {
            logger.log(BasicLevel.ERROR, "Error " + e);
        }

	return template;
    }
}
