/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 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
 *
 * Initial developer(s): ____________________________________.
 * Contributor(s): ______________________________________.
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

// StockHandlerBean.java
// Message Driven bean

package sampleappli;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.ejb.EJBException;
import javax.jms.*;
import javax.rmi.PortableRemoteObject;

/**
 * StockHandlerBean is a Message driven bean which is listening to a topic It
 * receives MapMessages that contains a customer identification, a product
 * identification and a quantity for the product When the StockHandlerBean
 * receives a message it builds a message corresponding to an Order and sends it
 * to a Queue destination then it updates the Stock database.
 */
public class StockHandlerBean implements MessageDrivenBean, MessageListener {

    private transient MessageDrivenContext mdbContext;

    StockHome sh = null;

    QueueConnectionFactory queueConnectionFactory = null;

    QueueConnection queueConnection = null;

    Queue queue = null;

    Context initialContext = null;

    // ------------------------------------------------------------------
    // MessageDrivenBean implementation
    // ------------------------------------------------------------------

    /**
     * Default constructor
     */
    public StockHandlerBean() {
    }

    /**
     * Set the associated context. The container call 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 MessageDrivenContext A MessageDrivenContext interface for the
     *        instance.
     * @throws EJBException Thrown by the method to indicate a failure caused by
     *         a system-level error.
     */

    public void setMessageDrivenContext(MessageDrivenContext ctx) {
        mdbContext = ctx;
    }

    /**
     * A container invokes this method before it ends the life of the
     * message-driven object. This happens when a container decides to terminate
     * the message-driven object. 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() {
    }

    /**
     * The Message driven bean must define an ejbCreate methods with no args.
     */
    public void ejbCreate() {
        try {
            initialContext = new InitialContext();
            sh = (StockHome) PortableRemoteObject.narrow(initialContext.lookup("java:comp/env/ejb/Stock"),
                    StockHome.class);
            queue = (Queue) initialContext.lookup("java:comp/env/jms/Orders");
            queueConnectionFactory = (QueueConnectionFactory) initialContext
                    .lookup("java:comp/env/jms/QueueConnectionFactory");
            queueConnection = queueConnectionFactory.createQueueConnection();
        } catch (Exception e) {
            System.err.println("StockHandlerBean ejbCreate : " + e);
        }
    }

    /**
     * onMessage method Map Messages are receive with the following format:
     * "CustomerId" String "ProductId" String "Quantity" int the Message driven
     * bean will construct a string for an Order that will be sent to the Queue
     * Orders and decrease the stock quantity for the product identified by
     * ProductId this method run in the scope of a transaction that the
     * container started immediately before dispatching the onMessage method the
     * sending message to the Order queue and the updating of the Stock table is
     * made in the same global transaction this transaction may be rolled back
     * if the stock quantity became negative
     */

    public void onMessage(Message message) {
        QueueSession session = null;
        QueueSender qs = null;
        int code;
        String pid = null;
        ;
        int qty = 0;
        String cid = null;
        ;
        MapMessage msg = (MapMessage) message;
        Stock stock = null;
        try {
            if (message.getJMSRedelivered()) {
                System.out.println("Ok, that's it!");
                return;
            }
        } catch (Exception ex) {
            System.err.println(ex.toString());
        }
        try {
            pid = msg.getString("ProductId");
            qty = msg.getInt("Quantity");
            cid = msg.getString("CustomerId");
            session = queueConnection.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
            qs = session.createSender(queue);
            stock = sh.findByPrimaryKey(pid);
            System.out.println("StockHandlerBean findByPrimaryKey(" + pid + ")");
        } catch (Exception ex) {
            System.err.println(ex.toString());
        }
        try {
            TextMessage tm = session.createTextMessage();
            String m = "For CustomerId = " + cid + " ProductId= " + pid + " Quantity= " + qty;
            tm.setText(m);
            qs.send(tm);
            System.out.println("StockHandlerBean message sent: " + m);
            stock.decreaseQuantity(qty);
        } catch (Exception ex) {
            // on negative Stock -> rollback the transaction
            mdbContext.setRollbackOnly();
        } finally {
            if (session != null) {
                try {
                    session.close();
                    System.out.println("StockHandlerBean session closed");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}