Wednesday, July 13, 2011

JMS: delete (remove) all messages from a JMS Queue

public static final String WEBLOGIC_JMS_XA_CONNECTION_FACTORY = "weblogic/jms/XAConnectionFactory";


 public static Context createInitialContext() throws NamingException {
  Hashtable ht = new Hashtable();
  ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
  ht.put(Context.PROVIDER_URL, "t3://acme.com:7009");     
  Context ctx = new InitialContext(ht);
  return ctx;
 }


 public void init(String jndiname) throws Exception {
  // get the initial context
  Context ctx = createInitialContext();
  // lookup the queue object
  queue = (Queue) ctx.lookup(jndiname);
  
  // lookup the queue connection factory
  queueConnFactory = (QueueConnectionFactory) ctx.lookup(WEBLOGIC_JMS_XA_CONNECTION_FACTORY);
  // create a queue connection
  queueConn = queueConnFactory.createQueueConnection();
  // create a queue session
  queueSession = queueConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
  // create a queue browser
  queueBrowser = queueSession.createBrowser(queue);
  
  // start the connection
  queueConn.start();
 }


 public void deleteAllMessagesFromQueue(String jndiname) throws Exception {
    init(jndiname);
    MessageConsumer consumer = queueSession.createConsumer(queue);
    Message message = null;
    do {
        message = consumer.receiveNoWait();
     if (message != null) message.acknowledge();
    } 
    while (message != null);
  
    consumer.close();
    queueConn.close();
 }






No comments: