Hi,

Many times due to different requirement it is desired to list all the Messages present inside the JMS Queue. Also some times it is required to delete all the messages present inside the JMS Queue. jmx-console can be used to perform the same tasks, but most of the time in production environments we disable the jmx-console or admin-console. So in such scenarios we can use the following kind of JMX code to list and if required then delete the Messages present inside the JMS Queue.

In this sample we will be using the default JMS Queue provided by JBoss as “queue/DLQ” but if you want to create your own JMS Queue then you can refer to the following article “How to create a Queue in JBoss ?“. Also we will be using a simple “QueueSend.java” program to send some test messages in the JMS Queue and then with the help of “ManageJMSQueue.java” program we will list the JMS Messages present inside the JMS Queue and if required we will delete them through the same JMX Code.

Step1). Write the Simple “QueueSend.java” program somewhere in your file system to send some JMS Messages to the JMS Queue “queue/DLQ” as following:

import java.io.*;
import java.util.Hashtable;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class QueueSend
{
	public final static String JNDI_FACTORY="org.jnp.interfaces.NamingContextFactory";
	public final static String JMS_FACTORY="/XAConnectionFactory";
	public final static String QUEUE="/queue/DLQ";
	private QueueConnectionFactory qconFactory;
	private QueueConnection qcon;
	private QueueSession qsession;
	private QueueSender qsender;
	private Queue queue;
	private TextMessage msg;

public void init(Context ctx, String queueName)throws NamingException, JMSException
     {
	qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
	qcon = qconFactory.createQueueConnection();
	qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
	queue = (Queue) ctx.lookup(queueName);
	qsender = qsession.createSender(queue);
	msg = qsession.createTextMessage();
	qcon.start();
     }

public void send(String message) throws JMSException
     {
	msg.setText(message);
	qsender.send(msg);
     }

public void close() throws JMSException
     {
	qsender.close();
	qsession.close();
	qcon.close();
     }

public static void main(String[] args) throws Exception {
	if (args.length != 1) {
	System.out.println("Usage: java QueueSend JBossURL");
	System.out.println("Example: java QueueSend localhost:1099");
	return;
	}
	InitialContext ic = getInitialContext(args[0]);
	QueueSend qs = new QueueSend();
	qs.init(ic, QUEUE);
	readAndSend(qs);
	qs.close();
	}

private static void readAndSend(QueueSend qs) throws IOException, JMSException
    {
	String line="Test Message Body with counter = ";
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	boolean readFlag=true;
	System.out.println("ntStart Sending Messages (Enter QUIT to Stop):n");
        int i=1;
	while(readFlag)
	{
	   System.out.print("<Msg_Sender> ");
	   String msg=br.readLine();
	   if(msg.equals("QUIT") || msg.equals("quit"))
	    {
	        qs.send(msg);
        	System.exit(0);
 	    }
        qs.send(msg);
        System.out.println("ttt msg sent: "+i+"t "+msg);
        i++;
        System.out.println();
	}
	br.close();
     }

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

Step2). Now write the “ManageJMSQueue.java” program as following in order to list the messages present inside the JMS Queue “queue/DLQ” and if required delete them through the same code.

import javax.management.*;
import java.io.*;
import java.util.*;
import java.rmi.*;
import javax.naming.*;
import java.io.*;
public class ManageJMSQueue
   {
      private MBeanServerConnection server=null;
      public ManageJMSQueue()
      {
            try{
            Hashtable<String,String> ht=new Hashtable<String,String>();
            ht.put(Context.INITIAL_CONTEXT_FACTORY,"org.jboss.security.jndi.JndiLoginInitialContextFactory");
            ht.put(Context.PROVIDER_URL,"localhost:1099");
            ht.put(Context.SECURITY_PRINCIPAL,"admin");
            ht.put(Context.SECURITY_CREDENTIALS,"admin");
            System.out.println("nt 1- Gotting InitialContext...... ");
            Context ctx = new InitialContext(ht);
            System.out.println("nt 2- Got InitialContext: "+ctx);
            server = (MBeanServerConnection) ctx.lookup("jmx/invoker/RMIAdaptor");
            }
            catch(Exception e)
            {
                System.out.println("nnt Exception inside ManageJMSQueue..."+e);
            }
      }

      public void monitorJMS() throws Exception
      {
           ObjectName objectName=new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue");
           System.out.println("nnServerPeer = "+ (javax.management.ObjectName)server.getAttribute(objectName, new String("ServerPeer")));
           System.out.println("QueueName = "+ (String)server.getAttribute(new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue"), new String("Name")));
           System.out.println("JNDI Name = "+ (String)server.getAttribute(new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue"), new String("JNDIName")));
           System.out.println("FullSize = "+ (Integer)server.getAttribute(new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue"), new String("FullSize")));
      }

     public void listAllJMS_Messages() throws Exception
      {
           ObjectName objectName=new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue");
           List<org.jboss.jms.message.JBossTextMessage> messages=(List<org.jboss.jms.message.JBossTextMessage>)server.invoke(objectName, "listAllMessages" , null, null);
           int count=0;
           for(org.jboss.jms.message.JBossTextMessage msg : messages)
                    System.out.println((++count)+"t"+msg.getText());
      }

     public void removeAllJMS_Messages() throws Exception
      {
           String queueName=(String)server.getAttribute(new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue"), new String("Name"));
           System.out.println("nt Removing all JMS Messages from Queue: "+queueName);
           server.invoke(new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue"), "removeAllMessages" , null, null);
           System.out.println("nt All the Messages are removed from JMS Queue: "+queueName);
      }

     public static void main(String ar[]) throws Exception
       {
            ManageJMSQueue ref=new ManageJMSQueue();
            ref.monitorJMS();
            System.out.println("nt Following Messages Are present inside the JMS Queue:");
            ref.listAllJMS_Messages();
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.print("nn Please Specify (yes/no) to delete all the messages from JMS Queue ? ");
            String answer="";
            if((answer=br.readLine()).equals("yes"))
                             ref.removeAllJMS_Messages();
            br.close();
       }
  }

Step3). Compile and then run the “QueueSend.java” program as following and then send some messages to the JMS Queue:

javac QueueSend.java
java QueueSend localhost:1099
	Start Sending Messages (Enter QUIT to Stop):

<Msg_Sender> TestMessageOne
			 msg sent: 1	 TestMessageOne

<Msg_Sender> TestMessageTwo
			 msg sent: 2	 TestMessageTwo

<Msg_Sender> TestMessageThree
			 msg sent: 3	 TestMessageThree

<Msg_Sender> quit

Step4). After sending some Messages to the JMS Queue “queue/DLQ” Compile and then run the “ManageJMSQueue” program as following to list the messages present inside the JMS Queue:

javac ManageJMSQueue.java
java ManageJMSQueue localhost:1099

	 1- Gotting InitialContext......
	 2- Got InitialContext: javax.naming.InitialContext@74341960

ServerPeer = jboss.messaging:service=ServerPeer
QueueName = DLQ
JNDI Name = /queue/DLQ
FullSize = 200000

	 Following Messages Are present inside the JMS Queue:
1	TestMessageOne
2	TestMessageTwo
3	TestMessageThree
4	quit

 Please Specify (yes/no) toi delete all the messages from JMS Queue ? yes
	 Removing all JMS Messages from Queue: DLQ
	 All the Messages are removed from JMS Queue: DLQ

.
.
Thanks
Middleware Magic Team

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.