Here are some simple sample applications for WebSphere MQ JMS that you may find useful. You may use them to verify your installation or to learn more about WebSphere MQ JMS semantics.
Both applications use client bindings rather than local bindings; and do not make use of JNDI for simplicity. They can be run as standalone J2SE/JSE programs.
Note: Applications need minor tweak in the config section and destination names according to your setup.
Author: Saket Rungta, wastedmonkeys.com
Simple Point-to-point application using WebSphere MQ JMS
package my.samples;
import javax.jms.JMSException;
import javax.jms.Session;
import com.ibm.jms.JMSMessage;
import com.ibm.jms.JMSTextMessage;
import com.ibm.mq.jms.JMSC;
import com.ibm.mq.jms.MQQueue;
import com.ibm.mq.jms.MQQueueConnection;
import com.ibm.mq.jms.MQQueueConnectionFactory;
import com.ibm.mq.jms.MQQueueReceiver;
import com.ibm.mq.jms.MQQueueSender;
import com.ibm.mq.jms.MQQueueSession;
/**
* SimplePTP: A minimal and simple testcase for Point-to-point messaging (1.02 style).
*
* Assumes that the queue is empty before being run.
*
* Does not make use of JNDI for ConnectionFactory and/or Destination definitions.
*
* @author saket
*/
public class SimplePTP {
/**
* Main method
*
* @param args
*/
public static void main(String[] args) {
try {
MQQueueConnectionFactory cf = new MQQueueConnectionFactory();
// Config
cf.setHostName("localhost");
cf.setPort(1414);
cf.setTransportType(JMSC.MQJMS_TP_CLIENT_MQ_TCPIP);
cf.setQueueManager("QM_thinkpad");
cf.setChannel("SYSTEM.DEF.SVRCONN");
MQQueueConnection connection = (MQQueueConnection) cf.createQueueConnection();
MQQueueSession session = (MQQueueSession) connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
MQQueue queue = (MQQueue) session.createQueue("queue:///Q1");
MQQueueSender sender = (MQQueueSender) session.createSender(queue);
MQQueueReceiver receiver = (MQQueueReceiver) session.createReceiver(queue);
long uniqueNumber = System.currentTimeMillis() % 1000;
JMSTextMessage message = (JMSTextMessage) session.createTextMessage("SimplePTP "+ uniqueNumber);
// Start the connection
connection.start();
sender.send(message);
System.out.println("Sent message:\\n" + message);
JMSMessage receivedMessage = (JMSMessage) receiver.receive(10000);
System.out.println("\\nReceived message:\\n" + receivedMessage);
sender.close();
receiver.close();
session.close();
connection.close();
System.out.println("\\nSUCCESS\\n");
}
catch (JMSException jmsex) {
System.out.println(jmsex);
System.out.println("\\nFAILURE\\n");
}
catch (Exception ex) {
System.out.println(ex);
System.out.println("\\nFAILURE\\n");
}
}
}
Simple Publish/Subscribe application using WebSphere MQ JMS
package my.samples;
import javax.jms.JMSException;
import javax.jms.Session;
import com.ibm.jms.JMSMessage;
import com.ibm.jms.JMSTextMessage;
import com.ibm.mq.jms.JMSC;
import com.ibm.mq.jms.MQTopic;
import com.ibm.mq.jms.MQTopicConnection;
import com.ibm.mq.jms.MQTopicConnectionFactory;
import com.ibm.mq.jms.MQTopicPublisher;
import com.ibm.mq.jms.MQTopicSession;
import com.ibm.mq.jms.MQTopicSubscriber;
/**
* SimplePubSub: A minimal and simple testcase for Publish/Subscribe (1.02 style).
*
* Topics are dynamically created on the queue manager and need not be pre-defined.
*
* (The Broker must be enabled on the queue manager and the JMS Publish/Subscribe
* queues must be defined manually.)
*
* Note: These samples are for WMQ Base Broker and incomplete for WebSphere Message Broker)
*
* Does not make use of JNDI for ConnectionFactory and/or Destination definitions.
*
* @author saket
*/
public class SimplePubSub {
/**
* Main method.
*
* @param args
*/
public static void main(String[] args) {
try {
MQTopicConnectionFactory cf = new MQTopicConnectionFactory();
// Config
cf.setHostName("localhost");
cf.setPort(1414);
cf.setTransportType(JMSC.MQJMS_TP_CLIENT_MQ_TCPIP);
cf.setQueueManager("QM_thinkpad");
cf.setChannel("SYSTEM.DEF.SVRCONN");
MQTopicConnection connection = (MQTopicConnection) cf.createTopicConnection();
MQTopicSession session = (MQTopicSession) connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
MQTopic topic = (MQTopic) session.createTopic("topic://foo");
MQTopicPublisher publisher = (MQTopicPublisher) session.createPublisher(topic);
MQTopicSubscriber subscriber = (MQTopicSubscriber) session.createSubscriber(topic);
long uniqueNumber = System.currentTimeMillis() % 1000;
JMSTextMessage message = (JMSTextMessage) session.createTextMessage("SimplePubSub "+ uniqueNumber);
// Start the connection
connection.start();
publisher.publish(message);
System.out.println("Sent message:\\n" + message);
JMSMessage receivedMessage = (JMSMessage) subscriber.receive(10000);
System.out.println("\\nReceived message:\\n" + receivedMessage);
publisher.close();
subscriber.close();
session.close();
connection.close();
System.out.println("\\nSUCCESS\\n");
}
catch (JMSException jmsex) {
System.out.println(jmsex);
System.out.println("\\nFAILURE\\n");
}
catch (Exception ex) {
System.out.println(ex);
System.out.println("\\nFAILURE\\n");
}
}
}

