Sunday, October 25, 2015

Send messages to IBM WebSphere MQ from Unix server using Shell script and JAVA

A standalone shell script to send messages to MQ on an IBM WebSphere MQ server using JAVA program.

The application mostly helps in testing connectivity from Metasolv M6 server to IBM WebSphere connectivity in MQ event generators in WLI.

In order to build this utility please follow below steps.

STEP 1. 


Create a alok_tmp(choose any name) in any directory on your unix box and create src and bin folder and below files.

Folders created inside directory i.e. /opt/app/script are as below

1. alok_tmp
2. alok_tmp/src
3. alok_tmp/bin

Files created inside directory src and bin

1. alok_tmp/sendMQ.sh
2. alok_tmp/src/MQSendUtility.java
3. alok_tmp/bin/requestMessage.xml
4. alok_tmp/bin/mq.properties

Below should be directory structure.


Class file will automatically be created after each time sh file is run.

STEP 2. 


Copy below to Java file to send the messages to MQ on IBM WebSphere server. Code below is self explanatory.

File: MQSendUtility.java

/** 
* This class provides access to the MQSeries queue facilities.  Once 
*
* instantiated, the main application program need only call the 'send'
*
* method to put message on request queue. The send method returns an MQMessage. 
*
* reply queue is still kept in class as earlier it was also used to receive the reply.
*
* but now it is now utilised to send a MQ message only. 
*
* @author Alok Mishra
*
* @version 1.0
*/

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;
import com.ibm.mq.MQC;
import com.ibm.mq.MQEnvironment;
import com.ibm.mq.MQException;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager; // Include the MQ package

public class MQSendUtility {
private static Properties props = new Properties();
private MQQueueManager qMgr;
private MQQueue requestQueue;
private MQQueue replyQueue;
public String replyQueueName;
private int openOptions;
private MQMessage storedMessage;

@SuppressWarnings("unchecked")
public MQSendUtility(String hostname, String channel, String qManager,
String aRequestQueue, String aReplyQueue) throws MQException {

try {
MQEnvironment.hostname = hostname;
MQEnvironment.channel = channel;
MQEnvironment.port = Integer.valueOf(props
.getProperty("mq.listen.port"));
MQEnvironment.userID = props
.getProperty("mq.server.security.principal");
MQEnvironment.password = props
.getProperty("mq.server.security.credentials");
MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY,
MQC.TRANSPORT_MQSERIES);
try {
qMgr = new MQQueueManager(qManager);
} catch (MQException e) {
print("An MQException occurred trying to connect to the QManager.");
Object o = e.exceptionSource;
print("MQException originated from object '" + o.toString());
print("Completion code = " + e.completionCode);
System.exit(1);
}
print("Connected to QManager " + qManager);

replyQueueName = aReplyQueue;

if (aRequestQueue.equals(aReplyQueue)) {
print("Open Options from IF");
openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT;
} else {
print("Open Options from ELSE");
openOptions = MQC.MQOO_OUTPUT;
}
print("Open Options"+openOptions);
requestQueue = qMgr.accessQueue(aRequestQueue, openOptions, 
null, // default queue manager
null, // no dynamic q name
null); // no alternate user id

print("Got access to request queue "+requestQueue);

} catch (MQException ex) {
print("MQCommunicator.constructor - MQException occurred : Completion code "
+ ex.completionCode
+ "\n>MQStatus: Reason code "
+ ex.reasonCode + " mesage" + ex.getClass());
System.exit(1);
}

catch (Exception e) {
print("MQCommunicator.constructor - Exception occurred - "
+ e.toString());
System.exit(1);
}
}

public MQMessage send(String buffer) {

try {
MQMessage sendMessage = null;

try {
// Create new MQMessage object
sendMessage = new MQMessage();
} catch (NullPointerException e) {
print("Unable to create new MQMessage");
return null;
}
print("MQMessage created");

sendMessage.format = MQC.MQFMT_STRING;
sendMessage.messageType = MQC.MQMT_REQUEST;
sendMessage.replyToQueueName = replyQueueName;
sendMessage.writeString(buffer);
MQPutMessageOptions pmo = new MQPutMessageOptions();
try {
requestQueue.put(sendMessage, pmo);
} catch (NullPointerException e) {
print("Request Q is null - cannot put message");
return null;
}
print("Message placed on queue");
storedMessage = new MQMessage();
storedMessage.correlationId = sendMessage.messageId;
print("Message ID for sent message = "
+ sendMessage.messageId.toString());
print("Correlation ID stored = "
+ storedMessage.correlationId.toString());

return storedMessage;

} catch (MQException ex) {
print("MQCommunicator.send - MQException occurred : Completion code "
+ ex.completionCode + " Reason code " + ex.reasonCode);
return null;
} catch (java.io.IOException ex) {
print("MQCommunicator.send - IOException occurred: " + ex);
return null;
} catch (Exception ex) {
print("MQCommunicator.send - General Exception occurred: " + ex);
return null;
}
}

