Mqqueuemanager Class

Mqqueuemanager Class

Mqqueuemanager Class

ת×Ô£ºhttp://hi.baidu.com/javashmily/blog/item/33a00f39fc860f23b9998f0c.html

MQQueueManager

java.lang.Object
   |
   *- com.ibm.mq.MQManagedObject
           |
           *- com.ibm.mq.MQQueueManager

public class MQQueueManager
extends MQManagedObject. (See topic "MQManagedObject".)

Note: The behavior of some of the options available in this class depends on the environment in which they are used. These elements are marked with a *. See Chapter 8, Environment-dependent behavior for details.

Variables

isConnected public boolean isConnected

True if the connection to the queue manager is still open.

Constructors

MQQueueManager public MQQueueManager(String queueManagerName)

Throws MQException.

Create a connection to the named queue manager.

Note: When using WebSphere MQ classes for Java, the hostname, channel name and port to use during the connection request are specified in the MQEnvironment class. This must be done before calling this constructor.

The following example shows a connection to a queue manager MYQM, running on a machine with hostname fred.mq.com.

MQEnvironment.hostname = "fred.mq.com"; // host to connect to MQEnvironment.port = 1414; // port to connect to. // If I don't set this, // it defaults to 1414 // (the default WebSphere MQ port) MQEnvironment.channel = "channel.name"; // the CASE-SENSITIVE // name of the // SVR CONN channel on // the queue manager MQQueueManager qMgr = new MQQueueManager("MYQM");

If the queue manager name is left blank (null or ""), a connection is made to the default queue manager.

See also MQEnvironment.

MQQueueManager public MQQueueManager(String queueManagerName, MQConnectionManager cxManager)

Throws MQException.

This constructor connects to the specified Queue Manager, using the properties in MQEnvironment. The specified MQConnectionManager manages the connection.

MQQueueManager public MQQueueManager(String queueManagerName, ConnectionManager cxManager)

Throws MQException.

This constructor connects to the specified Queue Manager, using the properties in MQEnvironment. The specified ConnectionManager manages the connection.

This constructor requires a JVM at at least Java 2 v1.3, with at least JAAS 1.0 installed.

MQQueueManager public MQQueueManager(String queueManagerName, int options)

Throws MQException.

This version of the constructor is intended for use only in bindings mode and it uses the extended connection API (MQCONNX) to connect to the queue manager. The options parameter allows you to choose fast or normal bindings. Possible values are:

  • MQC.MQCNO_FASTPATH_BINDING for fast bindings *.
  • MQC.MQCNO_STANDARD_BINDING for normal bindings.

MQQueueManager public MQQueueManager(String queueManagerName, int options, MQConnectionManager cxManager)

Throws MQException.

This constructor performs an MQCONNX, passing the supplied options. The specified MQConnectionManager manages the connection.

MQQueueManager public MQQueueManager(String queueManagerName, int options, ConnectionManager cxManager)

Throws MQException.

This constructor performs an MQCONNX, passing the supplied options. The specified ConnectionManager manages the connection.

This constructor requires a JVM at at least Java 2 v1.3, with at least JAAS 1.0 installed.

MQQueueManager public MQQueueManager(String queueManagerName, java.util.Hashtable properties)

The properties parameter takes a series of key/value pairs that describe the WebSphere MQ environment for this particular queue manager. These properties, where specified, override the values set by the MQEnvironment class, and allow the individual properties to be set on a queue manager by queue manager basis. See MQEnvironment.properties.

MQQueueManager public MQQueueManager(String queueManagerName, Hashtable properties, MQConnectionManager cxManager)

Throws MQException.

This constructor connects to the named Queue Manager, using the supplied Hashtable of properties to override those in MQEnvironment. The specified MQConnectionManager manages the connection.

MQQueueManager public MQQueueManager(String queueManagerName, Hashtable properties, ConnectionManager cxManager)

Throws MQException.

This constructor connects to the named Queue Manager, using the supplied Hashtable of properties to override those in MQEnvironment. The specified ConnectionManager manages the connection.

This constructor requires a JVM at at least Java 2 v1.3, with at least JAAS 1.0 installed.

Methods

accessDistributionList public synchronized MQDistributionList accessDistributionList ( MQDistributionListItem[] litems, int openOptions, String alternateUserId )

Throws MQException.

Parameters

litems The items to be included in the distribution list.

openOptions Options that control the opening of the distribution list.

alternateUserId If MQOO_ALTERNATE_USER_AUTHORITY is specified in the openOptions parameter, this parameter specifies the alternate user identifier that is used to check the authorization for the open. If MQOO_ALTERNATE_USER_AUTHORITY is not specified, this parameter can be left blank (or null).

Returns A newly created MQDistributionList which is open and ready for put operations.

Throws MQException if the open fails.

See also MQQueueManager.accessQueue.

accessDistributionList This is a simplified version of the AccessDistributionList method previously described. public synchronized MQDistributionList accessDistributionList ( MQDistributionListItem[] litems, int openOptions, )

