/**
 * 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: ServerManagement.java 18898 2009-10-23 07:25:28Z danesa $
 * --------------------------------------------------------------------------
 */
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.management.javaee.J2eeObjectName;
import org.ow2.jonas.lib.util.JonasObjectName;
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";
        List<List<String>> result = new ArrayList<List<String>>();
        try {
            on = J2eeObjectName.J2EEServer(getDomainName(), serverName);
            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 \"" + serverName + "\"");
        }

        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;
    }

    /**
     * Deploy a module on a target server in the domain.
     * @param fileName Name of the module's file.
     * @param serverName Target server name.
     * @throws Exception deploy operation failed.
     */
    public void deploy(final String fileName, final String serverName) throws Exception {
        ObjectName on = null;
        String operation = "deploy";
        try {
            on = J2eeObjectName.J2EEServer(getDomainName(), serverName);
            Object[] param = new String[1];
            param[0] = fileName;
            String[] signature = { "java.lang.String" };
            JonasManagementRepr.invoke(on, operation, param, signature, serverName);
        } catch (Exception e) {
            throw new Exception("Could not invoke method \"" + operation
                    + "\" on server \"" + serverName + "\"");
        }
    }

    /**
     * Uneploy a module on a target server.
     * @param fileName Name of the module's file.
     * @param serverName Target server name.
     * @throws Exception undeploy operation failed.
     */
    public void undeploy(final String fileName, final String serverName) throws Exception {
        ObjectName on = null;
        String operation = "undeploy";
        try {
            on = J2eeObjectName.J2EEServer(getDomainName(), serverName);
            Object[] param = new String[1];
            param[0] = fileName;
            String[] signature = { "java.lang.String" };
            JonasManagementRepr.invoke(on, operation, param, signature, serverName);
        } catch (Exception e) {
            throw new Exception("Could not invoke method \"" + operation
                    + "\" on server \"" + serverName + "\"");
        }
    }

    /**
     * Remove a module on a target server.
     * @param fileName Name of the module's file.
     * @param serverName Target server name.
     * @return true if the file successfully deleted
     * @throws Exception remove operation failed.
     */
    public boolean remove(final String fileName, final String serverName) throws Exception {
        ObjectName on = null;
        String operation = "removeModuleFile";
        try {
            on = J2eeObjectName.J2EEServer(getDomainName(), serverName);
            Object[] param = new String[1];
            param[0] = fileName;
            String[] signature = { "java.lang.String" };
            JonasManagementRepr.invoke(on, operation, param, signature, serverName);
        } catch (Exception e) {
            throw new Exception("Could not invoke method \"" + operation
                    + "\" on server \"" + serverName + "\"");
        }
        return true;
    }
    /**
     * Return true if a given service is in 'development' mode for a given server managed in the domain.
     * @param serviceName The service name, for example "depmonitor".
     * @param serverName Target server name.
     * @return true if a given service is in 'development' mode, false otherwise
     * @throws Exception
     */
    public boolean developmentMode(final String serviceName, final String serverName) throws Exception {
        ObjectName on = null;
        String attribute = "development";
        Object resultObj = null;
        boolean result;
        try {
            on = JonasObjectName.deployableMonitorService(getDomainName());
            resultObj = JonasManagementRepr.getAttribute(on, attribute, serverName);
        } catch (Exception e) {
            throw new Exception("Could not get attribute \"" + attribute + " for service \"" + serviceName
                    + "\" on server \"" + serverName + "\"");
        }
        if (resultObj != null) {
            result = ((Boolean) resultObj).booleanValue();
        } else {
            throw new Exception("Got null attribute \"" + attribute + " for service \"" + serviceName
                    + "\" on server \"" + serverName + "\"");
        }
        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;
    }
}
