/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2008 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.lib.management.extensions.server;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.TabularData;
import javax.management.remote.JMXServiceURL;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;
import org.ow2.jonas.lib.management.extensions.base.BaseManagement;
import org.ow2.jonas.lib.management.extensions.base.JonasManagementRepr;
import org.ow2.jonas.lib.util.Log;
import org.ow2.jonas.management.extensions.server.api.IServerManagement;
/**
 * Implements server management functions.
 * @author Adriana Danes
 * @author Oualaa Hani
 *
 */
public class ServerManagement extends BaseManagement implements IServerManagement {

    protected static Logger logger = Log.getLogger("org.ow2.jonas.lib.management.extensions.server");

    /**
     * A JOnAS JMX server's connector URL is constructed as follows :
     * protocol+connector_prefix+serverName
     */
    private static String connector_prefix = "connector_";
    /**
     * Constructor.
     */
    public ServerManagement() {
        super();
    }

    /**
     * Return a managed server's threads information.
     * @param serverName The managed server name
     * @throws Exception when operation invocation fails
     */
    public List<List<String>> getServerThreadsInformation(final String serverName) throws Exception {
        ObjectName on = null;
        String operation = "getThreadStackDumpList";
        String server = getDomainName() +":j2eeType=J2EEServer,name=" + serverName;
        List<List<String>> result = new ArrayList<List<String>>();
        try {
            on = new ObjectName(server);
            Object[] param = null;
            String[] signature = null;
            TabularData tabData = (TabularData) JonasManagementRepr.invoke(on, operation,
                    param, signature, serverName);

            CompositeDataSupport cmpData = null;

            for (Object ob : tabData.values()) {
                cmpData = (CompositeDataSupport) ob;
                ArrayList<String> subResult = new ArrayList<String>();
                subResult.add(cmpData.get("id").toString());
                subResult.add(cmpData.get("name").toString());
                subResult.add(cmpData.get("priority").toString());
                subResult.add(cmpData.get("is alive").toString());
                subResult.add(cmpData.get("is interrupted").toString());
                subResult.add(cmpData.get("state").toString());
                subResult.add(cmpData.get("is daemon").toString());
                subResult.add(cmpData.get("stackTrace").toString());
                result.add(subResult);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Could not invoke method \"" + operation
                    + "\" on server \"" + server + "\"");
        }

        return result;
    }
    /**
     * Return a managed server's threads information.
     * @param serverName The managed server name
     * @throws Exception when operation invocation fails
     */
    public List<List<String>> getServerThreadsInformation(final String jmxUrl, final String username, final String password) throws Exception {
        ObjectName on = null;
        String operation = "getThreadStackDumpList";
        List<List<String>> result = new ArrayList<List<String>>();
        try {
            on = getServerOn(jmxUrl);
            Object[] param = null;
            String[] signature = null;
            TabularData tabData = (TabularData) JonasManagementRepr.invoke(on, operation,
                    param, signature, jmxUrl, username, password);

            CompositeDataSupport cmpData = null;

            for (Object ob : tabData.values()) {
                cmpData = (CompositeDataSupport) ob;
                ArrayList<String> subResult = new ArrayList<String>();
                subResult.add(cmpData.get("id").toString());
                subResult.add(cmpData.get("name").toString());
                subResult.add(cmpData.get("priority").toString());
                subResult.add(cmpData.get("is alive").toString());
                subResult.add(cmpData.get("is interrupted").toString());
                subResult.add(cmpData.get("state").toString());
                subResult.add(cmpData.get("is daemon").toString());
                subResult.add(cmpData.get("stackTrace").toString());
                result.add(subResult);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Could not invoke method \"" + operation
                    + "\" on server \"" + on.getKeyProperty("name") + "\"");
        }

        return result;
    }

    private ObjectName getServerOn(final String jmxUrl) throws MalformedObjectNameException {
        JMXServiceURL url = null;
        ObjectName on = null;
        try {
            url = new JMXServiceURL(jmxUrl);
            String urlPath = url.getURLPath();
            int prefixIndex = urlPath.indexOf(connector_prefix);
            int serverNameIndex = prefixIndex + connector_prefix.length();
            String serverName = urlPath.substring(serverNameIndex);
            String server = getDomainName() +":j2eeType=J2EEServer,name=" + serverName;
            on = ObjectName.getInstance(server);
        } catch (MalformedURLException me) {
            logger.log(BasicLevel.ERROR, "Malformed URL:" + jmxUrl);
        }
        return on;
    }
}
