/*
 * 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 org.jboss.test.remoting.shutdown;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

import junit.framework.TestCase;

import org.jboss.remoting.Client;
import org.jboss.remoting.InvokerLocator;
import org.jboss.remoting.callback.Callback;
import org.jboss.remoting.callback.CallbackPoller;
import org.jboss.remoting.callback.HandleCallbackException;
import org.jboss.remoting.callback.InvokerCallbackHandler;

/** 
 * @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
 * @version $Revision: 1961 $
 * <p>
 * Copyright Jan 19, 2007
 * </p>
 */
public abstract class AbstractClient extends TestCase
{    
   private String transport;
   private Map extraConfig;
   
   
   public AbstractClient(String transport, Map config)
   {
      this.transport = transport;
      this.extraConfig = new HashMap(config);
      System.out.println("client transport: " + transport);
      System.out.println("log4j.configuration: " + System.getProperty("log4j.configuration"));
      Runtime.getRuntime().traceMethodCalls(true);
   }
   
   
   /**
    * This test is used to verify that a JVM with a client connected to a server will shut
    * down.  To exercise as many threads as possible, it enables leasing, registers a
    * connection listener, and registers a callback handler for polled callbacks.
    * 
    * At the end of the method, it creates a Thread which runs longer that this test is
    * supposed to last.  According to the value returned by the overridden abstract
    * method daemon(), it the Thread will be a daemon or non-daemon thread.
    */
   public void testShutdown() throws Throwable
   {
      try
      {
         String host = InetAddress.getLocalHost().getHostAddress();
         String locatorURI = transport + "://" + host + ":" + ShutdownTestServer.port;
         InvokerLocator locator = new InvokerLocator(locatorURI);
         HashMap clientConfig = new HashMap(extraConfig);
         clientConfig.put(Client.ENABLE_LEASE, "true");
         clientConfig.put(InvokerLocator.CLIENT_LEASE_PERIOD, "1000");
         Client client = new Client(locator, clientConfig);
         client.connect();
         System.out.println("client connected");
         client.addConnectionListener(new ShutdownTestServer.TestListener(), 1000);
         Integer i = (Integer) client.invoke(new Integer(17));
         if (18 != i.intValue())
            throw new Exception("invocation failed");
         System.out.println("invocation successful");
         TestCallbackHandler callbackHandler = new TestCallbackHandler();
         System.out.println("added connection listener");
         System.out.println("adding listener");
         HashMap metadata = new HashMap();
         metadata.put(CallbackPoller.CALLBACK_POLL_PERIOD, "500");
         client.addListener(callbackHandler, metadata, null, false);
         System.out.println("added listener");
         Thread.sleep(1000);
         if (!callbackHandler.receivedCallback)
         {
            System.out.println("callback failed");
            throw new Exception("callback failed");
         }
         System.out.println("callback successful");
         client.removeListener(callbackHandler);
         client.disconnect();
         Thread t = new Thread()
         {
            public void run()
            {
               try
               {
                  Thread.sleep(10000);
               }
               catch (InterruptedException e)
               {
                  System.out.println("interrupted");
               }
            }
         };
         t.setDaemon(daemon());
         t.start();
         System.out.println("client disconnected");
      }
      catch (Exception e)
      {
         System.out.println("exception in client: " + e);
         System.exit(1);
      }
   }
   
   
   abstract protected boolean daemon();
   
   
   protected static void getConfig(Map config, String configs)
   {
      int start = 0;
      int ampersand = configs.indexOf('&');
      while (ampersand > 0)
      {
         String s = configs.substring(start, ampersand);
         int equals = s.indexOf('=');
         String param = s.substring(0, equals);
         String value = s.substring(equals + 1);
         config.put(param, value);
         start = ampersand + 1;
         ampersand = configs.indexOf('&', start);
      }
   }
   
   
   public class TestCallbackHandler implements InvokerCallbackHandler
   {  
      public boolean receivedCallback;
      
      public void handleCallback(Callback callback) throws HandleCallbackException
      {
         receivedCallback = true;
         System.out.println("received callback: " + callback);
      }  
   }
}