Parameters

litems The items to be included in the distribution list.

openOptions Options that control the opening of the distribution list.

See accessDistributionList for details of the parameters.

alternateUserId is set to "".

accessProcess public synchronized MQProcess accessProcess ( String processName, int openOptions, String queueManagerName, String alternateUserId )

Throws MQException.

Establishes access to a WebSphere MQ process on this queue manager to inquire about the process attributes.

Parameters

processName Name of process to open.

openOptions Options that control the opening of the process. Inquire is automatically added to the options specified, so there is no need to specify it explicitly.

Valid options are:

MQC.MQOO_ALTERNATE_USER_AUTHORITY Validate with the specified user id

MQC.MQOO_FAIL_IF_QUIESCING Fail if the queue manager is quiescing

If more than one option is required, the values can be added together or combined using the bitwise OR operator. See the WebSphere MQ Application Programming Reference for a fuller description of these options.

queueManagerName Name of the queue manager on which the process is defined. Applications should leave this parameter blank or null.

alternateUserId If MQOO_ALTERNATE_USER_AUTHORITY is specified in the openOptions parameter, this parameter specifies the alternate user identifier that is used to check the authorization for the open. If MQOO_ALTERNATE_USER_AUTHORITY is not specified, this parameter can be left blank (or null).

accessProcess This is a simplified version of the AccessProcess method previously described. public synchronized MQProcess accessProcess ( String processName, int openOptions )

Parameters

processName The name of the process to open.

openOptions Options that control the opening of the process.

See accessProcess for details of the options.

queueManagerName and alternateUserId are set to "".

accessQueue public synchronized MQQueue accessQueue ( String queueName, int openOptions, String queueManagerName, String dynamicQueueName, String alternateUserId )

Throws MQException.

Establishes access to a WebSphere MQ queue on this queue manager to get or browse messages, put messages, inquire about the attributes of the queue or set the attributes of the queue.

If the queue named is a model queue, then a dynamic local queue is created. The name of the created queue can be determined by inspecting the name attribute of the returned MQQueue object.

Parameters

queueName Name of queue to open.

openOptions Options that control the opening of the queue. Valid options are:

MQC.MQOO_ALTERNATE_USER_AUTHORITY Validate with the specified user identifier.

MQC.MQOO_BIND_AS_QDEF Use default binding for queue.

MQC.MQOO_BIND_NOT_FIXED Do not bind to a specific destination.

MQC.MQOO_BIND_ON_OPEN Bind handle to destination when queue is opened.

MQC.MQOO_BROWSE Open to browse message.

MQC.MQOO_FAIL_IF_QUIESCING Fail if the queue manager is quiescing.

MQC.MQOO_INPUT_AS_Q_DEF Open to get messages using queue-defined default.

MQC.MQOO_INPUT_SHARED Open to get messages with shared access.

MQC.MQOO_INPUT_EXCLUSIVE Open to get messages with exclusive access.

MQC.MQOO_INQUIRE Open for inquiry - required if you wish to query properties.

MQC.MQOO_OUTPUT Open to put messages.

MQC.MQOO_PASS_ALL_CONTEXT Allow all context to be passed.

MQC.MQOO_PASS_IDENTITY_CONTEXT Allow identity context to be passed.

MQC.MQOO_SAVE_ALL_CONTEXT Save context when message retrieved*.

MQC.MQOO_SET Open to set attributes.

MQC.MQOO_SET_ALL_CONTEXT Allows all context to be set.

MQC.MQOO_SET_IDENTITY_CONTEXT Allows identity context to be set.

If more than one option is required, the values can be added together or combined using the bitwise OR operator. See WebSphere MQ Application Programming Reference for a fuller description of these options.

queueManagerName Name of the queue manager on which the queue is defined. A name which is entirely blank, or which is null, denotes the queue manager to which this MQQueueManager object is connected.

dynamicQueueName This parameter is ignored unless queueName specifies the name of a model queue. If it does, this parameter specifies the name of the dynamic queue to be created. A blank or null name is not valid if queueName specifies the name of a model queue. If the last non-blank character in the name is an asterisk (*), the queue manager replaces the asterisk with a string of characters that guarantees that the name generated for the queue is unique on this queue manager.

alternateUserId If MQOO_ALTERNATE_USER_AUTHORITY is specified in the openOptions parameter, this parameter specifies the alternate user identifier that is used to check the authorization for the open. If MQOO_ALTERNATE_USER_AUTHORITY is not specified, this parameter can be left blank (or null).

Returns MQQueue that has been successfully opened.

Throws MQException if the open fails.

accessQueue public synchronized MQQueue accessQueue ( String queueName, int openOptions )

Throws MQException if you call this method after disconnecting from the queue manager.

Parameters

queueName Name of queue to open

openOptions Options that control the opening of the queue

See MQQueueManager.accessQueue for details of the parameters.

