/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 Bull S.A.
 * Contact: jonas-team@ow2.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: MBeanTreeBuilder.java 16123 2009-01-08 12:46:35Z eyindanga $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.webapp.jonasadmin;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanOperationInfo;
import javax.management.ObjectName;
import javax.servlet.http.HttpServletRequest;

import org.ow2.jonas.lib.management.extensions.base.JonasManagementRepr;
import org.ow2.jonas.lib.management.extensions.base.mbean.J2eeMbeanItem;
import org.ow2.jonas.lib.management.extensions.base.mbean.MbeanItem;
import org.ow2.jonas.lib.management.extensions.base.mbean.OwnerMbeanItem;
import org.ow2.jonas.webapp.jonasadmin.common.BeanComparator;
import org.ow2.jonas.webapp.taglib.TreeBuilder;
import org.ow2.jonas.webapp.taglib.TreeControl;
import org.ow2.jonas.webapp.taglib.TreeControlNode;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.util.MessageResources;


/**
 * Implementation of <code>TreeBuilder</code> that adds the nodes required
 * for administering the Jonas server.
 *
 * @author Michel-Ange ANTON (initial developer)
 * @author Florent Benoit (changes for struts 1.2.2)
 */

public class MBeanTreeBuilder implements TreeBuilder {
// ----------------------------------------------------- Instance Variables

// ---------------------------------------------------- TreeBuilder Methods

    /**
     * Add the required nodes to the specified <code>treeControl</code>
     * instance.
     *
     * @param treeControl The <code>TreeControl</code> to which we should
     *  add our nodes
     * @param servlet The controller servlet for the admin application
     * @param request The servlet request we are processing
     */
    public void buildTree(final TreeControl treeControl, final ActionServlet servlet
        , final HttpServletRequest request) {
        try {
            TreeControlNode rootNode = treeControl.getRoot();
            MessageResources resources = (MessageResources) servlet.getServletContext().
                getAttribute(Globals.MESSAGES_KEY);
            getMBeans(rootNode, resources, request);
        } catch (Throwable t) {
            t.printStackTrace(System.out);
        }
    }

// ------------------------------------------------------ Protected Methods

    /**
     * Append nodes for all defined MBeans.
     *
     * @param rootNode Root node for the tree control
     * @param resources The MessageResources for our localized messages
     *
     * @exception Exception if an exception occurs building the tree
     */
    public void getMBeans(TreeControlNode rootNode, MessageResources resources,
            HttpServletRequest request)
        throws Exception {

        TreeControlNode nodeMBeans = new TreeControlNode("mbeans", "icon/mbeans.gif"
            , resources.getMessage("treenode.allmbeans"), "ListMBeans.do", "content", false);
        rootNode.addChild(nodeMBeans);

        WhereAreYou oWhere = (WhereAreYou) request.getSession().getAttribute(WhereAreYou.
            SESSION_NAME);
        String serverName = oWhere.getCurrentJonasServerName();

        ArrayList[] als = JonasAdminJmx.getFamiliesMbeansLists(serverName);
        if (als[MbeanItem.FAMILY_J2EE].size() > 0) {
            getJ2eeMBeans(nodeMBeans, resources, als[MbeanItem.FAMILY_J2EE]);
        }
        if (als[MbeanItem.FAMILY_OWNER].size() > 0) {
            getOwnerMBeans(nodeMBeans, resources, als[MbeanItem.FAMILY_OWNER]);
        }
        if (als[MbeanItem.FAMILY_UNKNOWN].size() > 0) {
            getUnknownMBeans(nodeMBeans, resources, als[MbeanItem.FAMILY_UNKNOWN]);
        }
    }

