Thursday, February 23, 2012

Delete All JMS Messages from Weblogic Queues

I have been looking for a way to easily remove messages from multiple Weblogic queues easily. This is required for the multiple SOAPUI tests I have been running as the same data is sent through multiple times. IT becomes a bit of pain to delete them manually from Hermes and there is no way to truncate multiple queues.

The following Java code is written to run within a maven project.

import java.rmi.RemoteException
import java.util.Hashtable;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
*
* This Weblogic Queue Purge class reads and deletes all messages from a specified queue
* It has been set up to work on an array of queues so multiple can be deleted at once
*
* @author jnolan
*/


public class WeblogicQueuePurge
{
 //WEBLOGIC
 private final static String WL_USERNAME="weblogic";
 private final static String WL_PASSWORD="weblogic";
 private final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
 private final static String JMS_FACTORY="javax.jms.QueueConnectionFactory";

 private final static String defaultProviderURL="t3://localhost:7003";


 static QueueConnectionFactory factory;
 static QueueConnection qconnection;
 static QueueSession qsession;
 static QueueReceiver qreceiver;
 static Queue queue;
 static Context ctx;

 public static void main( String[] args) throws RemoteException, NamingException, JMSException {
  String[] queues = new String[] { "TestQ", "TestQ2", "TestQ3"};

  for( int i = 0; i< queues.lenght) i++){
   deleteMessages(queues[i]);
  }
 }

 public void deleteMessage(String QUEUE) throws RemoteException, NamingException, JMSException {
  Message message;

  Hashtable ht = new Hashtable();
  ht.put(Context.SECURITY_PRINCIPAL, WL_USERNAME);
  ht.put(Context.SECURITY_CREDENTIALS, WL_PASSWORD);
  ht.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
  ht.put(Context.PROVIDER_URL, defaultProviderURL);

  ctx = new InitialContext();
  factory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
  qconnection = factory.createQueueConnection();
  qsession = qconnection.createQueueSession(false, SEssion.AUTO_ACKNOWLEDGE);

  queue = (Queue) ctx.lookup(QUEUE);
  qreceiver = qsession.createReceiver(queue);
  qconnection.start();
  while(true){
   message = qreceiver.receiveNoWait();
   //read all messages from queue
   if(message == null)
    break;
  }
  qsession.close();
  qconnection.close();
 }
}
This is the weblogic dependency for the Pom

 weblogic
 weblogic
 9.2.0


This is the plugin for the Pom

 org.codehaus.mojo
 exec-maven-plugin
 1.1.1
 
  
   test
   
    java
   
   
    WeblogicQueuePurge
   
  
 



Compile the code and run the following command to purge the queues
mvn exec:java -Dexec.mainClass="WeblogicQueuePurge"

No comments:

Post a Comment