import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueBrowser;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;



/**
 * Browses a given queue
 */
public class Browser {
	
	public static void main(String[] args){
		
		if (args.length != 1 ){
			System.out.println("usage: Browser <queue name>");
			System.exit(1);
	    }
		
		//declare and initialise variables
		String queueName= args[0];
		Context context = null;
        QueueConnectionFactory qFactory = null;
        QueueConnection qConnection = null;
        String factoryName = "JmsQueueConnectionFactory";
        Queue queue = null;
        QueueSession qSession = null;
        QueueBrowser qBrowser = null;
        java.util.Enumeration<Message> messages = null;
        Message msg;
        
		//
		System.out.println();
	    System.out.println("Browses queue: " + queueName);
	    
	    //
	    try 
	    {
	    	// create the JNDI initial context
	    	context = new InitialContext();
	    	
	    	// look up the ConnectionFactory
			qFactory = (QueueConnectionFactory) context.lookup(factoryName);
			
			// look up the Destination
			queue = (Queue) context.lookup(queueName);
			
			// create the connection
			qConnection = qFactory.createQueueConnection( "admin", "joram" );
			
			// create the session
			qSession = qConnection.createQueueSession
			    (false, Session.AUTO_ACKNOWLEDGE);
			
			//create a browser
			qBrowser = qSession.createBrowser(queue);
			
			//get the messages in the given queue
			messages = qBrowser.getEnumeration();

		    //print messages
		    while (messages.hasMoreElements()) {
		      msg = messages.nextElement();

		      if (msg instanceof TextMessage)
		        System.out.println(((TextMessage) msg).getText());
		    }

		    System.out.println();
		    System.out.println("Queue browsed.");

		    qConnection.close();
		}
	    catch(Exception e){
	    	e.printStackTrace();
	    	// close the connection
            if (qConnection != null) 
		{
		    try 
			{
		    	qConnection.close();
			} 
		    catch (JMSException exception) 
			{
			    exception.printStackTrace();
			}
		}
	    }
	}

}
