package examples.jms.queue;

import java.io.*;
import java.util.*;
import javax.transaction.*;
import javax.naming.*;
import javax.jms.*;

/**
 * This example shows how to establish a connection to a JMS
 * queue and receive messages from a queue in a client-demarcated
 * transaction.  The classes in this package operate on the same 
 * JMS queue. Run the classes together to witness messages being 
 * sent and received and to browse the queue for messages. 
 * <p>
 * To run this example:
 * <p>
 * <ol>
 * Compile the examples in this directory with a command like this:
 * <pre>  javac -d /weblogic/classes *.java</pre>
 * <li>
 * Start the WebLogic Server.
 * <li>
 * Execute the example from a command line with the WebLogic Server URL:
 * <pre>  java examples.jms.queue.QueueReceiveInTx t3://localhost:7001</pre>
 * <li>
 * The program displays messages as they are received from the Queue. 
 * To end the program, send a <tt>quit</tt> message from the shell running 
 * the examples.jms.queue.QueueSend program.
 * </ol>
 *
 * @author Copyright (c) 1999-2000 by BEA Systems, Inc. All Rights Reserved.
 */
public class QueueReceiveInTx
{
  public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
  public final static String JMS_FACTORY="javax.jms.QueueConnectionFactory";
  public final static String QUEUE="javax.jms.exampleQueue";

  private QueueConnectionFactory qconFactory;
  private QueueConnection qcon;
  private QueueSession qsession;
  private QueueReceiver qreceiver;
  private Queue queue;
  private boolean quit = false;
  private UserTransaction utx;

  public void receiveMessages()
  {
    Message msg = null;
    String msgText = "";

    try {
      utx.begin();
      System.out.println("TRANSACTION BEGUN");
      do {
        msg = qreceiver.receive();
        if (msg != null) {
          if (msg instanceof TextMessage) {
            msgText = ((TextMessage)msg).getText();
          } else {
            msgText = msg.toString();
          }
          System.out.println("Message Received: "+ msgText );
          if (msgText.equalsIgnoreCase("quit")) {
            utx.commit();
            System.out.println("TRANSACTION COMMITTED");
          }
        }
      } while(msg != null && ! msgText.equals("quit"));
    } catch (JMSException jmse) {
      System.out.println("Error receiving JMS message: "+jmse);
      jmse.printStackTrace();
    } catch (javax.transaction.NotSupportedException nse) {
      System.out.println("TRANSACTION COULD NOT BEGIN DUE TO: "+ nse);      
    } catch (javax.transaction.RollbackException rbe) {
      System.out.println("TRANSACTION ROLLED BACK DUE TO: "+rbe);
    } catch (javax.transaction.HeuristicRollbackException hre) {
      System.out.println("TRANSACTION ROLLED BACK DUE TO: "+hre);
    } catch (javax.transaction.HeuristicMixedException hme) {
      System.out.println("TRANSACTION ROLLED BACK DUE TO: "+hme);
    } catch (javax.transaction.SystemException se) {
      System.out.println("TRANSACTION EXCEPTION: "+se);
    }
  }

  /**
   * Create all the necessary objects for receiving
   * messages from a JMS queue.
   */
  public void init(Context ctx, String queueName)
       throws NamingException, JMSException
  {
    qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
    qcon = qconFactory.createQueueConnection();
    qsession = qcon.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
    utx = (UserTransaction) ctx.lookup("javax.transaction.UserTransaction");
    try {
      queue = (Queue) ctx.lookup(queueName);
    } catch (NamingException ne) {
      queue = qsession.createQueue(queueName);
      ctx.bind(queueName, queue);
    }
    qreceiver = qsession.createReceiver(queue);
    qcon.start();
  }

  /**
   * Close JMS objects.
   */
  public void close()
       throws JMSException
  {
    qreceiver.close();
    qsession.close();
    qcon.close();
  }


  public static void main(String[] args)
       throws Exception 
  {
    if (args.length != 1) {
      System.out.println("Usage: java examples.jms.queue.QueueReceiveInTx WebLogicURL");
      return;
    }
    InitialContext ic = getInitialContext(args[0]);
    QueueReceiveInTx qr = new QueueReceiveInTx();
    qr.init(ic, QUEUE);

    System.out.println("JMS Ready To Receive Messages (To quit, send a \"quit\" message).");

    qr.receiveMessages();
    qr.close();
  }

  private static InitialContext getInitialContext(String url)
       throws NamingException
  {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
    env.put(Context.PROVIDER_URL, url);
    return new InitialContext(env);
  }

}




