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

// SenderSF.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.JMSException;
import javax.jms.MapMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

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;

/**
 *
 */
public class SenderSF implements SessionBean {

    static protected Logger logger = null;
    SessionContext ejbContext;
    private transient InitialContext ictx = null;
    private transient TopicConnectionFactory tcf = null;
    private transient TopicConnection tc = null;
    private transient QueueConnectionFactory qcf = null;
    private transient QueueConnection qc = null;
    private transient MRecordHome ehome = null;
    private static int count = 1;

    // ------------------------------------------------------------------
    // 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 {
            tc.close();
            qc.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();
            tcf = (TopicConnectionFactory) ictx.lookup("TCF");
            qcf = (QueueConnectionFactory) ictx.lookup("QCF");
        } catch (NamingException e) {
            logger.log(BasicLevel.ERROR, "SenderSF : Cannot lookup Connection Factories: "+e);
            throw new CreateException("SenderSF: Cannot lookup Connection Factories");
        }

        // Create Connections
        try {
            qc = qcf.createQueueConnection();
            tc = tcf.createTopicConnection();
        } 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 topic
     * @param String destination
     * @param int value set in message
     * @param int nb of messages sent
     */
    public void sendOnTopic(String dest, int val, int nb) {
        logger.log(BasicLevel.DEBUG, "");
        // Lookup destinations
        Topic topic = null;
        try {
            topic = (Topic) ictx.lookup(dest);
        } catch (NamingException e) {
            throw new EJBException("sendOnTopic: Cannot lookup "+dest);
        }

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

        // Create the TopicPublisher
        TopicPublisher publisher = null;
        try {
            publisher = ss.createPublisher(topic);
        } catch (JMSException e) {
            throw new EJBException("Cannot create TopicPublisher: "+e);
        }

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

        // 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);
        }
    }

    /**
     * send messages on topic (transacted)
     * @param String destination
     * @param int value set in message
     * @param int nb of messages sent
     */
    public void sendOnTopicTx(String dest, int val, int nb) {
        sendOnTopic(dest, val, nb);
    }

    /**
     * send a message on queue
     * @param String destination
     * @param int value set in message
     * @param int nb of messages sent
     */
    public void sendOnQueue(String dest, int val, int nb) {
        logger.log(BasicLevel.DEBUG, "");
        // Lookup destination
        Queue queue = null;
        try {
            queue = (Queue) ictx.lookup(dest);
        } catch (NamingException e) {
            throw new EJBException("sendOnQueue: Cannot lookup "+dest);
        }

        // Create QueueSession
        // Must create Session at each request because of the bug in JMS
        // about Session not enlisted in transactions if open first.
        QueueSession ss = null;
        try {
            // (true, 0) are the recommanded args, although they are not taken
            // in account by the container.
            ss = qc.createQueueSession(true, 0);
        } catch (JMSException e) {
            throw new EJBException("Cannot create Session: "+e);
        }

        // Create the QueueSender
        QueueSender sender = null;
        try {
            sender = ss.createSender(queue);
        } catch (JMSException e) {
            throw new EJBException("Cannot create QueueSender: "+e);
        }

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

        // 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);
        }
    }

    /**
     * send messages on queue (transacted)
     * @param String destination
     * @param int value set in message
     * @param int nb of messages sent
     */
    public void sendOnQueueTx(String dest, int val, int nb) {
        sendOnQueue(dest, val, nb);
    }

    /**
     * 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++) {
            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;
                } else {
                    logger.log(BasicLevel.DEBUG, "sec : " + i + "/" + sec + " found:" + retval + "/" + nb);
                }
            } 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");
            }
        }
    }
	
}
