/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This 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 (at your option) any later version.
 *
 * This software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package test.detection.jndi;

import org.apache.log4j.Level;
import org.jboss.remoting.InvokerLocator;
import org.jboss.remoting.detection.jndi.JNDIDetector;
import org.jboss.remoting.network.NetworkRegistry;
import org.jboss.remoting.network.NetworkInstance;
import org.jboss.remoting.transport.Connector;
import org.w3c.dom.Document;
import test.DistributedTestCase;
import test.MultipleTestRunner;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.util.Random;

/**
 * Just tests that detector A sees detector B when B comes online then off.
 * This is a JUnit test, but will need to run JNDIDetectorTest2 at same time
 * in order to work properly.  Can also just run JNDIDetectorTestCase as
 * test harness to run both JNDIDetectorTest1 and JNDIDetectorTest2 (as regular JUnit test).
 * See the main for the arguments required (based on DistributedTestCase confines).
 *
 * @author <a href="mailto:telrod@e2technologies.net">Tom Elrod</a>
 */
public class JNDIDetectorTest1 extends DistributedTestCase
{
    // Setup for JNDI Server
    private int detectorPort = 1099;
    private String detectorHost = "localhost";
    private String contextFactory = "org.jnp.interfaces.NamingContextFactory";
    private String urlPackage = "org.jboss.naming:org.jnp.interfaces";

    private final Object waitObj = new Object();


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

    public JNDIDetectorTest1(String name, int port, String host)
    {
        super(name);
        this.detectorPort = port;
        this.detectorHost = host;
    }

    public JNDIDetectorTest1(int instances, int port, String host)
    {
        super("JNDIDetectorTest1");
        this.detectorPort = port;
        this.detectorHost = host;
        init(instances);
    }


    public int getDetectorPort()
    {
        return detectorPort;
    }

    public void setDetectorPort(int detectorPort)
    {
        this.detectorPort = detectorPort;
    }

    public String getDetectorHost()
    {
        return detectorHost;
    }

    public void setDetectorHost(String detectorHost)
    {
        this.detectorHost = detectorHost;
    }

    public void testDetectors()
    {
        try
        {

            JNDIDetector detector = new JNDIDetector();
            detector.setCleanDetectionNumber(2);

            Connector connector = new Connector();

            NetworkRegistry reg = setupServers(detector, connector);

            // should already be called from setUp()
            //startup();

            // Need to allow heartbeat so have detection
            Thread.currentThread().sleep(2000);

            //Should now have an entry for both of the registries
            int regCount = reg.getServers().length;

            // Actual junit test
            assertTrue("JNDIDetector should have found at least one other registry.",
                       regCount == 1);
            System.err.println("regCount = " + regCount);
            NetworkInstance[] instances = reg.getServers();
            for(int x = 0; x < instances.length; x++)
            {
                System.err.println("Network instance " + x + " = " + instances[x]);
            }

            shutdown();

            System.err.println("returning from shutdown()");

            // sleep for a few seconds so the 1st detector can discover 2nd one down
            //Thread.currentThread().sleep(20000);
            synchronized(waitObj)
            {
                waitObj.wait(90000);
            }

            System.err.println("done waiting.");

            regCount = reg.getServers().length;
            System.out.println("stopped.  now regCount = " + regCount);
            instances = reg.getServers();
            for(int x = 0; x < instances.length; x++)
            {
                System.out.println("Network instance " + x + " = " + instances[x]);
            }

            // Actual junit test
            assertTrue("JNDIDetector should not find any other registries.", regCount == 0);
            // stop the 2nd detector, so see if 1st one detects it is missing
            connector.stop();
            //connector.destroy();
            connector = null;
            detector.stop();
            detector = null;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }


    private synchronized NetworkRegistry setupServers(JNDIDetector detector, Connector connector)
    {
        NetworkRegistry registry = null;
        System.setProperty("jboss.identity", String.valueOf(System.currentTimeMillis()));
        System.out.println("jboss.identity = " + System.getProperty("jboss.identity"));

        try
        {
            MBeanServer server = MBeanServerFactory.createMBeanServer();

            //registry = NetworkRegistry.getInstance();
            registry = TestNetworkRegistry.createNetworkRegistry();
            server.registerMBean(registry, new ObjectName("remoting:type=NetworkRegistry"));

            int port = Math.abs(new Random().nextInt(2000));
            System.out.println("port = " + port);

            InvokerLocator locator = new InvokerLocator("socket://localhost:" + port);
            StringBuffer buf = new StringBuffer();
            buf.append("<?xml version=\"1.0\"?>\n");
            buf.append("<handlers>\n");
            buf.append("  <handler subsystem=\"mock\">org.jboss.remoting.transport.mock.MockServerInvocationHandler</handler>\n");
            buf.append("</handlers>\n");
            Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(buf.toString().getBytes()));
            connector.setInvokerLocator(locator.getLocatorURI());
            connector.setConfiguration(xml.getDocumentElement());
            ObjectName obj = new ObjectName("jboss.remoting:type=Connector,transport=" + locator.getProtocol());
            server.registerMBean(connector, obj);
            //connector.create();
            connector.start();

            //Need to set new domain for identity
            server.registerMBean(detector, new ObjectName("remoting:type=JNDIDetector"));

            // set config info for detector and start it.
            detector.setPort(detectorPort);
            detector.setHost(detectorHost);
            detector.setContextFactory(contextFactory);
            detector.setURLPackage(urlPackage);
            detector.start();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        return registry;
    }

    public static void main(String[] args)
    {
        org.apache.log4j.BasicConfigurator.configure();
        org.apache.log4j.Category.getRoot().setLevel(Level.DEBUG);

        JNDIDetectorTest1 test = null;
        if(args.length == 2)
        {
            String sPort = args[0];
            int port = Integer.parseInt(sPort);
            String host = args[1];
            test = new JNDIDetectorTest1("JNDIDetectorTest1", port, host);
        }
        else if(args.length == 3)
        {
            String sInstances = args[0];
            int instances = Integer.parseInt(sInstances);
            String sPort = args[1];
            int port = Integer.parseInt(sPort);
            String host = args[2];
            test = new JNDIDetectorTest1(instances, port, host);
        }
        else
        {
            test = new JNDIDetectorTest1("JNDIDetectorTest1");
        }

        MultipleTestRunner runner = new MultipleTestRunner();
        runner.doRun(test, true);

        //test.testDetectors();

        System.exit(0);

    }

    private static class TestNetworkRegistry extends NetworkRegistry
    {
        public static NetworkRegistry createNetworkRegistry()
        {
            return new TestNetworkRegistry();
        }
    }

}
