Wednesday, October 17, 2012

Post JMS messages to WebSphere queues from stand alone Client:

We may encounter a situation to send JMS messages to queues/topics configured in Websphere from standalone java program and unit/functional testing would be one good scenario for our case.

We need additional client libraries to lookup resources from JNDI and connect to websphere SIB and queues which can be downloaded from here.

Client Program:

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.io.*;


public class PostJMSMessage {

public static void publish() {
final Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.ibm.websphere.naming.WsnInitialContextFactory");
env.put(Context.PROVIDER_URL, "iiop://:");

final Context jndiContext;
try {
jndiContext = new InitialContext(env);
} catch (NamingException e) {
System.err.println("Could not create JNDI API context: "+ e.toString());
System.exit(1);
return;
}

try {
ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext.lookup("");
Connection qConn = connectionFactory.createConnection();
Session qSession = qConn.createSession(false,Session.AUTO_ACKNOWLEDGE);
Queue q = (Queue) jndiContext.lookup("");

MessageProducer producer = qSession.createProducer(q);
ObjectMessage message = qSession.createObjectMessage();
message.setObject((Serializable) );
producer.send(message);

producer.close();
qSession.close();
qConn.close();
in.close();
} catch (Exception e) {
System.err.println("Could not perfrom JMS operation: "+ e.toString());
System.exit(2);
}
}

public static void main(String[] args) {
publish();
}
}


Jars required in classpath:

The following jars are required in classpath along with any application specific jars to compile and run the program

sibc.jms.jar
sibc.jndi.jar
sibc_install-o0902.06.jar

Compile & Run:

Navigate to the directory where the client program and jars are copied and find out IBM jdk path.

/opt/IBM/WebSphere/AppServer/java/bin/javac -cp :sibc.jms.jar:sibc.jndi.jar:. PostJMSMessage.java

/opt/IBM/WebSphere/AppServer/java/bin/java -cp :sibc.jms.jar:sibc.jndi.jar:. PostJMSMessage

No comments:

Enter your Comments