For this version of the method, queueManagerName, dynamicQueueName, and alternateUserId are set to "".

Returns MQProcess that has been successfully opened.

Throws MQException if the open fails.

See also MQQueueManager.accessQueue.

backout public synchronized void backout()

Throws MQException.

Calling this method indicates to the queue manager that all the message gets and puts that have occurred since the last syncpoint are to be backed out. Messages put as part of a unit of work (with the MQC.MQPMO_SYNCPOINT flag set in the options field of MQPutMessageOptions) are deleted; messages retrieved as part of a unit of work (with the MQC.MQGMO_SYNCPOINT flag set in the options field of MQGetMessageOptions) are reinstated on the queue.

See also the description of the "commit" method.

begin* (bindings connection only) public synchronized void begin()

Throws MQException.

This method is supported only by the WebSphere MQ classes for Java in bindings mode and it signals to the queue manager that a new unit of work is starting.

Do not use this method for applications that use local one-phase transactions.

commit public synchronized void commit()

Throws MQException.

Calling this method indicates to the queue manager that the application has reached a syncpoint, and that all of the message gets and puts that have occurred since the last syncpoint are to be made permanent. Messages put as part of a unit of work (with the MQC.MQPMO_SYNCPOINT flag set in the options field of MQPutMessageOptions) are made available to other applications. Messages retrieved as part of a unit of work (with the MQC.MQGMO_SYNCPOINT flag set in the options field of MQGetMessageOptions) are deleted.

See also the description of the "backout" method.

disconnect public synchronized void disconnect()

Throws MQException.

Terminates the connection to the queue manager. All open queues and processes accessed by this queue manager are closed, and hence become unusable. When you have disconnected from a queue manager the only way to reconnect is to create a new MQQueueManager object.

Normally, any work performed as part of a unit of work is committed. However, if this connection is managed by a ConnectionManager, rather than an MQConnectionManager, the unit of work might be rolled back.

getCharacterSet public int getCharacterSet()

Throws MQException.

Returns the CCSID (Coded Character Set Identifier) of the queue manager's codeset. This defines the character set used by the queue manager for all character string fields in the application programming interface.

Throws MQException if you call this method after disconnecting from the queue manager.

getCommandInputQueueName public String getCommandInputQueueName()

Throws MQException.

Returns the name of the command input queue defined on the queue manager. This is a queue to which applications can send commands, if authorized to do so.

Throws MQException if you call this method after disconnecting from the queue manager.

getCommandLevel public int getCommandLevel()

Throws MQException.

Indicates the level of system control commands supported by the queue manager. The set of system control commands that correspond to a particular command level varies according to the architecture of the platform on which the queue manager is running. See the WebSphere MQ documentation for your platform for further details.

Throws MQException if you call this method after disconnecting from the queue manager.

Returns One of the MQC.MQCMDL_LEVEL_xxx constants

getDistributionListCapable public boolean getDistributionListCapable()

Indicates whether the queue manager supports distribution lists.

getJDBCConnection public java.sql.Connection getJDBCConnection(XADataSource dataSource, String userid, String password) throws MQException, SQLException, Exception

Returns a Connection object for use with the JTA-JDBC support.

This method declares Exception in its throws clause so as to avoid problems with the JVM verifier for customers who are not using the JTA functionality. The actual exception thrown is javax.transaction.xa.XAException which would require the jta.jar file to be added to the classpath for programs which didn't previously require it.

Parameters

dataSource A database-specific implementation of the XADataSource interface which defines the details of the database to connect to. See the documentation for your database to determine how to create an appropriate XADataSource object to pass into getJDBCConnection.

userid The userid to use for this connection to the database. This is passed to the underlying XADataSource.getXAConnection method.

password The password to use for this connection to the database. This is passed to the underlying XADataSource.getXAConnection method.

getJDBCConnection public java.sql.Connection getJDBCConnection(javax.sql.XADataSource xads) throws MQException, SQLException, Exception

Returns a Connection object for use with the JTA-JDBC support.

This method declares Exception in its throws clause so as to avoid problems with the JVM verifier for customers who are not using the JTA functionality. The actual exception thrown is javax.transaction.xa.XAException which would require the jta.jar file to be added to the classpath for programs which didn't previously require it.

Parameters

xads A database-specific implementation of the XADataSource interface which defines the details of the database to connect to. See the documentation for your database to determine how to create an appropriate XADataSource object to pass into getJDBCConnection.

getMaximumMessageLength public int getMaximumMessageLength()

Throws MQException.

Returns the maximum length of a message (in bytes) that can be handled by the queue manager. No queue can be defined with a maximum message length greater than this.

Throws MQException if you call this method after disconnecting from the queue manager.

getMaximumPriority public int getMaximumPriority()

Throws MQException.

Returns the maximum message priority supported by the queue manager. Priorities range from zero (lowest) to this value.

Throws MQException if you call this method after disconnecting from the queue manager.

