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

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.rmi.RemoteException;
import java.util.Set;

import javax.management.Attribute;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import junit.extensions.RepeatedTest;
import junit.framework.TestCase;

import org.objectweb.jonas.jtests.tables.DBEnv;
import org.objectweb.jonas.jtests.tables.DBEnvHome;

/**
 * JTestCase extends TestCase to provide a set of standard routines
 * used in jonas tests.
 */
public abstract class JTestCase extends TestCase {
    protected static String jonasName = "jonas"; // change this XXX
    protected static String testtorun = null;
    protected static Context ictx = null;
    public static UserTransaction utx = null;
    protected static String jb = null;

    protected static MBeanServerConnection cnx = null;

    private static DBEnv dbEnv = null;
    private static boolean tableSessionLoaded = false;

    protected StringBuffer msgerror = null;

    public static final String PACKAGE = "org.objectweb.jonas.jtests.clients.";


    public JTestCase(String name) {
        super(name);
    }

    protected static void callTest(String classname, String testname) throws Exception {
        Class clazz = Class.forName(PACKAGE + classname);
        Class[] paramTypes = {String.class};
        Object[] arguments = {testname};
        Constructor constructor = clazz.getDeclaredConstructor(paramTypes);
        JTestCase mytestcase = (JTestCase) constructor.newInstance(arguments);
        System.out.print("Running " + classname + " (" + testname + ")\t");
        junit.textui.TestRunner.run(mytestcase);
    }

     protected static void callrepeatedTest(String classname, String testname, int n) throws Exception {
        Class clazz = Class.forName(PACKAGE + classname);
        Class[] paramTypes = {String.class};
        Object[] arguments = {testname};
        Constructor constructor = clazz.getDeclaredConstructor(paramTypes);
        JTestCase mytestcase = (JTestCase) constructor.newInstance(arguments);
        RepeatedTest myrepeatedtest = new RepeatedTest(mytestcase,n);
        System.out.print("Running repeated " + n + "times " + classname + " (" + testname + ")\t");
        junit.textui.TestRunner.run(myrepeatedtest);
    }

    /**
     * random returns an integer between 0 and max - 1
     */
    public int random(int max) throws RemoteException {
        double d = Math.random();
        int ret = (int) (max * d);
        return ret;
    }

    /*
     ** Make an absolute path with the filename.
     */
    public String absPath(String name) {
        String ret = jb + "/ejbjars/" + name + ".jar";
        return ret;
    }



    private static JMXServiceURL jmxServerUrl = null;
    private static String urlSuffix = "service:jmx:";
    private static String registry = null;
    private static String defaultRegistry = "rmi://localhost:1099";
    private static String protocol = null;
    private static String defaultProtocol = "jrmp";


    private void getJmxCnx() {
        if (cnx == null) {
            try {
                if (registry == null) {
                    registry = defaultRegistry;
                }
                registry = registry + "/";
                int  indx = registry.lastIndexOf(":");
                String st = registry.substring(0, indx);
                String serverUrl = urlSuffix + st +"/jndi/"+registry;
                if (protocol == null) {
                    protocol = defaultProtocol;
                }
                String connectorName = protocol.concat("connector_");
                connectorName = connectorName.concat(jonasName);
                serverUrl = serverUrl.concat(connectorName);
                jmxServerUrl = new JMXServiceURL(serverUrl);
                System.out.println("JMX connector: "+serverUrl);
                JMXConnector cntor = JMXConnectorFactory.connect(jmxServerUrl, null);
                cnx = cntor.getMBeanServerConnection(null);

            } catch (IOException e) {
                System.err.println("Can't reach server " + jonasName
                        + " as couldn't create JMXConnector (" + e.getMessage()
                        + ")");
                System.err.println("Check name, registry and protocol options.");
                System.exit(2);
            }
        }
    }


    private static ObjectName j2eeserver = null;

    private ObjectName getJ2eeServer() {
        if (j2eeserver == null) {
            try {
                ObjectName on = ObjectName.getInstance("*:j2eeType=J2EEServer,name=" + jonasName);
                Set j2eeservers = cnx.queryNames(on, null);
                if (j2eeservers.isEmpty()) {
                    System.err.println("Can't admin server " + jonasName + ": didn't found J2EEServer MBean");
                    System.exit(2);
                }
                j2eeserver = (ObjectName) j2eeservers.iterator().next();
            } catch (Exception e) {
                System.err.println("Can't invoke mbeanServer: " + e);
            }
        }
        return j2eeserver;
    }

    private void getInitialContext() {
        try {
            ictx = new InitialContext();
        } catch (NamingException e) {
            System.err.println("Can't get InitialContext: " +e);
            System.exit(2);
        }
    }

    private void getUserTransaction() {
        try {
            utx = (UserTransaction) PortableRemoteObject.narrow(ictx.lookup("java:comp/UserTransaction"), UserTransaction.class);
        } catch (NamingException e) {
            System.err.println("Can't get UserTransaction: " +e);
            System.exit(2);
        }
    }


    /**
     * common setUp routine, used for every test.
     */
    protected void setUp() {
        getInitialContext();
        getUserTransaction();
        jb = System.getProperty("jonas.base");
        registry = System.getProperty("registry");
        protocol = System.getProperty("protocol");
        getJmxCnx();


        try {
            // rollback transaction if previous test failed to do so
            if (utx.getStatus() != Status.STATUS_NO_TRANSACTION) {
                utx.rollback();
            }
        } catch (SystemException e) {
            throw new RuntimeException("Cannot use UserTransaction", e);
        }

        // Load Session bean tables.jar
        if (!tableSessionLoaded) {
            String filename = "tables";
            if (!isLoaded(filename)) {
                addBeans(filename);
            }
            tableSessionLoaded = true;
        }
        debug("Junit Running " + getName());
    }

