/*
 * 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.clients.jca15;

import junit.framework.*;
import java.io.BufferedReader; 
import java.io.FileInputStream;
import java.io.InputStreamReader; 
import java.io.IOException;
import java.lang.String;
import java.rmi.RemoteException;
import javax.rmi.PortableRemoteObject;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.UserTransaction;
import javax.transaction.SystemException;

import org.objectweb.jonas.jtests.beans.jca15.TransactedCA;
import org.objectweb.jonas.jtests.beans.jca15.TransactedCAHome;
import org.objectweb.jonas.jtests.beans.jca15.Utility;
import org.objectweb.jonas.jtests.util.JTestCase;
import org.objectweb.jonas.jtests.clients.jca15.F_securityTest;

/**
 * F_xatransactionTests tests JOnAS Connection Architecture XA Transaction
 */

public class F_xatransactionTest extends JTestCase {

    static Context ctx = null;

    // Lookup bean home

    protected static String BEAN_HOME = "TransactedCAHome";
    protected static TransactedCAHome home = null;
    private static final String RAR_JNDI_NAME = "eis/ErsatzXATransaction";
    final public int CLOSE_HANDLE = 0;
    final public int CLOSE_PHYSICAL = 1;
    public int CloseType = 0;
    static TransactedCA bean = null;
    public String UseBeans="jca15";
    String err="";
    
    public F_xatransactionTest(String name) {
        super(name);
    }

    protected void setUp() {
        super.setUp();
        try {
    	    // get JNDI initial context

            if (ctx == null) {
                err="InitialContext()";
	            ctx = new InitialContext();
            }
	    //
	    // We want to start transactions for client: get UserTransaction
	    //
            if (utx == null) {
                err="lookup(javax.transaction.UserTransaction)";
	            utx = (UserTransaction) ctx.lookup(Utility.USER_TRANSACTION);
            }
            if (home == null) {
    	        useBeans(UseBeans, false);
            }
            getBean();
            assertTrue (6 == 6);

        } catch (SystemException se1) {
            String s="setUp error: Unable to "+err+" SystemException="+se1 ;
            fail(s);
	    } catch (Exception e) {
	        fail("Cannot do setUp. Error on "+err+" Exception="+e);
        }
    }
    private void getBean() throws Exception {
        // Connecting to TransactedCAHome thru JNDI

        if (home == null) {
	        home = (TransactedCAHome)PortableRemoteObject.narrow(
							    ctx.lookup(BEAN_HOME),
							    TransactedCAHome.class);
            bean = home.create();
        }
    }
    protected void tearDown() throws Exception {
        //bean.closeUp(CloseType);
    }
    protected void startUp(String testName) {
	    try {
	        bean.method1(RAR_JNDI_NAME, testName);
	    } catch (Exception ee) {
	        ee.printStackTrace();
	        System.exit(2);
	    }
    }

// test list ****************************************************

    /**
     * The application server invokes the ManagedConnection.getXAResource method
     * to get the XAResource instance associated with the ManagedConnection instance.
     * Then, application server calls the TM, which in turn calls the 
     * XAResourceImpl.start() method.
     * 
     * This test verifies the existence of the instance, assigned Xid, and start()
     */
    public void testIsXaresource() {
        CloseType=CLOSE_PHYSICAL;
        
        try {
            startUp("testIsXaresource");
            assertTrue(5 == 5);
            String ans = bean.getXid();
            assertTrue(5 == 5);
            assertEquals("OK", ans);
            bean.closeUp(CloseType);
            assertTrue(5 == 5);
        } catch (Exception e) {
            System.err.println("XatransactionTest: Exception in TransactedCASLR");
            e.printStackTrace();
        } catch (Throwable t) {
            System.err.println("XatransactionTest: Exception in TransactedCASLR");
            t.printStackTrace();
        }
    }
    /**
     *  At connection close, the application server performs "transactional" cleanup.
     *  The application server dissociates the XAResource instance (corresponding 
     *  to the ManagedConnection "mc" instance) from the transaction manager.
     *  The transaction manager calls XAResource.end(Xid, flag)
     * <p>
     *  The ConnectionEvent is CLOSE_CONNECTION. This test verifies that application 
     *  server called TM which in turn called XAResource.end(). 
     *  
     *
     */
    public void testIsXAend1() {
        CloseType=CLOSE_HANDLE; // leave physical connection open
        
        try {
            startUp("testIsXAend1");
            assertTrue(5 == 5);
            assertTrue(bean.getCMInstance());  // is physical connection o.k.
            bean.closeUp(CloseType);
            assertTrue(bean.getCMInstance());  // should still be o.k.
            assertTrue(5 == 5);
        } catch (Exception e) {
            System.err.println("testIsXAend1: Exception in TransactedCASLR");
            e.printStackTrace();
        } catch (Throwable t) {
            System.err.println("testIsXAend1: Exception in TransactedCASLR");
            t.printStackTrace();
        }
    }
    /**
     *  At connection close, the application server performs "transactional" cleanup.
     *  The application server dissociates the XAResource instance (corresponding 
     *  to the ManagedConnection "mc" instance) from the transaction manager.
     *  The transaction manager calls XAResource.end(Xid, flag)
     * <p>
     *  The ConnectionEvent is CONNECTION_ERROR_OCCURRED to force a physical close.
     *  verifies mc.XAR reference is null
     *
     */
    public void testIsXAend2() {
        CloseType=CLOSE_PHYSICAL;
        
        try {
            startUp("testIsXAend2");
            String ans = bean.getXid();
            assertEquals("FAIL", ans);        // XAR is dissociated, should FAIL
            // testIsXAend2 should not work. end() not called by TM-
        } catch (Exception e) {
            System.err.println("testIsXAend2: Exception in TransactedCASLR");
            e.printStackTrace();
        } catch (Throwable t) {
            System.err.println("testIsXAend2: Exception in TransactedCASLR");
            t.printStackTrace();
        }
    }

    public static Test suite() {
        return new TestSuite(F_xatransactionTest.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];
            Integer i_arg;

            if (s_arg.equals("-n")) {
                testtorun = args[++argn];
            }
        }

        if (testtorun == null) {
            junit.textui.TestRunner.run(suite());
        } else {
            junit.textui.TestRunner.run(new F_xatransactionTest(testtorun));
        }
    }
}