26 comments
Comments feed for this article
June 4, 2007 at 4:32 pm
Anonymous
I like the format of this WMQ blog. It is pleasant to the eye and also to actually read English again. I hope it becomes as popular and as much used as the mqseries.net site. The mqseries.net site is such a zoo and the search engines give you everything under the sun no matter what you put in for query arguments, which makes them not useless but close.
You might want to advertise this site a bit more… I completely inadvertently stumbled upon it. A Google search found an interesting looking xml file that I decided I wanted to go to the origin site of where it came from. Not exactly a high hit path to get new users… I don’t think.
Thanks for taking the lead on creating this site content!!
Regards,
GTC
June 7, 2007 at 5:50 pm
Khang
I am using MQ 6.0.2, with support pac for Topic, do not touch the JMS Administrated Objects.
I already run “strmqbrk -m QMA”, create topic “XYZ”.
Run MQ Explorer, right-click on topic “XYZ”, click “Test Publication”, everything is running well
However, when I run the above code, SimplePubSub, connect to topic XYZ. (all on the same machine)
error: javax.jms.JMSException: MQJMS1111: JMS1.1 The required Queues/Publish Subscribe services are not set up {0}
JMSException nFAILUREn
Could you help me what other things I need to run before above java code running
June 18, 2007 at 4:13 pm
Sergio
Hi Saket,
First of all – thank you for starting this site. I much appreciated it clear-cut style, and concise yet complete examples. Great work!
I would like to correct a small bug in your sample code:
The following line:
MQQueue queue = (MQQueue) session.createQueue(“queue://Q1″);
Should actually be:
MQQueue queue = (MQQueue) session.createQueue(“queue:///Q1″);
Note three forward slashes are required (not two) to account for a default queue manager name.
Best regards, and keep posting!
Sergio
June 18, 2007 at 4:40 pm
Saket Rungta
@Sergio
Thanks Sergio for the kind words and yes, you spotted it well! I’ve fixed the original post.
@Khang
Apologies, I couldn’t help you with debugging. It is difficult without sufficient information.
@GTC
Many thanks for the kind words.
June 19, 2007 at 8:46 am
Anonymous
Hi Saket,
This line also needs to be fixed – I forgot to put it in my first post:
MQTopic topic = (MQTopic) session.createTopic(“topic://foo”);
should be:
MQTopic topic = (MQTopic) session.createTopic(“topic:///foo”);
Thanks!
June 19, 2007 at 9:23 am
Saket Rungta
I’m not sure I agree with that. Two forward slashes is correct for topics. Please see ‘Using Java’ book for more details. thanks for your interest.
Topic name syntax:
topic://TopicName[?property=value[&property=value]*]
June 19, 2007 at 9:35 am
Anonymous
Apologies!
You are right – only two slashes are required.
S.
July 5, 2007 at 3:49 am
Joseph
Hi,
I’m trying to connect to a remote Websphere MQ Server, which was setup by another team in our company. I tried to use your first example (with little modifications) and got this error:
javax.jms.JMSSecurityException: MQJMS2013: invalid security authentication supplied for MQQueueManager
I was wondering if you guys know how to resolve this…
thanks,
-J
July 7, 2007 at 1:06 pm
FJ
@saket
I am not sure I like the example that much. Does it expect to use a channel table? I always believed that in a client connection you needed 3 things:
host — present and catered for
port — present and catered for
channel — conspicuously absent from your setup
qmgr name — optional (present here)
@Joseph
In the simple JMS setup we have here you would use
cf.createQueueConnection(userid, passwd) or cf.createTopicConnection(userid,passwd) to specify a user for the use of the connection. Ususally this is obfuscated by the use of a JAAS alias in the JNDI setup. Now if you need to go SSL you better read the manuals. I believe there is a whole book about SSL.
July 23, 2007 at 11:59 am
Saket Rungta
@FJ
Thanks. You’re right, I’ve added channel information.
July 24, 2007 at 3:42 am
Joseph
@Saket,
Things went well after adding channel. Would you happen to know how to implement session id of some sort? I think it has something to do with correlation id…
regards,
-J
October 19, 2007 at 1:57 pm
Andy Piper
@Khang you need to run MQJMS_PSQ.mqsc from the \Java\bin directory on your Queue Manager in order for the JMS stuff to work.
October 26, 2007 at 11:32 am
Balakumar
Websphere MQ JMS code is working fine… Can anyone help me in pooling the connection factory… It will be of great use to me.
November 29, 2007 at 9:02 pm
Jose R Padilla
How do you use Pubsub using WAS definition for:
WebSphere MQ connection factory collection?
January 24, 2008 at 10:25 am
Ashish Shekhar
Hi Saket,
I was going through your blog and its a commendable effort I must say.
I had a question that I was searching about.
How do we find out which queue manager is a remote queue manager pointing to? Basically how to read the properties of a queue through Java.
Please see if you can help me with this.
Regards,
Ashish
January 24, 2008 at 5:52 pm
Saket Rungta
@Ashish,
To read properties of a queue in the Java language is feasible by using the PCF classes. These are available as a downloadable add-on (aka SupportPac) at:
http://www-1.ibm.com/support/docview.wss?rs=171&uid=swg24000668&loc=en_US&cs=utf-8&lang=en
I’m not aware of how a client application can query a qmgr for another connected qmgr properties, but it may be feasible. Try exploring the functionality offered by the PCF classes.
thanks.
January 28, 2008 at 6:18 am
Ashish Shekhar
I tried the PCF classes and i’m usign the following code to check for the queue attributes which is working fine for local queues but not for remote definitions. could you suggest something on this?
code:
package com.anz.MQ;
// ==================================================================
//
// Program Name
// MQAttr
//
// Last date of modification
// 1 Oct 2000
//
// Description
// This java class will output the attributes of a queue.
//
// Sample Command Line Parameters
// -h 127.0.0.1 -p 1414 -c CLIENT.CHANNEL -m MQA1 -q TEST.QUEUE
//
// Copyright(C), Roger Lacroix, Capitalware
//
// ——————————————————————
import com.ibm.mq.*;
import com.ibm.mq.pcf.PCFConstants;
import java.io.IOException;
import java.util.Hashtable;
import java.io.*;
import java.util.GregorianCalendar;
import java.util.Calendar;
public class MQAttr
{
private MQQueueManager _queueManager = null;
private Hashtable params = null;
public int port = 1414;
public String hostname = “127.0.0.1″;
//public String channel = “CLIENT.TO.MQA1″;
public String channel = “SYSTEM.DEF.SVRCONN”;
//public String qManager = “MQA1″;
public String qManager = “INDASHISH.MQ”;
public String inputQName = “SYSTEM.DEFAULT.LOCAL.QUEUE”;
public MQAttr()
{
super();
}
private boolean allParamsPresent()
{
boolean b = params.containsKey(“-h”) &&
params.containsKey(“-p”) &&
params.containsKey(“-c”) &&
params.containsKey(“-m”) &&
params.containsKey(“-q”);
if (b)
{
try
{
port = Integer.parseInt((String) params.get(“-p”));
}
catch (NumberFormatException e)
{
b = false;
}
// Set up MQ environment
hostname = (String) params.get(“-h”);
channel = (String) params.get(“-c”);
qManager = (String) params.get(“-m”);
inputQName = (String) params.get(“-q”);
}
return b;
}
private void getAttr() throws MQException
{
// int openOptions = MQC.MQOO_INQUIRE + MQC.MQOO_FAIL_IF_QUIESCING + MQC.MQOO_INPUT_SHARED;
int openOptions = MQC.MQOO_INQUIRE + MQC.MQOO_FAIL_IF_QUIESCING;
int InhibitGet;
String dType=”Nothing”;
String qType=”Nothing”;
String iPut=”Nothing”;
String iGet=”Nothing”;
String share=”Nothing”;
String tControl = “Nothing”;
String tType = “Nothing”;
int qTypeNum=0;
// GregorianCalendar DateTime;
String Date;
String Time;
MQQueue queue = _queueManager.accessQueue( inputQName,
openOptions,
null, // default q manager
null, // no dynamic q name
null ); // no alternate user id
System.out.println(“MQAttr v1.0 connected.\n”);
try
{
qTypeNum = queue.getQueueType();
System.out.println(“Found queue type: ” + qTypeNum);
switch (qTypeNum)
{
case MQC.MQQT_LOCAL:
qType = “Local”;
break;
case MQC.MQQT_MODEL:
qType = “Model”;
break;
case MQC.MQQT_ALIAS:
qType = “Alias”;
break;
case MQC.MQQT_REMOTE:
qType = “Remote”;
break;
// case MQC.MQQT_CLUSTER:
case 7:
qType = “Cluster”;
break;
default :
qType = “Unknown”;
break;
}
if ( (qTypeNum == MQC.MQQT_LOCAL ) ||
(qTypeNum == MQC.MQQT_MODEL ) ||
(qTypeNum == MQC.MQQT_REMOTE ) ||
(qTypeNum == MQC.MQQT_ALIAS ) )
{
if (queue.getInhibitPut() == MQC.MQQA_PUT_ALLOWED)
iPut = “Allowed”;
else
iPut = “Inhibited”;
}
if ( (qTypeNum == MQC.MQQT_LOCAL ) ||
(qTypeNum == MQC.MQQT_MODEL ) ||
(qTypeNum == MQC.MQQT_ALIAS ) )
{
if (queue.getInhibitGet() == MQC.MQQA_GET_ALLOWED)
iGet = “Allowed”;
else
iGet = “Inhibited”;
}
System.out.println(“Queue Name: ” + inputQName);
System.out.println(“Queue Type: ” + qType );
if ( (qTypeNum == MQC.MQQT_LOCAL) || (qTypeNum == MQC.MQQT_MODEL) )
{
switch (queue.getDefinitionType())
{
case MQC.MQQDT_PREDEFINED :
dType = “Predefined”;
break;
case MQC.MQQDT_PERMANENT_DYNAMIC :
dType = “Permanent”;
break;
case MQC.MQQDT_TEMPORARY_DYNAMIC :
dType = “Temporary”;
break;
default :
dType = “Unknown”;
break;
}
if (queue.getShareability() == MQC.MQQA_SHAREABLE )
share = “Shareable”;
else
share = “Not Shareable”;
if (queue.getTriggerControl() == MQC.MQTC_OFF )
tControl = “OFF”;
else
tControl = “ON”;
switch (queue.getTriggerType())
{
case MQC.MQTT_NONE :
tType = “None”;
break;
case MQC.MQTT_FIRST:
tType = “First”;
break;
case MQC.MQTT_EVERY:
tType = “Every”;
break;
case MQC.MQTT_DEPTH:
tType = “Depth”;
break;
default :
tType = “Unknown”;
break;
}
System.out.println(“Definition Type: ” + dType );
System.out.println(“Current Depth: ” + queue.getCurrentDepth() );
System.out.println(“Get Messages: ” + iGet );
System.out.println(“Put Messages: ” + iPut );
System.out.println(“Maximum Depth: ” + queue.getMaximumDepth() );
System.out.println(“Maximum Message Length: ” + queue.getMaximumMessageLength() );
System.out.println(“Open Input Count: ” + queue.getOpenInputCount() );
System.out.println(“Open Output Count: ” + queue.getOpenOutputCount() );
System.out.println(“Shareability: ” + share );
System.out.println(“Trigger Control: ” + tControl );
System.out.println(“Trigger Type: ” + tType );
System.out.println(“Trigger Data: ” + queue.getTriggerData() );
System.out.println(“Trigger Depth: ” + queue.getTriggerDepth() );
System.out.println(“Trigger Message Priority: ” + queue.getTriggerMessagePriority() );
} // if
if (qTypeNum == MQC.MQQT_REMOTE)
{
System.out.println(“Put Messages: ” + iPut );
}
if (qTypeNum == MQC.MQQT_ALIAS)
{
System.out.println(“Get Messages: ” + iGet );
System.out.println(“Put Messages: ” + iPut );
}
} // try
catch (MQException e)
{
if ( (e.completionCode == 1 ) && (e.reasonCode == 2068) )
{
}
else
{
System.out.println(“MQ Error:Completion code:” + e.completionCode + ” reason code: ” + e.reasonCode );
System.exit(1);
}
}
queue.close();
_queueManager.disconnect();
}
private void init(String[] args) throws IllegalArgumentException
{
params = new Hashtable(5);
if (args.length > 0 && (args.length % 2) == 0)
{
for (int i = 0; i < args.length; i+=2)
{
params.put(args[i], args[i+1]);
}
}
else
{
throw new IllegalArgumentException();
}
if (allParamsPresent())
{
// Set up MQ environment
MQEnvironment.hostname = hostname;
MQEnvironment.channel = channel;
MQEnvironment.port = port;
}
else
{
throw new IllegalArgumentException();
}
}
public static void main(String[] args)
{
MQAttr mqattr = new MQAttr();
try
{
mqattr.init(args);
mqattr.selectQMgr();
mqattr.getAttr();
}
catch (IllegalArgumentException e)
{
System.out.println(“Usage: java MQAttr “);
System.exit(1);
}
catch (MQException e)
{
System.out.println(e + “: ” + PCFConstants.lookupReasonCode (e.reasonCode));
System.exit(1);
}
}
private void selectQMgr() throws MQException
{
_queueManager = new MQQueueManager(qManager);
}
}
This is being run with the appropriate command line agruments.
Regards,
Ashish
January 28, 2008 at 10:18 am
Ethan
I got the following error when I tried the above code in two different boxes, MQ server in one box (linux) while the program runs in another (Sun).
I have make the user found in both boxes and belongs to the same group.
What else could have caused the exception?
javax.jms.JMSException: MQJMS2007: failed to send message to MQ queue
javax.jms.JMSException: MQJMS2007: failed to send message to MQ queue
at com.ibm.mq.jms.services.ConfigEnvironment.newException(ConfigEnvironment.java:553)
at com.ibm.mq.jms.MQMessageProducer.sendInternal(MQMessageProducer.java:1598)
at com.ibm.mq.jms.MQMessageProducer.send(MQMessageProducer.java:1022)
at com.ibm.mq.jms.MQMessageProducer.send(MQMessageProducer.java:1056)
at SimplePTP.main(SimplePTP.java:58)
August 2, 2010 at 3:13 pm
adityat2010
Hi Ethan,
what was the fix for the above issue. I am also facing the same issue.
May 26, 2008 at 11:00 am
hananafci
hello ,
i have a task to make java program (jms) that will listen to mq queue and whenever a new message is added to the queue the program should print it so as long as the program is running ,any message added to the queue must be printed by the program and now am searching for any one to help me how to make this .
thanks alot
January 6, 2009 at 1:08 pm
krishanka
Can anyone tell me how to send an XML file using JMS in an IBM MQ
February 23, 2009 at 8:10 pm
Waldemar’s blog » Blog Archive » IBM WebSphere MQ testing using LoadRunner
[...] My first script for WebSphere MQ testing was written in Java as Java Vuser script. It it pretty simple since we are just using MQ JMS API. There is lots of examples howto connect to WebSphere in Java. Here is good a example http://hursleyonwmq.wordpress.com/2007/05/29/simplest-sample-applications-using-websphere-mq-jms/. [...]
August 25, 2009 at 1:05 pm
shashanksdixit
Hi
I have created factory as given above and I tried to getConnection by following.
MQQueueConnection connection = (MQQueueConnection) cf.createQueueConnection();
I received JMSException as given by Joseph above. Then I tried
MQQueueConnection connection = (MQQueueConnection) cf.createQueueConnection(” “, ” “); // with a simple blank space.
I was able to get the connection. If I try something different e.g. createQueueConnection(“abcd “, “abcd “) then I get JMSException. I understand that the user ‘abcd’ does not exist. But does a blank space (” “) user exists? I am not able to understand why the code has worked for cf.createQueueConnection(” “, ” “). Can somebody please enlighten me ? Thanks a lot in advance.
Regards,
Shashank
August 3, 2010 at 4:51 am
Simplest sample applications using WebSphere MQ JMS « Felipe Avendano's Blog
[...] source/fuente: http://hursleyonwmq.wordpress.com [...]
September 13, 2010 at 10:09 am
Implementing retrial with a MDB or an MQ batch job? (WAS 7, MQ 6) « The Holy Java
[...] Use MQ provider-specific APIs to create the objects and configure them. See this JMS + MQ API example. [...]
December 30, 2011 at 1:01 am
Sijoy Thomas
In the above code I tried to make use of JNDI for ConnectionFactory but it is failing with
javax.naming.NameNotFoundException: Object MQQueueConnectionFactory not found on
queue manager SOURCE.QM
This is the code change I have made
Hashtable props = new Hashtable();
props.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,”com.ibm.mq.jms.context.WMQInitialContextFactory”);
props.put(javax.naming.Context.PROVIDER_URL,”SOURCE.QM”);
Context qmContext = new javax.naming.InitialContext(props);
//Context ctx = new InitialContext();
MQQueueConnectionFactory cf = (MQQueueConnectionFactory) qmContext.lookup(“MQQueueConnectionFactory”);