    /**
     * Append nodes for all defined Owner MBeans.
     *
     * @param p_ParentNode Parent node for the tree control
     * @param p_Resources The MessageResources for our localized messages
     * @param p_List The list of Mbeans
     *
     * @exception Exception if an exception occurs building the tree
     */
    public void getOwnerMBeans(TreeControlNode p_ParentNode, MessageResources p_Resources
        , ArrayList p_List)
        throws Exception {

        TreeControlNode nodeMBeans = new TreeControlNode("mbeans" + WhereAreYou.NODE_SEPARATOR
            + "owner", "icon/mbeans.gif", p_Resources.getMessage("treenode.mbeans.owner")
            , "ListOwnerMBeans.do", "content", false);
        p_ParentNode.addChild(nodeMBeans);
        // Sort list
        Collections.sort(p_List, new BeanComparator(new String[] {
            "domain", "type", "objectName"}));

        // Detail MBean node
        String sLastDomain = "";
        String sLastType = "";
        TreeControlNode nodeMBean = null;
        TreeControlNode nodeDomain = null;
        TreeControlNode nodeType = null;
        TreeControlNode nodeParent = null;
        OwnerMbeanItem oItem;

        Iterator it = p_List.iterator();
        while (it.hasNext()) {
            oItem = (OwnerMbeanItem) it.next();

            nodeParent = nodeMBeans;
            if (oItem.getDomain() != null) {
                // Domain node
                if (oItem.getDomain().equals(sLastDomain) == false) {
                    sLastDomain = oItem.getDomain();
                    nodeDomain = new TreeControlNode(nodeParent.getName()
                        + WhereAreYou.NODE_SEPARATOR + oItem.getDomain(), "icon/mbeandomain.gif"
                        , oItem.getDomain(), null, "content", false);
                    nodeMBeans.addChild(nodeDomain);
                }
                nodeParent = nodeDomain;

                if (oItem.getType() != null) {
                    // Type node
                    if (oItem.getType().equals(sLastType) == false) {
                        sLastType = oItem.getType();
                        nodeType = new TreeControlNode(nodeParent.getName()
                            + WhereAreYou.NODE_SEPARATOR + oItem.getType(), "icon/mbeantype.gif"
                            , oItem.getType(), null, "content", false);
                        nodeDomain.addChild(nodeType);
                    }
                    nodeParent = nodeType;
                }
            }

            // Mbean node
            nodeMBean = new TreeControlNode("mbeans" + WhereAreYou.NODE_SEPARATOR
                + oItem.getObjectName(), "icon/mbean.gif", oItem.getObjectName()
                , "ListMBeanDetails.do?select=" + URLEncoder.encode(oItem.getObjectName()
                , "UTF-8"), "content", false);
            nodeParent.addChild(nodeMBean);

        }
    }

    /**
     * Append nodes for all defined J2EE MBeans.
     *
     * @param p_ParentNode Parent node for the tree control
     * @param p_Resources The MessageResources for our localized messages
     * @param p_List The list of Mbeans
     *
     * @exception Exception if an exception occurs building the tree
     */
    public void getJ2eeMBeans(TreeControlNode p_ParentNode, MessageResources p_Resources
        , ArrayList p_List)
        throws Exception {

        TreeControlNode nodeMBeans = new TreeControlNode("mbeans" + WhereAreYou.NODE_SEPARATOR
            + "j2ee", "icon/mbeans.gif", p_Resources.getMessage("treenode.mbeans.j2ee")
            , "ListJ2eeMBeans.do", "content", false);
        p_ParentNode.addChild(nodeMBeans);
        // Sort list
        Collections.sort(p_List, new BeanComparator(new String[] {
            "domain", "j2eeType", "name", "objectName"}));

        // Detail MBean node
        J2eeMbeanItem oItem;
        String sLastDomain = "";
        String sLastType = "";
        TreeControlNode nodeMBean = null;
        TreeControlNode nodeDomain = null;
        TreeControlNode nodeType = null;
        TreeControlNode nodeParent = null;

        Iterator it = p_List.iterator();
        while (it.hasNext()) {
            oItem = (J2eeMbeanItem) it.next();

            nodeParent = nodeMBeans;
            if (oItem.getDomain() != null) {
                // Domain node
                if (oItem.getDomain().equals(sLastDomain) == false) {
                    sLastDomain = oItem.getDomain();
                    nodeDomain = new TreeControlNode(nodeParent.getName()
                        + WhereAreYou.NODE_SEPARATOR + oItem.getDomain(), "icon/mbeandomain.gif"
                        , oItem.getDomain(), null, "content", false);
                    nodeMBeans.addChild(nodeDomain);
                }
                nodeParent = nodeDomain;
            }
            if (oItem.getJ2eeType() != null) {
                // Type node
                if (oItem.getJ2eeType().equals(sLastType) == false) {
                    sLastType = oItem.getJ2eeType();
                    nodeType = new TreeControlNode(nodeParent.getName()
                        + WhereAreYou.NODE_SEPARATOR + oItem.getJ2eeType(), "icon/mbeantype.gif"
                        , oItem.getJ2eeType(), null, "content", false);
                    nodeDomain.addChild(nodeType);
                }
                nodeParent = nodeType;
            }

            // Mbean node
            nodeMBean = new TreeControlNode("mbeans" + WhereAreYou.NODE_SEPARATOR
                + oItem.getObjectName(), "icon/mbean.gif", oItem.getObjectName()
                , "ListMBeanDetails.do?select=" + URLEncoder.encode(oItem.getObjectName()
                , "UTF-8"), "content", false);
            nodeParent.addChild(nodeMBean);

        }
    }

