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

package org.objectweb.jonas.jtests.clients.management;

import java.net.MalformedURLException;
import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.InitialContext;

import junit.framework.Test;
import junit.framework.TestSuite;

import org.ow2.carol.util.configuration.ConfigurationRepository;
import org.ow2.carol.util.configuration.ProtocolConfiguration;

import org.objectweb.jonas.jtests.util.JTestCase;

/**
* JMX Service test suite
*
* @author Adriana Danes
*
*/

public class F_Connectors extends JTestCase {

    /**
     * Constructor
     */
    public F_Connectors(String name) {
        super(name);
    }

    /**
     * init environment
     */
    protected void setUp() {
        super.setUp();
    }

    /**
     * This suite is all test cases
     */
    public static Test suite() {
        return new TestSuite(F_Connectors.class);
    }

    public static void main (String args[]) {
        String testtorun = null;
        // Get args
        for (int argn = 0; argn < args.length; argn++) {
            String s_arg = args[argn];

            if (s_arg.equals("-n")) {
                testtorun = args[++argn];
            }
        }
        if (testtorun == null) {
            junit.textui.TestRunner.run(suite());
        } else {
            junit.textui.TestRunner.run(new F_Connectors(testtorun));
        }
    }

    public void testConnectJmxRemote() throws Exception {
        // Prepare ObjectName for J2EEServer MBean
        // This is a well known MBeans which should be registered in the MBean Server
        String sOn = jonasName + ":j2eeType=J2EEServer,name=" + jonasName;
        ObjectName on = null;
        try {
            on = ObjectName.getInstance(sOn);
        } catch (MalformedObjectNameException e) {
            // Can't test the connection if no ObjectName
            fail("Can't create ObjectName for J2EEServer MBean using String: " + sOn);
        }

        // Determine protocols used by Carol and their configuration
        ProtocolConfiguration[] protocolConfigurations = ConfigurationRepository.getConfigurations();
        Properties myCarolConfig = new Properties();
        for (int c = 0; c < protocolConfigurations.length; c++) {
            String protocol = protocolConfigurations[c].getName();
            //if (!protocol.equals("cmi")) {
                myCarolConfig.setProperty(protocol, protocolConfigurations[c].getProviderURL());
            //}
        }

        int nbProtocols = myCarolConfig.size();
        if (nbProtocols == 0) {
            fail("Can't find any protocol in Carol configuration");
        }
        boolean foundJ2EEServerMBean = true;
        for (Iterator it = myCarolConfig.keySet().iterator(); it.hasNext();) {
            String carolProtocol = (String) it.next();
            String sCarolURL = (String) myCarolConfig.get(carolProtocol);
            URI carolURL = new URI(sCarolURL);
            int portNb = carolURL.getPort();
            String port = String.valueOf(portNb);
            String url = null;
            Map env = null;
            if (carolProtocol.equals("jrmp")) {
                // Treat JRMP case
                url = "service:jmx:rmi:///jndi/rmi://localhost:" + port + "/jrmpconnector_" + jonasName;
            } else if (carolProtocol.equals("iiop")) {
                // Treat IIOP case
                url = "service:jmx:iiop:///jndi/iiop://localhost:" + port + "/iiopconnector_" + jonasName;
                env = new HashMap();
                env.put("java.naming.corba.orb", new InitialContext().lookup("java:comp/ORB"));
            } else if (carolProtocol.equals("cmi")) {
                // Treat CMI
                url = "service:jmx:rmi:///jndi/cmi://localhost:" + port + "/cmiconnector_" + jonasName;
            } else {
                continue;
            }
            //System.out.println("===Use URL=== " + url);
            // Try to connect to the MBeanServer
            JMXServiceURL connURL = null;
            try {
                connURL = new JMXServiceURL(url);
            } catch (MalformedURLException e) {
                fail("Can't create JMXServiceURL with string: " + url);
            }
            JMXConnector connector = null;
            try {
                connector = JMXConnectorFactory.newJMXConnector(connURL, env);
            } catch (MalformedURLException e1) {
                fail("there is no provider for the protocol in " + url);
            } catch (java.io.IOException e) {
                fail("Connector client cannot be made because of a communication problem (used URL: " + url + ")");
            }
            MBeanServerConnection currentServerConnection = null;
            try {
                connector.connect(env);
                currentServerConnection = connector.getMBeanServerConnection();
            } catch (java.io.IOException ioe) {
                fail("connection could not be made because of a communication problem");
            }
            // Look up J2EEServer MBean in the MBeanServer
            try {
                foundJ2EEServerMBean = currentServerConnection.isRegistered(on);
            } catch (java.io.IOException ioe) {
                fail("Connected, via " + carolProtocol + ", but can't find MBean " + on.toString() + " in the MBeanServer");
            }

        }
        assertTrue(foundJ2EEServerMBean);
    }
}