    protected void tearDown() throws Exception {
    }

    /**
     * isLoaded remote operation
     */
    private boolean isLoaded(String filename) {
        String an = absPath(filename);
        boolean ret = false;
        try {
            String[] params = {an};
            String[] signature = {"java.lang.String"};
            try {
                Boolean r = (Boolean) cnx.invoke(getJ2eeServer(), "isDeployed", params, signature);
                ret = r.booleanValue();
            } catch (Exception e) {
                System.err.println("Cannot deploy " + an + ": " + e);
            }

        } catch (Exception e) {
            System.err.println("Cannot test bean: " + e);
        }
        return ret;
    }

    /**
     * addBean remote operation
     */
    public void addBeans(String filename) {
        String an = absPath(filename);
        try {
                String[] params = {an};
                String[] signature = {"java.lang.String"};
                try {
                    cnx.invoke(getJ2eeServer(), "deploy", params, signature);
                } catch (Exception e) {
                    System.err.println("Cannot deploy " + an + ": " + e);
                }
        } catch (Exception e) {
            System.err.println("Cannot load bean: " + e);
        }
    }

    /**
     * unloadBean remote operation
     */
    public void unloadBeans(String filename) {
        String an = absPath(filename);
        try {
                String[] params = {an};
                String[] signature = {"java.lang.String"};
                try {
                    cnx.invoke(getJ2eeServer(), "undeploy", params, signature);
                } catch (Exception e) {
                    System.err.println("Can't invoke mbeanServer: " + e);
                }

        } catch (Exception e) {
            System.err.println("Cannot unload bean: " + e);
        }
    }

    /**
     * load a bean jar file in the jonas server
     * @param filename jar file, without ".jar" extension
     * @param create creates tables at loading (CMP1 only)
     * Note that in CMP2, the decision to create the tables is in
     * the jonas specific deployment descriptor.
     * @return true if bean has just been loaded.
     */
    public boolean useBeans(String filename, boolean create) {
        debug("useBeans " + filename);
        boolean added = false;
        try {
            // Load bean in EJBServer if not already loaded.
            if (!isLoaded(filename)) {
                addBeans(filename);

                // Create table if the bean was not loaded
                if (create) {
                    getDBEnv().initTable(filename);
                }
                added = true;
            }
        } catch (Exception e) {
            error("Cannot load bean: " + e);
        }
        return added;
    }

    /**
     * synchronize all entity beans
     * @param passivate passivate all instances after synchronization.
     */
    public void sync(boolean passivate) {
        debug("sync");
        try {
            if (passivate) {
                sleep(2500);
            }
            String domainName = j2eeserver.getDomain();
            ObjectName on = ObjectName.getInstance(domainName + ":type=service,name=ejbContainers");
            Boolean[] params = {passivate};
            String[] signature = {"boolean"};
            try {
                cnx.invoke(on, "syncAllEntities", params, signature);
            } catch (Exception e) {
                System.err.println("Can't invoke mbeanServer: " + e);
            }

        } catch (Exception e) {
            error("Cannot sync entities" + e);
        }
    }

    /**
     * Set the Default Transaction Timeout value on the server.
     * @param tt timeout in seconds
     */
    public static void stopTxAt(int tt) {
        try {
            String domainName = j2eeserver.getDomain();
            ObjectName on = ObjectName.getInstance(domainName + ":j2eeType=JTAResource,name=JTAResource,J2EEServer=" + jonasName);
            try {
                Attribute att = new Attribute("timeOut", tt);
                cnx.setAttribute(on, att);
                //Integer val = (Integer) cnx.getAttribute(on, "timeOut");
            } catch (Exception e) {
                System.err.println("Can't invoke mbeanServer: " + e);
            }

        } catch (Exception e) {
            System.err.println("Cannot set transaction timeout: " + e);
        }
    }

    /**
     * Get the session bean to manage database tables.
     */
    public DBEnv getDBEnv() {
        if (dbEnv == null) {

            useBeans("tables", false);

            // Connect to the DBEnvHome object
            DBEnvHome dbhome = null;
            try {
                dbhome = (DBEnvHome) PortableRemoteObject.narrow(ictx.lookup("tablesDBEnvHome"), DBEnvHome.class);
            } catch (NamingException e) {
                System.err.println(">>> " + e);
                fail("Cannot bind to DBEnvHome");
            }

            // Create the table using a session bean
            try {
                dbEnv = dbhome.create();
            } catch (Exception e) {
                fail(e.toString());
            }
        }
        return dbEnv;
    }

    /**
     * for debugging : Uncomment the line.
     */
    public static void debug(String msg) {
        //System.out.println("DEBUG: " + msg);
    }

    /**
     * Print error message.
     */
    public static void error(String msg) {
        System.err.println("ERROR: " + msg);
    }

    /**
     * sleep n millisec.
     */
    public void sleep(int msec) {
        try {
            Thread.sleep(msec);
        } catch (InterruptedException e) {
            fail(e.toString());
        }
    }

    public void testEmpty() throws Exception {
    }

}