public void finalise() {
try {
// Closing the queues
requestQueue.close();

if (requestQueue != replyQueue)
replyQueue.close();

// Disconnect from the queue manager
qMgr.disconnect();

} catch (MQException ex) {
print("MQCommunicator.finalise - MQException occurred : Completion code "
+ ex.completionCode
+ ">MQStatus: Reason code "
+ ex.reasonCode);
}
}

public static void print(String msg) {
PrintWriter message = new PrintWriter(System.out, true);
message.println(">MQStatus: " + msg);
}

private static String getFileContent(String fileName) throws Exception {
File file = new File(fileName);
StringBuffer strBuffer = new StringBuffer();
try {
FileInputStream fileIn = new FileInputStream(file);
int lengthOfFile = (int) file.length();
byte[] outputByte = new byte[lengthOfFile];
// copy binary content to output stream
while (fileIn.read(outputByte) != -1) {
strBuffer.append(new String(outputByte));
}
fileIn.close();
} catch (Exception e) {
print("Exception FileInputStream" + e.getMessage());
e.printStackTrace();
throw e;
}
return strBuffer.toString();
}

public static void main(String args[]) throws Exception {


InputStream file = null;
String propertyFile = "mq.properties";
print("Load property File");
try {
file = MQSendUtility.class.getClassLoader().getResourceAsStream(
propertyFile);
props.load(file);
print("Loaded property File");
String filePath="requestMessage.xml";
String message = MQSendUtility.getFileContent(filePath);
String reqQueueName = props.getProperty("mq.request.queue");
String repQueueName = props.getProperty("mq.reply.queue");
String queueManager = props.getProperty("mq.queue.manager");
String channel = props.getProperty("mq.channel.name");
String qManagerUrl = props.getProperty("mq.provider.url");
print("Calling Constructor");
MQSendUtility util = new MQSendUtility(qManagerUrl, channel,
queueManager, reqQueueName, repQueueName);
MQMessage replyMsg = util.send(message);


} catch (IOException io) {
if (file == null)
print("No input file specified");
} catch (Exception e) {
print("Exception occured in main " + e.getMessage());
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

}

STEP 3. 


Copy below to shell script.

File: sendMQ.sh

#!/bin/ksh

#Execute Domain variables
. /opt/app/domains/my_domain/bin/setDomainEnv.sh

# Assuming domain variables don't include com.ibm.mq.jar so include it
CLASSPATH=$CLASSPATH:/opt/app/domains/my_domain/mq-jars/com.ibm.mq.jar
export CLASSPATH

cd /opt/app/script/alok_tmp
javac -d bin -sourcepath src src/MQSendUtility.java

cd /opt/app/script/alok_tmp/bin
java -Dbea.home=$BEA_HOME  MQSendUtility


STEP 4. 


Below is property file & request message file(XML).

File: mq.properties 

mq.provider.url=#IP Address of the IBM WebSphere MQ server i.e. 172.0.0.1
mq.channel.name=#Channel Name.This must be a valid channel on the IBM WebSphere MQ server.
mq.request.queue=# MQ Name where msg need to be put.This should be a valid queue for the specified queue manager.
mq.reply.queue=# reply queue name.This should be a valid queue for the specified queue manager.
mq.queue.manager=# This should be a valid queue manager on the IBM WebSphere MQ server i.e. qmgr123.
mq.listen.port=# Specifies the port of the IBM WebSphere MQ server.
mq.server.security.principal=#Specifies the username who has permission to use this channel.
mq.server.security.credentials=# Specifies the password for the given user.


File: requestMessage.xml

Hello, this is a test message being sent to MQ on IBM websphere server.

STEP 5. 


Now run sendMQ.sh and see output as below.




Hope above helps in testing Metasolv to WebSphere MQ connectivity by checking if M6 application server is able to send a message to MQ , please leave your feedback or query.