getSyncpointAvailability public int getSyncpointAvailability()

Throws MQException.

Indicates whether the queue manager supports units of work and syncpointing with the MQQueue.get and MQQueue.put methods.

Returns

  • MQC.MQSP_AVAILABLE if syncpointing is available.
  • MQC.MQSP_NOT_AVAILABLE if syncpointing is not available.

Throws MQException if you call this method after disconnecting from the queue manager.

isConnected public boolean isConnected()

Returns the value of the isConnected variable.

put public synchronized void put(String qName, String qmName, MQMessage msg, MQPutMessageOptions pmo, String altUserId) throws MQException

Places a single message onto a queue without having to create a MQQueue object first.

The qName (queue name) and qmName (queue manager name) parameters identify where the message is placed. If the queue is a model queue then an MQException is thrown.

In other respects, this method behaves like the put method on the MQQueue object. It is an implementation of the MQPUT1 MQI call. See MQQueue.put.

Parameters

qName The name of the queue onto which the message should be placed.

qmName The name of the queue manager on which the queue is defined.

msg The message to send.

pmo Options controlling the actions of the put. See MQPutMessageOptions for more details.

altUserid Specifies an alternative user identifier used to check authorization when placing the message on a queue.

put public synchronized void put(String qName, String qmName, MQMessage msg, MQPutMessageOptions pmo) throws MQException

Places a single message onto a queue without having to create a MQQueue object first.

This version of the method allows you to omit the altUserid parameter. See the fully-specified method (MQQueueManager.put) for details of the parameters.

put public synchronized void put(String qName, String qmName, MQMessage msg) throws MQException

Places a single message onto a queue without having to create a MQQueue object first.

This version of the method allows you to omit the put message options (pmo) and altUserid parameters. See the fully-specified method (MQQueueManager.put) for details of the parameters.

put public synchronized void put(String qName, MQMessage msg, MQPutMessageOptions pmo) throws MQException

Places a single message onto a queue without having to create a MQQueue object first.

This version of the method allows you to omit the qmName and altUserid parameters. See the fully-specified method (MQQueueManager.put) for details of the parameters.

put public synchronized void put(String qName, MQMessage msg) throws MQException

Places a single message onto a queue without having to create a MQQueue object first.

This version of the method allows you to omit the qmName, put message options (pmo), and altUserid parameters. See the fully-specified method (MQQueueManager.put) for details of the parameters.

/**
* This class handles the interaction with the com.ibm.mq classes
* to provide a connection to the MQ system.
* It support multiple backend systems by transactionID, see MQ Session Bean specification.
**/
import com.ibm.mq.*;
import java.io.*;
import java.util.*;

