/* $Id$ */
// =========================================================
// Copyright (C) NEC Corporation 2005
// NEC CONFIDENTIAL AND PROPRIETARY
// All rights reserved by NEC Corporation.
// This program must be used solely for the purpose for which
// it was furnished by NEC Corporation. No part of this
// program may be reproduced or disclosed to others, in any
// form, without the prior written permission of NEC
// Corporation. Use of copyright notice does not evidence
// publication of the program.
// =========================================================

import java.util.Enumeration;

import javax.naming.InitialContext;
import javax.naming.NamingException;
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;

public class QueueBrowserExample
{
    private static QueueConnectionFactory queueConnectionFactory;
    private static QueueConnection        queueConnection;
    private static QueueSession           queueSession;
    private static QueueBrowser           queueBrowser;
    private static Queue                  queue;
    private static String                 QUEUECONFACT = "QueueConnectionFactory";

    private static String                 myname = QueueAsynchConsumer.class.getName();
    private static InitialContext         context;


    public static void main( String[] args )
    {
        String           queueName = null;
        TextMessage      message = null;

        if( args.length < 2 ) {
            System.out.println( "usage: java " + myname + " <queue_name> <factory_name>" );
            System.exit(1);
        }
        queueName = args[0];
        QUEUECONFACT = args[1];

        try {
            System.out.print( "looking up " + QUEUECONFACT + " ..." );
            queueConnectionFactory =
                    (QueueConnectionFactory)lookupJNDI( QUEUECONFACT );
            System.out.println( "done!!" );
            System.out.print( "creating QueueConnection ..." );
            queueConnection =
                    queueConnectionFactory.createQueueConnection();
            System.out.println( "done!!" );
            System.out.print( "creating QueueSession ..." );
            queueSession = queueConnection.createQueueSession( false,
                    Session.AUTO_ACKNOWLEDGE );
            System.out.println( "done!!" );
            System.out.print( "looking up " + queueName + " ..." );
            queue = (Queue)lookupJNDI( queueName );
            System.out.println( "done!!" );
        } catch( Exception e ) {
            System.out.println( e );
            e.printStackTrace();
            if( queueConnection != null ) {
                try {
                    queueConnection.close();
                } catch( JMSException ee ) {}
            }
        }

        try {
            System.out.print( "creating QueueBrowser ..." );
            QueueBrowser queueBrowser = queueSession.createBrowser(queue);
            System.out.println( "done!!" );
            Enumeration msgs = queueBrowser.getEnumeration();
            System.out.println( "Current messages browsing ..." );
            System.out.println( "============================================" );
            int count =0;
            while (msgs.hasMoreElements()) {
                count++;
                System.out.println("#" + (count));
                printMessage((Message)msgs.nextElement());
            }
            System.out.println((count == 0 ? "NO" : "\n" + String.valueOf(count)) +
                                " messages were found on queue <" + queueName + ">");
            System.out.println( "============================================" );
            System.out.println( "done!!" );
        } catch( Exception e ) {
            System.out.println( e );
            e.printStackTrace();
        } finally {
            if( queueConnection != null ) {
                try {
                    queueConnection.close();
                } catch( JMSException ee ) {}
            }
        }

        return;
    }


    private static Object lookupJNDI( String name ) throws Exception
    {
        Object    obj=null;

        if( context == null ) {
            try {
                context = new InitialContext();
            } catch( NamingException e ) {
                System.err.println( "lookupJNDI creatng InitialContext failed." );
                e.printStackTrace();
                throw e;
            }
        }
        try {
            obj = context.lookup( name );
        } catch( NamingException e ) {
            System.err.println( "lookupJNDI looking up object failed." );
            e.printStackTrace();
            throw e;
        }
        return obj;
    }


    private static void printMessage(Message msg) {
        try {
            System.out.println("Class: " + msg.getClass().getName() +
                                "\nID: " + msg.getJMSMessageID() +
                                "\nPriority: " + msg.getJMSPriority()
                                );
            Enumeration props = msg.getPropertyNames();
            if (props.hasMoreElements() == true) {
                System.out.print("Properties: ");
                while (props.hasMoreElements()) {
                    String propName = String.valueOf(props.nextElement());
                    System.out.print("" + propName + " = " + msg.getStringProperty(propName) +
                    (props.hasMoreElements() ? ", " : "\n"));
                }
            } else {
                System.out.print("Properties:  No Properties Found");
            }
            System.out.println("\nBody: " + msg.toString());
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}