    /**
     * Append nodes for all defined Unknown MBeans.
     *
     * @param p_ParentNode Parent node for the tree control
     * @param p_Resources The MessageResources for our localized messages
     * @param p_List The list of Mbeans
     *
     * @exception Exception if an exception occurs building the tree
     */
    public void getUnknownMBeans(TreeControlNode p_ParentNode, MessageResources p_Resources
        , ArrayList p_List)
        throws Exception {

        TreeControlNode nodeMBeans = new TreeControlNode("mbeans" + WhereAreYou.NODE_SEPARATOR
            + "unknown", "icon/mbeans.gif", p_Resources.getMessage("treenode.mbeans.unknown")
            , "ListUnknownMBeans.do", "content", false);
        p_ParentNode.addChild(nodeMBeans);
        // Sort list
        Collections.sort(p_List, new BeanComparator(new String[] {
            "domain", "objectName"}));

        // Detail MBean node
        MbeanItem oItem;
        String sLastDomain = "";
        TreeControlNode nodeMBean = null;
        TreeControlNode nodeDomain = null;
        TreeControlNode nodeType = null;
        TreeControlNode nodeParent = null;

        Iterator it = p_List.iterator();
        while (it.hasNext()) {
            oItem = (MbeanItem) it.next();

            nodeParent = nodeMBeans;
            if (oItem.getDomain() != null) {
                // Domain node
                if (oItem.getDomain().equals(sLastDomain) == false) {
                    sLastDomain = oItem.getDomain();
                    nodeDomain = new TreeControlNode(nodeParent.getName()
                        + WhereAreYou.NODE_SEPARATOR + oItem.getDomain(), "icon/mbeandomain.gif"
                        , oItem.getDomain(), null, "content", false);
                    nodeMBeans.addChild(nodeDomain);
                }
                nodeParent = nodeDomain;

            }

            // Mbean node
            nodeMBean = new TreeControlNode("mbeans" + WhereAreYou.NODE_SEPARATOR
                + oItem.getObjectName(), "icon/mbean.gif", oItem.getObjectName()
                , "ListMBeanDetails.do?select=" + URLEncoder.encode(oItem.getObjectName()
                , "UTF-8"), "content", false);
            nodeParent.addChild(nodeMBean);

        }
    }

    /**
     * Append nodes Attributes and Operations for a defined MBean.
     *
     * @param nodeMBean The MBean node
     * @param onMBean The MBean Object name
     * @param resources Resource
     * @throws Exception
     */
    protected void getMBeanInfo(TreeControlNode nodeMBean, ObjectName onMBean
        , MessageResources resources, String serverName)
        throws Exception {
        // Get all infos of a MBean
        MBeanInfo oMBeanInfo = JonasManagementRepr.getMBeanInfo(onMBean, serverName);
        // Get attributes infos
        MBeanAttributeInfo[] aoMBeanAttributeInfo = oMBeanInfo.getAttributes();
        if (aoMBeanAttributeInfo.length > 0) {
            // Append attributes node
            TreeControlNode nodeAttributes = new TreeControlNode("Attributes"
                + WhereAreYou.NODE_SEPARATOR + onMBean.toString(), "icon/JonasQuestion.gif"
                , resources.getMessage("treenode.allmbeans.attributes"), null, "content", false);
            nodeMBean.addChild(nodeAttributes);
            // Loop to append each attribute node
            for (int i = 0; i < aoMBeanAttributeInfo.length; i++) {
                TreeControlNode nodeAttr = new TreeControlNode(String.valueOf(i)
                    + WhereAreYou.NODE_SEPARATOR + onMBean.toString() + WhereAreYou.NODE_SEPARATOR
                    + aoMBeanAttributeInfo[i].getName(), "icon/property.gif"
                    , aoMBeanAttributeInfo[i].getName(), null, "content", false);
                nodeAttributes.addChild(nodeAttr);
            }
        }
        // Get operations infos
        MBeanOperationInfo[] aoMBeanOperationInfo = oMBeanInfo.getOperations();
        if (aoMBeanOperationInfo.length > 0) {
            // Append operations node
            TreeControlNode nodeOperations = new TreeControlNode("Operations"
                + WhereAreYou.NODE_SEPARATOR + onMBean.toString(), "icon/JonasQuestion.gif"
                , resources.getMessage("treenode.allmbeans.operations"), null, "content", false);
            nodeMBean.addChild(nodeOperations);
            // Loop to append each operation node
            for (int i = 0; i < aoMBeanOperationInfo.length; i++) {
                TreeControlNode nodeOpe = new TreeControlNode(String.valueOf(i)
                    + WhereAreYou.NODE_SEPARATOR + onMBean.toString() + WhereAreYou.NODE_SEPARATOR
                    + aoMBeanOperationInfo[i].getName(), "icon/action.gif"
                    , aoMBeanOperationInfo[i].getName(), null, "content", false);
                nodeOperations.addChild(nodeOpe);
            }
        }
    }
}
