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


import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.transaction.RollbackException;
import javax.transaction.TransactionRolledbackException;
import javax.transaction.Status;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.objectweb.jonas.jtests.beans.annuaire.Personne;
import org.objectweb.jonas.jtests.beans.annuaire.PersonneHome;
import org.objectweb.jonas.jtests.util.JTestCase;

/**
 * these tests check state validity with transactions.
 * Uses bean Personne (nom:pk, numero)
 */
public class F_State extends JTestCase {

    private static String BEAN_HOME = "annuairePersonneECHome";
    protected static PersonneHome ehome = null;

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

    protected void setUp() {
        super.setUp();
        if (ehome == null) {
            useBeans("annuaire", true);
            try {
                ehome = (PersonneHome) PortableRemoteObject.narrow(ictx.lookup(BEAN_HOME), PersonneHome.class);
            } catch (NamingException e) {
                fail("Cannot get bean home");
            }
        }
    }

    protected void tearDown() throws Exception {
        super.tearDown();
    }

    /**
     * Test with commit. Both beans should be modified
     */
    public void testCommit() throws Exception {
        // create beans
        // Sometimes, the beans may exist. Delete them first.
        Personne bob = null;
        Personne jack = null;
        try {
            bob = ehome.create("Bob", "1");
        } catch (CreateException e) {
            ehome.remove("Bob");
            bob = ehome.create("Bob", "1");
        }
        try {
            jack = ehome.create("Jack", "2");
        } catch (CreateException e) {
            ehome.remove("Jack");
            jack = ehome.create("Jack", "2");
        }

        // transaction qui va etre committee
        utx.setTransactionTimeout(6);
        utx.begin();
        String newval = "4";
        try {
            bob.setNumero(newval);
            jack.setNumero(newval);
            utx.commit();
            // Check beans have bean modified
            assertTrue("first bean not modified", bob.getNumero().equals(newval));
            assertTrue("second bean not modified", jack.getNumero().equals(newval));
        } finally {
            // remove created beans
            bob.remove();
            jack.remove();
        }
    }

    /**
     * Test if modifications are cancelled after timeout.
     */
    public void testTimeout() throws Exception {
        // create beans
        // Sometimes, the beans may exist. Delete them first.
        Personne bob = null;
        String bobnum = "1";
        try {
            bob = ehome.create("Bob", bobnum);
        } catch (CreateException e) {
            ehome.remove("Bob");
            bob = ehome.create("Bob", bobnum);
        }
        Personne jack = null;
        String jacknum = "2";
        try {
            jack = ehome.create("Jack", jacknum);
        } catch (CreateException e) {
            ehome.remove("Jack");
            jack = ehome.create("Jack", jacknum);
        }

        // tx that will be timed out.
        int nbsec = 5;
        utx.setTransactionTimeout(nbsec);
        utx.begin();
        // first bean access, before timeout
        bob.setNumero("3");
        sleep((nbsec + 3)*1000);
        try {
            // second bean access, after timeout
            jack.setNumero("4");
            // fail("should not access bean inside a rolled back transaction");
            // possible case. But transaction will be rolled back later.
        } catch (TransactionRolledbackException e) {
            // ideal case.
            debug("TransactionRolledbackException");
        } catch (RemoteException e) {
            // normal case.
            debug("RemoteException:" + e);
        } finally {
            try {
                utx.commit();
                fail("should not commit transaction");
            } catch (RollbackException e) {
                // Normal case.
            } finally {
                // Check that beans have not bean modified
                // This is the most important checking of the test!
                assertTrue("first bean modified", bob.getNumero().equals(bobnum));
                assertTrue("second bean modified", jack.getNumero().equals(jacknum));
                // remove created beans
                bob.remove();
                jack.remove();
            }
        }
	}

    /**
     * Test si les modifications apres le timeout sont effectivement
     * annulees par le rollback.
     * Implique que ces modifications soient bien enrolees dans la transaction
     * ou bien carrement pas faite du tout.
     */
    public void testTimeout1() throws Exception {
        // create the bean
        // Sometimes, the bean may exist.
        Personne jack = null;
        String jacknum = "2";
        try {
            jack = ehome.create("Jack", jacknum);
        } catch (CreateException e) {
            ehome.remove("Jack");
            jack = ehome.create("Jack", jacknum);
        }

        // transaction qui va etre rollbackee sur timeout
        int nbsec = 5;
        utx.setTransactionTimeout(nbsec);
        utx.begin();
        try {
            sleep((nbsec + 3)*1000);
            // bean accede apres le timeout
            jack.setNumero("4");
            utx.commit();
            // remove created beans
            jack.remove();
            fail("timeout should rollback transaction");
        } catch (RollbackException e) {
            assertEquals(utx.getStatus(), Status.STATUS_NO_TRANSACTION);
        }
        // Check beans have not been modified
        // This is the most important checking of the test!
        try {
            assertTrue("bean modified", jack.getNumero().equals(jacknum));
        } finally {
            // remove created beans
            jack.remove();
        }
	}

