Weblogic

Programmatically Deleting Messages from Queue in Weblogic

Although I found many examples of this online, none of them were complete enough to “just work” for me with Weblogic.  The snippet below is the working method I ended up with after much trial and error.

The main piece I was missing was the call to connection.start();.  Please also notice the format of the message ID, which is used to delete a single message using a Message Selector.

import java.util.Hashtable;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
	
public class JMSDeleteFromQueueTest {

	public static void main(String[] args) throws NamingException, JMSException {
		final String CF_NAME = "jms/ConnectionFactory/MyConnectFactory";
		final String QUEUE_NAME = "jms/DistributedQueue/MyQueue";

		InitialContext initialContext;
		QueueConnectionFactory queueCF;

		Hashtable<String, String> properties = new Hashtable<String, String>();
		properties.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");

		initialContext = new InitialContext(properties);
		queueCF = (QueueConnectionFactory) initialContext.lookup(CF_NAME);
		
		final String messageId = "ID:<323320.1500603834230.0>";
		System.out.println("Delete message with ID = " + messageId);

		try (QueueConnection connection = queueCF.createQueueConnection();
			QueueSession session = connection.createQueueSession(false, JMSContext.CLIENT_ACKNOWLEDGE);) {
				connection.start();
				Queue errorRepositoryQueue = (Queue) initialContext.lookup(QUEUE_NAME);
				MessageConsumer consumer = session.createConsumer(errorRepositoryQueue, "JMSMessageID = '" + messageId + "'");
				System.out.println("selector = " + consumer.getMessageSelector());
				Message message = consumer.receive(1000);
				message.acknowledge();
		}

	}
	
}