public class MQConnection {
private String _qManager;
private int _maxLength;
private int _maxMessage;
private int _expiry;
private String _outBoundQueue;
private String _inBoundQueue;
private String _waitInterval;
//private String _backEndId;
private static int count = 0;

// The indicator that a message is finished.
private static final String _endSignal = "&EOFR";
private int _MQSeriesMaxLength;
// Set flag for debugging purpose.
// private static boolean _debug = BackEndObjectFactory.getDebugFlag();
//jz set debug for each call
private boolean _debug = false;
// For trigger purpose.
protected byte[] corrID = null;
/**
* MQConnections constructor comment.
* Get customized configuration from TransactionFileManager class.
*/
public MQConnection(String id) throws MQBrokerException{
super();
BackEndObject be =BackEndObjectFactory.getBackEndObject(id);
if(be == null){
throw new MQBrokerException("Fail finding configuration for "+id + " Current config:"+BackEndObjectFactory.getBackEndHashTable());
}
//this._backEndId =id;
this._inBoundQueue =be.getInBoundQ();
this._outBoundQueue =be.getOutBoundQ();
this._waitInterval =be.getWaitInterval();
this._maxMessage =be.getMaxMessage();
this._maxLength =be.getMaxLength();
this._expiry =be.getExpiry();
this._MQSeriesMaxLength =be.getMQSeriesMaxLength();
this._qManager =be.getQManager();
/*
MQEnvironment.hostname = be.getHostName();
MQEnvironment.channel = be.getChannel();
MQEnvironment.port = be.getPortNumber();
MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY,MQC.TRANSPORT_MQSERIES);

//select binding or clients based on the value of hostname.
MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY,MQC.TRANSPORT_MQSERIES);*/
}
/**
* Handles creation of the MQQueueManager class object in the com.ibm.mq package.
* Implement in future with connection pooling.
* Return a MQQueueManager
*/
protected MQQueueManager connect()throws MQBrokerException{
MQQueueManager _qMgr;
try{
_qMgr = new MQQueueManager(_qManager);
}catch (MQException ex) {
throw new MQBrokerException("MQ Error occured in connect(), ex: " + ex);
} return _qMgr;
}
/**
* Disconnects from Queue Manager to free up the resource.
* If not connected it does nothing.
* Return void
*/
protected void disconnect(MQQueueManager qMgr) throws MQBrokerException{
try{
if (qMgr.isConnected()){
qMgr.disconnect();
}
}catch (MQException ex) {
throw new MQBrokerException("MQ Error occured in disconnect(), ex: " + ex );
}
}

/**
* retrieve one message from a queue.
* To seperate this with receiveMessage method in order to handle multiple messages.
* when backend has size limit, if the message parse in is over that limit,
* the message will be break up, and the application will do multiple get
*/
private String getMessageFromQ(MQMessage qMessage,MQQueue queueName, MQGetMessageOptions gmo)
throws MQBrokerException{
String reply=null;
try{
// get the reply message, 4M is the size limit for MQ. No need to change this.
//if (_debug) { System.out.println("$ " +this.toString() + " $$$$$$$$$$$$==> MQConnection.getMessageFromQ --> starts ");}
queueName.get(qMessage,gmo,_MQSeriesMaxLength);
// queueName.get(qMessage,gmo);
//if (_debug) { System.out.println("$ " +this.toString() + " $$$$$$$$$$$$==> MQConnection.getMessageFromQ --> before reading the reply ");}
// return the reply message in String format
if (qMessage.messageType==4) {
throw new MQBrokerException("received MQ exception report - feedback: " + qMessage.feedback);
}
reply = qMessage.readString(qMessage.getMessageLength());
//if (_debug) { System.out.println("$ " +this.toString() + " $$$$$$$$$$$$==> MQConnection.getMessageFromQ --> after the reply is read");}
}catch(IOException ex){
System.out.println("IOException in MQConnection.getMessageFromQ --> ex= " + ex.getMessage());
throw new MQBrokerException("Fail in qMessage.writeString(message).");
}catch(MQException ex){
if(ex != null && ex.getMessage() != null){
System.out.println("MQException in MQConnection.getMessageFromQ --> ex=" + ex.getMessage());
throw new MQBrokerException("MQException in MQConnection.getMessageFromQ --> ex=" + ex.getMessage());
}else{
System.out.println("MQException in MQConnection.getMessageFromQ --> message is null");
throw new MQBrokerException("MQException in MQConnection.getMessageFromQ --> message is null");
}
}return reply;

}
/**
* Return an instance of a message.
* Creation date: (1/31/01 11:46:42 AM)
*/
private MQMessage getMessageInstance(byte[] correlationId){
// if (_debug) { System.out.println("getMessageInstance() _userid = " + _userid);}
MQMessage qMessage = new MQMessage();
if(correlationId!=null){
qMessage.correlationId = correlationId;
qMessage.messageId = correlationId;
} else {
qMessage.correlationId = MQC.MQCI_NONE;
qMessage.messageId = MQC.MQMI_NONE;
}
qMessage.format = MQC.MQFMT_STRING;
qMessage.messageType = MQC.MQMT_REQUEST;
qMessage.characterSet = 850;
qMessage.replyToQueueName = _outBoundQueue;
qMessage.expiry = _expiry;
qMessage.replyToQueueManagerName = _qManager;
qMessage.userId = _userid;
qMessage.report = MQC.MQRO_EXCEPTION_WITH_FULL_DATA + MQC.MQRO_DISCARD_MSG;
return qMessage;
}
/**
* Public method that get called.
* Establishs connection---send messages--reveive messages--disconnect.
*/

public String getReply(String message, String backEndID) throws MQBrokerException {
String replyMessage = "";
StringBuffer myReplyFromMQSeries = new StringBuffer();
MQQueueManager qMgr = null;
long start = System.currentTimeMillis();
boolean gotConnection = false;

_debug = BackEndObjectFactory.getDebugFlagbyUserid(_userid);

try {
qMgr = ConnectionFactory.getConnection(backEndID, _userid);

gotConnection = true;

byte[] correlationId = sendMessage(message, qMgr, null);
if (_debug) { System.out.println(" " +this.toString() + " MQConnection.getReply--> Message sent");}

replyMessage = receiveMessage(correlationId, qMgr);
if (_debug) { System.out.println(" " +this.toString() + " MQConnection.getReply--> Message received");}


} catch (MQBrokerException e) {
System.out.println("MQConnection.getReply--> MQBrokerException e = " + e.getMessage() + ", and the class ex = " + e.getClass());
disconnect(qMgr);
throw new MQBrokerException(e.toString());
} catch (ConnectionTimeOutException ex) {
System.out.println("MQConnection.getReply--> ConnectionTimeOutException ex = " + ex.getMessage() + ", and the class ex = " + ex.getClass());
throw new MQBrokerException(ex.toString());
} catch (Exception ex) {
System.out.println("MQConnection.getReply--> Exception ex = " + ex.getMessage() + ", and the class ex = " + ex.getClass());
throw new MQBrokerException(ex.toString());
} finally {
if (gotConnection) {
try {
ConnectionFactory.returnConnection(qMgr, backEndID, _userid);
} catch (Exception ex) {
System.out.println("MQConnection.getReply (final) --> Exception ex = " + ex.getMessage() + ", and the class ex = " + ex.getClass());
}
}
}
return replyMessage;
}





/**
* the same correlationId as the included argument.
* Open Queue---retrieve one or multiple messages-----close Queue.
*/
protected String receiveMessage(byte [] correlationId, MQQueueManager qMgr) throws MQBrokerException{

String replyMessage = null;
MQQueue reply_queue = null;
try{
if (_debug) { System.out.println("* " +this.toString() + " *=> MQConnection.receiveMessage --> start, correlationId=" + correlationId);}

int openOptions = MQC.MQOO_INPUT_SHARED |MQC.MQOO_INQUIRE |MQC.MQOO_FAIL_IF_QUIESCING;

reply_queue = qMgr.accessQueue(_outBoundQueue,openOptions,null,null,null);
if (_debug) { System.out.println("* " +this.toString() + " *=> MQConnection.receiveMessage --> queue " + reply_queue.name.trim() + " opened");}

MQGetMessageOptions gmo = new MQGetMessageOptions();
gmo.options = (MQC.MQGMO_ACCEPT_TRUNCATED_MSG + MQC.MQGMO_WAIT + MQC.MQGMO_FAIL_IF_QUIESCING);
gmo.matchOptions = (MQC.MQMO_MATCH_CORREL_ID);
gmo.waitInterval= Integer.parseInt(_waitInterval);

MQMessage qMessage = getMessageInstance(correlationId);

replyMessage = getMessageFromQ(qMessage,reply_queue,gmo);
if (_debug) { System.out.println("* " +this.toString() + " *=> MQConnection.receiveMessage --> end:" + replyMessage);}

}catch(MQException ex2) {
if(ex2 != null && ex2.getMessage() != null){
System.out.println("MQConnection.receiveMessage --> MQException: " + ex2.getMessage());
throw new MQBrokerException( "Error occured in receiveMessage()"+ex2.getMessage());
}else{
System.out.println("MQConnection.receiveMessage --> MQException: null exception");
throw new MQBrokerException( "Error occured in receiveMessage(). The exception thrown is NULL!!!");
}
}catch(Exception e){
System.out.println("MQConnection.receiveMessage --> Exception block e = " + e.getClass() + " error: " + e.getMessage()+ " qMgr.isConnected="+qMgr.isConnected());
throw new MQBrokerException( "Error occured in receiveMessage()." + e.getMessage());
}finally{
try { qMgr.commit();
} catch (MQException ex) {
System.out.println("MQConnection.receiveMessage (final) --> MQException at commit:" +ex.getMessage()); }
if(reply_queue != null && reply_queue.isOpen()){
try{
reply_queue.close();
if (_debug) { System.out.println("* " +this.toString() + " *=> MQConnection.receiveMessage --> queue " + reply_queue.name.trim() + " closed");}
}catch(MQException ex){
System.out.println("MQConnection.receiveMessage (final) --> MQException at close:" +ex.getMessage()); }
}
}
return replyMessage;
}

/**
* Handle one or multiple messages.
* Open Queue---send one or multiple messages---close queue.
* @return byte [] correlationId
* The corrlation ID in send message here is just for trigger process use.
* Front end application just parse in null as corrID when they sent message.
*/

protected byte[] sendMessage(String message,MQQueueManager qMgr,byte[] corrID) throws MQBrokerException{

byte[] correlationId = null;
MQQueue local_queue = null;
MQMessage qMessage = null;

try{
if (_debug) { System.out.println("* " +this.toString() + " *=> MQConnection.sendMessage --> " + message);}

int openOptions = MQC.MQOO_OUTPUT+MQC.MQOO_SET_IDENTITY_CONTEXT;

local_queue = qMgr.accessQueue(_inBoundQueue,openOptions,null,null,null);
if (_debug) { System.out.println("* " +this.toString() + " *=> MQConnection.sendMessage --> queue " + local_queue.name.trim() + " opened");}

MQPutMessageOptions pmo = new MQPutMessageOptions();

pmo.options = (MQC.MQPMO_SET_IDENTITY_CONTEXT + MQC.MQPMO_FAIL_IF_QUIESCING);

qMessage = getMessageInstance(null);

qMessage = putMessageToQ(message,qMessage,local_queue,pmo);
correlationId = qMessage.messageId;

if (_debug) { System.out.println("* " +this.toString() + " *=> MQConnection.sendMessage --> end, correlationId=" + correlationId);}
}catch (MQException ex2) {
if(ex2 != null && ex2.getMessage() != null){
System.out.println("MQConnection.sendMessage --> MQException ex2 = " + ex2.getMessage());
throw new MQBrokerException("MQ Error occured in sendMessage(), ex: " + ex2.getMessage());
}else{
System.out.println("MQConnection.sendMessage --> MQException ex2 is null ");
throw new MQBrokerException("MQ Error occured in sendMessage(), ex: is null!!!" );
}
}catch(Exception e){
System.out.println("MQConnection.sendMessage --> Exception block e = " + e.getClass() +" error: " + e.getMessage());
throw new MQBrokerException( "Error occured in sendMessage()." + e.getMessage());
}finally{
if(local_queue != null && local_queue.isOpen()){
try{
local_queue.close();
if (_debug) { System.out.println("* " +this.toString() + " *=> MQConnection.sendMessage --> queue " + local_queue.name.trim() + " closed");}
}catch(MQException ex){
if(ex != null && ex.getMessage() != null){
System.out.println("MQConnection.sendMessage (final) --> MQException ex = " + ex.getMessage());
}else{
System.out.println("MQConnection.sendMessage (final) --> MQException ex is null ");
}
}catch(Exception ex){
System.out.println("MQConnection.sendMessage (final) --> Exception ex = " + ex.getMessage());
}
}
}

return correlationId;
}


private static boolean _printFlag = BackEndObjectFactory.getPrintFlag();
private String _userid = "";

/**
* Public method that get called.
* Establishs connection---send messages--reveive messages--disconnect.
*/
public String getReply(String message, String backEndID, String userid) throws MQBrokerException {
_userid = userid;
return getReply(message, backEndID);
}

/**
* put one message into queue.
* The reason to seperate this is to handle multiple messages.
* When the message size over the limit of _maxLength, multiple message will be sent
* in stead of one. This method will be called several times in this case.

*/
private MQMessage putMessageToQ(String message,MQMessage qMessage,MQQueue queueName, MQPutMessageOptions pmo)
throws MQBrokerException{
try{
qMessage.clearMessage();
qMessage.writeString(message);
// if (_debug) { System.out.println("putMessageToQ() qMessage.userId = " + qMessage.userId);}
queueName.put(qMessage,pmo);
return qMessage;
}catch(IOException ex){
throw new MQBrokerException("IOException in putMessageToQ. ex=" + ex.getMessage());
}catch(MQException ex){
throw new MQBrokerException("MQException in putMessageToQ. ex=" + ex.getMessage());
}

}
}
-------------------
Caller for the above:
String system = ControlFile.getSystemByTxnId(txn.trim());
if (system == null) {
throw new MQConnectException("Invalid System Specified!",(new Exception()));}
MQConnection mq = null;
try {
mq = new MQConnection(system);
replyString = mq.getReply(str,system,userid);
return replyString;

}
================================
package mq;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;