    public void testRollbackOnlyBasic() throws Exception {
        utx.setTransactionTimeout(6);
        utx.begin();
        utx.setRollbackOnly();
        try {
            utx.commit();
            fail("Should rollback transaction");
        } catch (RollbackException e) {
            assertEquals(utx.getStatus(), Status.STATUS_NO_TRANSACTION);
        }
	}

    /**
     * Test si les modifications apres le rollbackonly sont effectivement
     * annulees par le rollback.
     * Implique que ces modifications soient bien enrolees dans la transaction
     * ou bien carrement pas faite du tout.
     */
    public void testRollbackOnly1() throws Exception {
        // create beans
        // Sometimes, the beans may exist. Delete them first.
        Personne jack = null;
        String jacknum = "2";
        try {
            jack = ehome.create("Jack", jacknum);
        } catch (CreateException e) {
            ehome.remove("Jack");
            jack = ehome.create("Jack", jacknum);
        }

        // transaction qui va etre rollbackee AVANT l'acces au bean
        utx.setTransactionTimeout(6);
        utx.begin();
        try {
            // rollback only de la transaction
            utx.setRollbackOnly();
            // bean accessed after rollbackOnly
            jack.setNumero("4");
            // Actually, we could get an exception here.
            // maybe should write this test differently
            utx.commit();
            // remove created beans
            jack.remove();
            fail("Should rollback transaction");
        } catch (RollbackException e) {
            assertEquals(utx.getStatus(), Status.STATUS_NO_TRANSACTION);
        }
        // Check beans have not been modified
        // This is the most important checking of the test!
        try {
            assertTrue("bean modified", jack.getNumero().equals(jacknum));
        } finally {
            // remove created beans
            jack.remove();
        }
	}

    /**
     * Test si les modifications apres le rollbackonly sont effectivement
     * annulees par le rollback.
     * Implique que ces modifications soient bien enrolees dans la transaction
     * ou bien carrement pas faite du tout.
     */
    public void testRollbackOnly() throws Exception {
        // create beans
        // Sometimes, the beans may exist. Delete them first.
        Personne bob = null;
        String bobnum = "1";
        try {
            bob = ehome.create("Bob", bobnum);
        } catch (CreateException e) {
            ehome.remove("Bob");
            bob = ehome.create("Bob", bobnum);
        }
        Personne jack = null;
        String jacknum = "2";
        try {
            jack = ehome.create("Jack", jacknum);
        } catch (CreateException e) {
            ehome.remove("Jack");
            jack = ehome.create("Jack", jacknum);
        }

        // transaction qui va etre rollbackee entre les
        // 2 acces aux beans
        utx.setTransactionTimeout(6);
        utx.begin();
        // premier bean accede avant le rollbackOnly
        bob.setNumero("3");
        // rollback only de la transaction
        utx.setRollbackOnly();
        try {
            // deuxieme bean accede apres le rollbackOnly
            jack.setNumero("4");
            //fail("should not access bean inside a rolled back transaction");
            // possible case. But transaction will be rolled back later.
        } catch (TransactionRolledbackException e) {
            // ideal case.
        } catch (RemoteException e) {
            assertTrue((e.detail instanceof TransactionRolledbackException)
                    || (e instanceof TransactionRolledbackException));
            // normal case.
        } finally {
            try {
                utx.commit();
                fail("should not commit transaction");
            } catch (RollbackException e) {
                // Normal case.
                assertEquals(utx.getStatus(), Status.STATUS_NO_TRANSACTION);
            } finally {
                // Controle que les 2 beans n'ont pas ete modifies
                assertTrue("first bean modified", bob.getNumero().equals(bobnum));
                assertTrue("second bean modified", jack.getNumero().equals(jacknum));
                // remove created beans
                bob.remove();
                jack.remove();
            }
        }
	}

    public static Test suite() {
        return new TestSuite(F_State.class);
    }

    public static void main (String args[]) {
        String testtorun = null;
        // Get args
        for (int argn = 0; argn < args.length; argn++) {
            String sarg = args[argn];
            if (sarg.equals("-n")) {
                testtorun = args[++argn];
            }
        }
        if (testtorun == null) {
            junit.textui.TestRunner.run(suite());
        } else {
            junit.textui.TestRunner.run(new F_State(testtorun));
        }
    }
}
