/*
 * 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$
 * --------------------------------------------------------------------------
 */

// SenderSF1_1.java
// Stateful Session Bean

package org.objectweb.jonas.jtests.beans.message;

import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Iterator;

import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.FinderException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.transaction.UserTransaction;
import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;

import org.objectweb.jonas.common.Log;
import org.objectweb.jonas.jtests.util.Env;
import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * This Session Bean is equivalent to the Sender1_1SF bean
 * the only difference is it is bean managed transaction
 * it is using ConnectionFactory, Connection, Session and MessageProducer
 */
public class Sender1_2SF implements SessionBean {

    static protected Logger logger = null;
    SessionContext ejbContext;
    private transient InitialContext ictx = null;
    private transient ConnectionFactory cf = null;
    private transient javax.jms.Connection c = null;
    private transient MRecordHome ehome = null;
    private static int count = 1;
    private static UserTransaction utx = null;
    // ------------------------------------------------------------------
    // SessionBean implementation
    // ------------------------------------------------------------------

    /** 
     * Set the associated session context. The container calls this method
     * after the instance creation. 
     * The enterprise Bean instance should store the reference to the context
     * object in an instance variable. 
     * This method is called with no transaction context.
     *
     * @param sessionContext A SessionContext interface for the instance.
     * @throws EJBException Thrown by the method to indicate a failure caused by
     * a system-level error.
     */
    public void setSessionContext(SessionContext ctx) {
        if (logger == null)
            logger = Log.getLogger(Log.JONAS_TESTS_PREFIX);
        logger.log(BasicLevel.DEBUG, "");
        ejbContext = ctx;
    }
	
    /**
     * A container invokes this method before it ends the life of the session object. 
     * This happens as a result of a client's invoking a remove operation, or when a 
     *  container decides to terminate the session object after a timeout. 
     * This method is called with no transaction context. 
     *
     * @throws EJBException Thrown by the method to indicate a failure caused by
     * a system-level error.
     */
    public void ejbRemove() {
        logger.log(BasicLevel.DEBUG, "");
        try {
            c.close();
        } catch (Exception e) {
            logger.log(BasicLevel.ERROR, "Exception on close:" + e);
        }
    }
	
    /**
     * The Session bean must define 1 or more ejbCreate methods.
     *
     * @throws CreateException Failure to create a session EJB object.
     */
    public void ejbCreate() throws CreateException {
        logger.log(BasicLevel.DEBUG, "");
        // Lookup Connection Factories
        try {
            ictx = new InitialContext();
            cf = (ConnectionFactory) ictx.lookup("CF");
        } catch (NamingException e) {
            logger.log(BasicLevel.ERROR, "SenderSF : Cannot lookup Connection Factories: "+e);
            throw new CreateException("SenderSF: Cannot lookup Connection Factories");
        }


        // Create Connections
        try {

            c = cf.createConnection();
        } catch (JMSException e) {
            logger.log(BasicLevel.ERROR, "SenderSF : Cannot create connections: "+e);
            throw new CreateException("SenderSF: Cannot create connections");
        }

        // Lookup Entity Home for checking
        String BEAN_HOME = "messageMRecordECHome";
        try {
            ehome = (MRecordHome) PortableRemoteObject.narrow(ictx.lookup(BEAN_HOME), MRecordHome.class);
        } catch (NamingException e) {
            logger.log(BasicLevel.ERROR, "SenderSF ejbCreate: Cannot get entity home: "+e);
            throw new CreateException("SenderSF: Cannot get entity home");
        }
    }

    /**
     * A container invokes this method on an instance before the instance
     * becomes disassociated with a specific EJB object.
     */
    public void ejbPassivate() {
        logger.log(BasicLevel.DEBUG, "");
    }

    /**
     * A container invokes this method when the instance is taken out of 
     * the pool of available instances to become associated with a specific 
     * EJB object.
     */
    public void ejbActivate() {
        logger.log(BasicLevel.DEBUG, "");
    }
    
    // ------------------------------------------------------------------
    // private methods
    // ------------------------------------------------------------------

    /**
     * return a unique identifier
     */
    private String getUUID() {
        long uuid;
        synchronized(getClass()) {
            uuid =  System.currentTimeMillis() * 256 + count;
            count++;
        }
        return String.valueOf(uuid);
    }

    // ------------------------------------------------------------------
    // Sender implementation
    // ------------------------------------------------------------------

    /**
     * send a message on destination (topic or queue)
     * @param Session session
     * @param String destination
     * @param int value set in message
     * @param int nb of messages sent
     * @param boolean commit transaction if true
     */
    public void sendOnDestination(Session ss, String dst, int val, int nb) {

        // Lookup destinations
        Destination  dest  = null;
        try {
            dest = (Destination) ictx.lookup(dst);
        } catch (NamingException e) {
            throw new EJBException("sendOnDestination: Cannot lookup "+dest);
        }

       // Create the MessageProducer for destination
        MessageProducer producer = null;
        try {
            producer  = ss.createProducer(dest);
        } catch (JMSException e) {
            throw new EJBException("Cannot create MessageProducer: "+e);
        }

        // Send messages on the destination
        try {
            for (int i = 0; i < nb; i++) {
                MapMessage mess = ss.createMapMessage();
                mess.setString("Id", getUUID());
                mess.setString("Text",dst);
                mess.setInt("Value", val);
                producer.send(mess);
            }
        } catch (JMSException e) {
            throw new EJBException("Cannot send message: "+e);
        }

    }