import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import com.ibm.jms.JMSBytesMessage;
import com.ibm.jms.JMSMessage;
import com.ibm.jms.JMSTextMessage;
import com.ibm.mq.MQC;
import com.ibm.mq.MQEnvironment;
import com.ibm.mq.MQException;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import com.ibm.mq.jms.JMSC;
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;

/*
need:
----------------
com.ibm.mq.jar
com.ibm.mq.jmqi.jar
com.ibm.msg.client.jms.internal.jar
com.ibm.msg.client.jms.jar
com.ibm.msg.client.provider.jar

From C:\Program Files\IBM\SDP\runtimes\base_v7\installedConnectors\wmq.jmsra.rar
*/
@SuppressWarnings( { "deprecation", "unchecked" })
public class MQJavaHybrid {

private String hostname;// = "localhost";
private String queueInName;//
private String queueOutName;//
private String channel;// = "SYSTEM.DEF.SVRCONN";
private int port;// // default: 1414
private int readWait;
private String QManagerName;// = "QM2";
private String userId;

public MQJavaHybrid() {
init();
}

private void init() {
/*
* mqj.properties:
hostname=localhost
port=1412

# local queue manager (assumption: same for request / response)
QManagerName=QM2

#(assumption: same for request / response)
channel=SYSTEM.DEF.SVRCONN

#e.g. reply queue - where the message be placed by remote QM
QueueInName=Q_IN

# send (remote) queue
QueueOutName=Q_OUT

readWait=5000

# for client mode:
userId=Gopher
*/
ResourceBundle bundle = ResourceBundle.getBundle("mqj");
hostname = bundle.getString("hostname");
queueInName = bundle.getString("QueueInName");
queueOutName = bundle.getString("QueueOutName");
channel = bundle.getString("channel");
QManagerName = bundle.getString("QManagerName");
port = Integer.parseInt(bundle.getString("port"));
userId = bundle.getString("userId");
readWait = Integer.parseInt(bundle.getString("readWait"));

}

public void testSendUsingNonJMSJavaMQAPI(final String messageText) {
MQQueue queueOut = null;
MQQueueManager MQQM = null;
try {

MQEnvironment.hostname = hostname;
MQEnvironment.channel = channel;
MQEnvironment.port = port; // default: 1414
MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES);

// Connect to the QM's listener
MQQM = new MQQueueManager(QManagerName);

// Read | Write access
int queueAccessOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT;

// For client mode ?:
//int openOptions = MQC.MQOO_OUTPUT+MQC.MQOO_SET_IDENTITY_CONTEXT;
queueOut = MQQM.accessQueue(queueOutName, queueAccessOptions);


// Construct message. UTF for XML
MQMessage mqMessageOut = getMessageInstance();
// setMessage()
mqMessageOut.writeUTF(messageText);

// Using MQPMO_DEFAULT
MQPutMessageOptions pmo = new MQPutMessageOptions();

// client mode ?
//pmo.options = (MQC.MQPMO_SET_IDENTITY_CONTEXT + MQC.MQPMO_FAIL_IF_QUIESCING);

// !!!!!!!!!!!!!!!!!!!!!
queueOut.put(mqMessageOut, pmo);
// !!!!!!!!!!!!!!!!!!!!!
System.out.println("Message placed on the outbound queue.");
}

catch (MQException ex) {
System.out.println("Nothing doing: MQ error. Completion code " + ex.completionCode + " Reason code "
+ ex.reasonCode);
} catch (Exception ex) {
System.out.println("Ouch, another bummer: " + ex);
} finally {
// Close the queues
try {
queueOut.close();
} catch (MQException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Disconnect from the queue manager
try {
MQQM.disconnect();
} catch (MQException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

/**
* Construct an MQ message with the replyTo header
* @return
*/
private MQMessage getMessageInstance() {
final int expiryCode = 0; // message never expires on the receiving end - will need to purge
MQMessage mqMessageOut = new MQMessage();

//mqMessageOut.format = MQC.MQFMT_STRING;
//mqMessageOut.messageType = MQC.MQMT_REQUEST;
//mqMessageOut.characterSet = 850;
//mqMessageOut.replyToQueueName = queueInName;
//mqMessageOut.expiry = expiryCode;
//mqMessageOut.replyToQueueManagerName = QManagerName;
//mqMessageOut.userId = userId;
//mqMessageOut.report = MQC.MQRO_EXCEPTION_WITH_FULL_DATA + MQC.MQRO_DISCARD_MSG;
return mqMessageOut;
}

private void delayGettingAMessage() throws Exception{
System.out.println("About to start waiting for " + (readWait/1000) + " secs.");
Thread.currentThread().sleep(readWait);
}
public void readUsingJMS() {
try {

// Wait for mainframe to reply
delayGettingAMessage();
// ----------------------- Good to go -----------------------

MQQueueConnectionFactory cf = new MQQueueConnectionFactory();
int transportType = JMSC.MQJMS_CLIENT_NONJMS_MQ;
// JMSC.MQJMS_TP_CLIENT_MQ_TCPIP;
// JMSC.MQJMS_CLIENT_JMS_COMPLIANT;

cf.setHostName(hostname);
cf.setPort(port);
cf.setTransportType(transportType);
cf.setQueueManager(QManagerName);
cf.setChannel(channel);
// ?? cf.setClientID(userId);
cf.setUseConnectionPooling(true);

MQQueueConnection connection = (MQQueueConnection) cf.createQueueConnection();
MQQueueSession session = (MQQueueSession) connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

// Here need change to (queueInName) - replyTo queue to pick up the messages
com.ibm.mq.jms.MQQueue queue = (com.ibm.mq.jms.MQQueue) session.createQueue(queueOutName); //(queueInName);
System.out.println("About to read from queue " + queue.getBaseQueueName());
MQQueueReceiver receiver = (MQQueueReceiver) session.createReceiver(queue);

// Start the connection to QM
connection.start();

Message message = receiver.receive(readWait);

//if (message instanceof com.ibm.jms.JMSBytesMessage) {
if (message instanceof javax.jms.BytesMessage) {
// JMSBytesMessage receivedMessage = (JMSBytesMessage) message;
// int length = (int) receivedMessage.getBodyLength();
// byte[] messageBody = new byte[length];
// receivedMessage.readBytes(messageBody);
// System.out.println("Received Byte message:\n" + (new String(messageBody)));
BytesMessage receivedMessage = (BytesMessage) message;
String messageText = receivedMessage.readUTF();
System.out.println("Received ByteMessage: \n" + messageText);
// } else if (message instanceof com.ibm.jms.JMSMessage) {
} else if (message instanceof javax.jms.TextMessage) {

System.out.println("Received Text message:\n" + ((TextMessage) message).getText());
} else if (message == null) {
System.out.println("No messages on queue ............. " + queue.getBaseQueueName());
}

receiver.close();
session.close();
connection.close();

System.out.println("Done.....");
} catch (JMSException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}

public static void main(String[] args) {
MQJavaHybrid mqj = new MQJavaHybrid();
// Send an MQ message
DateFormat df = new SimpleDateFormat("hh:mm:ss:SSS");
final String messageText = "" + df.format(new Date()) + "";

mqj.testSendUsingNonJMSJavaMQAPI(messageText);
mqj.readUsingJMS();
}
}