Tuesday, March 31, 2015

Accessing Oracle Advanced Queue (OAQ) directly using JNDI and plain JMS from a standalone java program


I spent a while trying to insert a message into AQ from a standalone Java program. All examples in the internet were using a foreign JMS in weblogic and then accessing the Queues. I didn't want to go that route and add an extra layer between my stand alone program and Oracle AQ. I hope this helps you. You can also use a similar technique to configure OAQ as JMS connection in any middleware software.

Basically there are 3 jars that are required to be in the class path
1. aqapi.jar
2. jmscommon.jar
3. ojdbc6.jar


The Initial Context

The context Factory should be oracle.jms.AQjmsInitialContextFactory
Context.INITIAL_CONTEXT_FACTORY oracle.jms.AQjmsInitialContextFactory
Context.SECURITY_PRINCIPAL dbusername
Context.SECURITY_CREDENTIALS dbpassword
"db_url" jdbc:oracle:thin:dbusername/dbpassword@hostname:1521:SID

Looking up Connection Factory

If you are looking up QueueConnectionFactory use the string QueueConnectionFactory. Below are some valid Values
ConnectionFactory
QueueConnectionFactory
TopicConnectionFactory
XAConnectionFactory
XAQueueConnectionFactory
XATopicConnectionFactory

Looking Up Queues or Factories

For Queues use Queues/QUEUENAME
For Topics use Topics/TOPICNAME


Working snippet

try {
    QueueConnectionFactory qcf = null;
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "oracle.jms.AQjmsInitialContextFactory");
    env.put(Context.SECURITY_PRINCIPAL, "dbusername");
    env.put(Context.SECURITY_CREDENTIALS, "dbpassword");
    env.put("db_url", "jdbc:oracle:thin:dbusername/dbpassword@hostname:1521:SID");
    InitialContext ctx = new InitialContext(env);
    qcf = (QueueConnectionFactory)ctx.lookup("QueueConnectionFactory");
    QueueConnection qc = qcf.createQueueConnection( "dbusername","dbpassword");
    QueueSession qsession = qc.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
    System.out.println("Successfully created AQ session");
    Queue q = (Queue)ctx.lookup("Queues/OTMQUEUE");
    QueueSender qs = qsession.createSender(q);
    TextMessage msg = qsession.createTextMessage();
    msg.setText("Message hello world");
    qs.send(msg);
    qs.close();
    qsession.commit();
    qsession.close();
    qc.close();
} catch (Exception ex) {
    ex.printStackTrace();
}