    /**
     * send a message on destination (topic or queue)
     * the transaction is demarcated before the session creation
     * @param String destination
     * @param int value set in message
     * @param int nb of messages sent
     * @param boolean commit transaction if true
     */
    public void sendOnDestinationWithTxBeforeSession(String dst, int val, int nb, boolean commit)
        throws RemoteException  {
        logger.log(BasicLevel.DEBUG, "");

        // Obtain the UserTransaction interface
        try {
            utx = ejbContext.getUserTransaction();
        } catch (IllegalStateException e) {
            logger.log(BasicLevel.ERROR, "Can't get UserTransaction");
            throw new RemoteException("Can't get UserTransaction:", e);
        }



        // Start a global transaction
        try {
            utx.begin();
        } catch (NotSupportedException e) {
            logger.log(BasicLevel.ERROR, "Can't start Transaction");
            throw new RemoteException("Can't start Transaction:", e);
        } catch (SystemException e) {
            logger.log(BasicLevel.ERROR, "Can't start Transaction");
            throw new RemoteException("Can't start Transaction:", e);
        }


        // Create Session
        // Create Session at each request : Avoids the bug in JMS
        // about Session not enlisted in transactions if open first.
        Session ss = null;
        try {
            // (true, 0) are the recommanded args, although they are not taken
            // in account by the container.
            ss = c.createSession(true, 0);
        } catch (JMSException e) {
            throw new EJBException("Cannot create Session: "+e);
        }
        sendOnDestination(ss, dst, val, nb);


        // Close Session: This is mandatory for the correct behaviour of
        // XA protocol. An XA END must be sent before commit or rollback.
        try {
            ss.close();
        } catch (JMSException e) {
            throw new EJBException("Cannot close session: "+e);
        }

        try {
            // commit or rollback the transaction depending on commit parameter
            if(commit) {
                 utx.commit();
            } else {
                 utx.rollback();
            }

        } catch (Exception e) {
            logger.log(BasicLevel.ERROR, "Can't rollback Transaction");
            throw new RemoteException("Can't rollback Transaction:", e);
        }
    }

    /**
     * send messages on destination (topic or queue)
     * the transaction is demarcated after the session creation
     * @param String destination
     * @param int value set in message
     * @param int nb of messages sent
     * @param boolean commit transaction if true
     */
    public void sendOnDestinationWithTxAfterSession(String dst, int val, int nb, boolean commit)
        throws RemoteException  {

       // Obtain the UserTransaction interface
        try {
            utx = ejbContext.getUserTransaction();
        } catch (IllegalStateException e) {
            logger.log(BasicLevel.ERROR, "Can't get UserTransaction");
            throw new RemoteException("Can't get UserTransaction:", e);
        }

       Session ss = null;
        try {
 
            ss = c.createSession(false, 0);
        } catch (JMSException e) {
            throw new EJBException("Cannot create Session: "+e);
        }

       // Start a global transaction
        try {
            utx.begin();
        } catch (NotSupportedException e) {
            logger.log(BasicLevel.ERROR, "Can't start Transaction");
            throw new RemoteException("Can't start Transaction:", e);
        } catch (SystemException e) {
            logger.log(BasicLevel.ERROR, "Can't start Transaction");
            throw new RemoteException("Can't start Transaction:", e);
        }
        sendOnDestination(ss, dst, val, nb);
       // Close Session: This is mandatory for the correct behaviour of
        // XA protocol. An XA END must be sent before commit or rollback.
        try {
            ss.close();
        } catch (JMSException e) {
            throw new EJBException("Cannot close session: "+e);
        }

        try {
            // commit or rollback the transaction depending on commit parameter
            if(commit) {
                 utx.commit();
            } else {
                 utx.rollback();
            }

        } catch (Exception e) {
            logger.log(BasicLevel.ERROR, "Can't rollback Transaction");
            throw new RemoteException("Can't rollback Transaction:", e);
        }
    }

  

    /**
     * Checking send methods
     * @param int value looked in messages received
     * @param int nb of messages that could be received
     * @param int nb of seconds max to wait for all messages
     * @return actual nb of messages received
     */
    public int check(int val, int nb, int sec) {
        Collection elist = null;
        int retval = 0;
        for (int i = 0; i <= sec; i++) {
            logger.log(BasicLevel.DEBUG, "sec : " + i + "/" + sec);
            try {
                elist = ehome.findByValue(val);
                retval = elist.size();
                if (retval >= nb) {
                    // clean database before returning
                    Iterator it = elist.iterator();
                    while (it.hasNext()) {
                        MRecord ent = (MRecord) PortableRemoteObject.narrow(it.next(), MRecord.class);
                        try {
                            ent.remove();
                        } catch (Exception e) {
                            throw new EJBException("Error on remove");
                        }
                    }
                    return retval;
                }
            } catch (FinderException e) {
            } catch (RemoteException e) {
                return retval;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
        return retval;
    }

    /**
     * Clean all entity beans for this value
     */
    public void clean(int val) {
        logger.log(BasicLevel.DEBUG, "");
        Collection elist = null;
        try {
            elist = ehome.findByValue(val);
        } catch (FinderException e) {
            return;
        } catch (Exception e) {
            throw new EJBException("Error on find");
        }
        Iterator it = elist.iterator();
        while (it.hasNext()) {
            MRecord ent = (MRecord) PortableRemoteObject.narrow(it.next(), MRecord.class);
            try {
                ent.remove();
            } catch (Exception e) {
                throw new EJBException("Error on remove");
            }
        }
    }
	
}
