package net.pascalalma.myservices;

import java.util.Properties;
import java.util.concurrent.Callable;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.naming.Context;
import javax.naming.InitialContext;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class EJBTestBase {

    private static Logger log = LoggerFactory.getLogger(EJBTestBase.class);
    static Context context;

    public EJBTestBase() {
    }

    @BeforeClass
    public static void setUp()
            throws Exception {
        log.debug("setUp");
        Properties props = new Properties();
        props.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                "org.apache.openejb.client.LocalInitialContextFactory");

        props.put("MyDS", "new://Resource?type=DataSource");
        props.put("MyDS.JdbcDriver", "org.hsqldb.jdbcDriver");
        props.put("MyDS.JdbcUrl", "jdbc:hsqldb:.");
        
        context = new InitialContext(props);
        log.debug("End of setUp");

    }

    @AfterClass
    public static void tearDown()
            throws Exception {
        log.debug("tearDown");

        context.close();
    }

    public void testWithTransaction() throws Exception {
        Caller transactionBean = (Caller) context.lookup("TransactionBeanLocal");

        transactionBean.call(new Callable(){
            public Object call() throws Exception {
    //            do some work();your testing method here
                return null;
            }
        });
    }

     public static interface Caller {
        public <V> V call(Callable<V> callable) throws Exception;
    }

    /**
     * This little bit of magic allows our test code to execute in
     * the scope of a container controlled transaction.
     *
     * The src/test/resource/META-INF/ejb-jar.xml will cause this
     * EJB to be automatically discovered and deployed when
     * OpenEJB boots up.
     */
    @Stateless
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public static class TransactionBean implements Caller {

        public <V> V call(Callable<V> callable) throws Exception {
            return callable.call();
        }

    }
}
