/*
 * Enhydra Java Application Server
 * The Initial Developer of the Original Code is Lutris Technologies Inc.
 * Portions created by Lutris are Copyright (C) 1997-2000 Lutris Technologies
 * Inc.
 * All Rights Reserved.
 *
 * The contents of this file are subject to the Enhydra Public License Version
 * 1.0 (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at
 * http://www.enhydra.org/software/license/epl.html
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations under the
 * License.
 *-----------------------------------------------------------------------------
 * $Id: SimpleReceiver.java,v 1.2 2002/10/29 15:27:02 jmesnil Exp $
 *-----------------------------------------------------------------------------
 */

import javax.jms.*;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.naming.NamingException;

/**
 * Created on Mar 4, 2002
 * @author  Christophe Ney - Lutris Technologies cney@batisseurs.com
 */
public class SimpleReceiver extends Thread {

    public void run() {

        try {
            // Use JNDI to find the connection factory and the destination
            Context ctx = new InitialContext();
            QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("theQueueConnectionFactory");
            Queue queue = (Queue) ctx.lookup("theQueue");

            // create a connection, session, sender, and the message QueueConnection conn;
            QueueConnection connection = factory.createQueueConnection();
            QueueSession session = connection.createQueueSession (false, Session.AUTO_ACKNOWLEDGE);
            QueueReceiver receiver = session.createReceiver(queue);

            // start up the connection, send the message
            connection.start();
            TextMessage msg = null;
            try {
                while (true) {
                    msg = (TextMessage)receiver.receive();
                    System.out.println("[SimpleReceiver] received: "+msg.getText());
                    if (msg.getText().startsWith("LAST ")) break;
                }
            } catch (JMSException e) {
                System.err.println("Exception thrown by receive :"+e.getMessage());
            } catch (ClassCastException e) {
                System.err.println("Received an unknown message of type :"+msg.getClass().getName());
            }
            connection.stop();

            // now close all resources to ensure that native resources are released
            receiver.close();
            session.close();
            connection.close();
        } catch (Exception e) {
            System.err.println("Exception thrown from SimpleSender "+e.getMessage());
            e.printStackTrace();
        }
    }

}
