/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 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$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.webapp.jonasadmin.mbean;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import javax.management.ObjectName;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ow2.jonas.lib.management.extensions.base.JonasManagementRepr;
import org.ow2.jonas.lib.management.extensions.base.mbean.MbeanItem;
import org.ow2.jonas.webapp.jonasadmin.WhereAreYou;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * List of all Attributes for a MBean.
 *
 * @author Michel-Ange ANTON
 */

public final class ListMBeanAttributesAction extends ListMBeanDetailsAction {

// --------------------------------------------------------- Public Methods

    public ActionForward executeAction(ActionMapping p_Mapping, ActionForm p_Form
        , HttpServletRequest p_Request, HttpServletResponse p_Response)
        throws IOException, ServletException {

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

        try {
            // Save current action
            setAction(ACTION_ATTRIBUTES);
            // Parameter
            String sSelect = p_Request.getParameter("select");

            // Create a request attribute with our collection of MBeans
            ArrayList list = new ArrayList();
            // Get all infos of a MBean
            ObjectName on = new ObjectName(sSelect);
            MbeanItem oItem = MbeanItem.build(on);
            MBeanInfo oMBeanInfo = JonasManagementRepr.getMBeanInfo(on, serverName);
            // Get attributes infos
            MBeanAttributeInfo[] aoAttributes = oMBeanInfo.getAttributes();
            if (aoAttributes.length > 0) {
                Object oValue;
                String sError;
                // Loop to append each attribute node
                for (int i = 0; i < aoAttributes.length; i++) {
                    sError = null;
                    oValue = null;
                    try {
                        oValue = JonasManagementRepr.getAttribute(on, aoAttributes[i].getName(), serverName);
                    } catch (Exception ex) {
                        sError = ex.getMessage();
                    }
                    list.add(new ViewMBeanAttributes(aoAttributes[i], oValue, sError));
                }
                // Sort
                Collections.sort(list, new MBeanAttributesByName());
            }
            // Infos for displaying
            p_Request.setAttribute("MBean", oItem);
            p_Request.setAttribute("MBeanAttributes", list);
            // Active and save filtering display if not exists
            MbeanFilteringForm oForm = (MbeanFilteringForm) m_Session.getAttribute(
                "mbeanFilteringForm");
            if (oForm == null) {
                oForm = new MbeanFilteringForm();
                oForm.reset(p_Mapping, p_Request);
                m_Session.setAttribute("mbeanFilteringForm", oForm);
            }
            oForm.setSelectedName(sSelect);
            // Force the node selected in tree when the direct is used (MBeans list)
            StringBuffer sbBranch = new StringBuffer("domain*mbeans");
            sbBranch.append(WhereAreYou.NODE_SEPARATOR);
            sbBranch.append(sSelect);
            m_WhereAreYou.selectNameNode(sbBranch.toString(), true);
        } catch (Throwable t) {
            addGlobalError(t);
            saveErrors(p_Request, m_Errors);
            return (p_Mapping.findForward("Global Error"));
        }
        // Forward to the corresponding display page
        return p_Mapping.findForward("List MBean Attributes");
    }

// --------------------------------------------------------- Inner Classes

    public class ViewMBeanAttributes {
        private String name;
        private String type;
        private String is;
        private String read;
        private String write;
        private String description;
        private String value;
        private String errorMessage;
        private boolean error;

        public ViewMBeanAttributes(MBeanAttributeInfo po_Attr, Object po_Value, String ps_Error) {
            setName(po_Attr.getName());
            setType(po_Attr.getType());
            setDescription(po_Attr.getDescription());
            setObjectValue(po_Value);
            setErrorMessage(ps_Error);
            if (ps_Error != null) {
                setError(true);
            }
            if (po_Attr.isIs() == true) {
                setIs("is");
            }
            if (po_Attr.isReadable() == true) {
                setRead("read");
            }
            if (po_Attr.isWritable() == true) {
                setWrite("write");
            }
        }

        public void setObjectValue(Object objectValue) {
            if (objectValue == null) {
                value = "null";
            }
            else {
                // Detect Array or Collection
                if (objectValue.getClass().isArray() == true) {
                    // Array
                    value = arrayToString((Object[]) objectValue);
                }
                else {
                    try {
                        // Collection
                        value = collectionToString((Collection) objectValue);
                    }
                    catch (Exception e) {
                        // Default
                        value = objectValue.toString();
                    }
                }
            }
        }

        public String arrayToString(Object[] p_Array) {
            StringBuffer sb = new StringBuffer();
            sb.append("[ ");
            for (int i = 0; i < p_Array.length; i++) {
                if (p_Array[i] == null) {
                    sb.append("null");
                }
                else {
                    sb.append(p_Array[i].toString());
                }
                if ((i + 1) < p_Array.length) {
                    sb.append(" - ");
                }
            }
            sb.append(" ]");
            return sb.toString();
        }

        public String collectionToString(Collection p_Collection) {
            StringBuffer sb = new StringBuffer();
            sb.append("[ ");
            Iterator it = p_Collection.iterator();
            while (it.hasNext()) {
                sb.append(it.next().toString());
                if (it.hasNext()) {
                    sb.append(" - ");
                }
            }
            sb.append(" ]");
            return sb.toString();
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getIs() {
            return is;
        }

        public void setIs(String is) {
            this.is = is;
        }

        public String getRead() {
            return read;
        }

        public void setRead(String read) {
            this.read = read;
        }

        public String getWrite() {
            return write;
        }

        public void setWrite(String write) {
            this.write = write;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public String getErrorMessage() {
            return errorMessage;
        }

        public void setErrorMessage(String errorMessage) {
            this.errorMessage = errorMessage;
        }

        public boolean isError() {
            return error;
        }

        public void setError(boolean error) {
            this.error = error;
        }
    }

    public class MBeanAttributesByName implements Comparator {

        public int compare(Object p_O1, Object p_O2) {
            ViewMBeanAttributes o1 = (ViewMBeanAttributes) p_O1;
            ViewMBeanAttributes o2 = (ViewMBeanAttributes) p_O2;
            return o1.getName().compareToIgnoreCase(o2.getName());
        }

        public boolean equals(Object p_Obj) {
            if (p_Obj instanceof ViewMBeanAttributes) {
                return true;
            }
            return false;
        }
    }

}
