Websphere MQ Using Java
Websphere MQ Using Java
Using Java
SC34-5456-07
MQSeries®
Using Java
SC34-5456-07
Note!
Before using this information and the product it supports, be sure to read the general information under “Appendix H.
Notices” on page 373.
Contents v
Methods . . . . . . . . . . . . . . 293 Appendix B. Scripts provided with
QueueSender . . . . . . . . . . . . . 295 MQSeries classes for Java Message
Methods . . . . . . . . . . . . . . 295
Service . . . . . . . . . . . . . . 351
QueueSession . . . . . . . . . . . . . 298
Methods . . . . . . . . . . . . . . 298
Session . . . . . . . . . . . . . . . 301 Appendix C. LDAP schema definition
Fields . . . . . . . . . . . . . . . 301 for storing Java objects . . . . . . . 353
Methods . . . . . . . . . . . . . . 301 Checking your LDAP server configuration . . . 353
StreamMessage . . . . . . . . . . . . . 306 | Attribute definitions . . . . . . . . . . . 354
Methods . . . . . . . . . . . . . . 306 | objectClass definitions . . . . . . . . . . 355
TemporaryQueue . . . . . . . . . . . . 314 | Server-specific configuration details . . . . . . 356
Methods . . . . . . . . . . . . . . 314 | Netscape Directory (4.1 and earlier) . . . . . 356
TemporaryTopic . . . . . . . . . . . . 315 | Microsoft® Active Directory . . . . . . . 356
MQSeries constructor. . . . . . . . . . 315 | Sun Microsystems’ Schema Modification
Methods . . . . . . . . . . . . . . 315 | Applications. . . . . . . . . . . . . 357
TextMessage . . . . . . . . . . . . . . 316 | iSeries OS/400 V4R5 Schema Modification . . 357
Methods . . . . . . . . . . . . . . 316
Topic . . . . . . . . . . . . . . . . 317 Appendix D. Connecting to MQSeries
MQSeries constructor. . . . . . . . . . 317 Integrator V2. . . . . . . . . . . . 359
Methods . . . . . . . . . . . . . . 317
Publish/subscribe . . . . . . . . . . . . 359
TopicConnection . . . . . . . . . . . . 319
Transformation and routing . . . . . . . . 360
Methods . . . . . . . . . . . . . . 319
TopicConnectionFactory . . . . . . . . . . 321
MQSeries constructor. . . . . . . . . . 321 Appendix E. JMS JTA/XA interface
Methods . . . . . . . . . . . . . . 321 with WebSphere . . . . . . . . . . 361
TopicPublisher . . . . . . . . . . . . . 324 Using the JMS interface with WebSphere . . . . 361
Methods . . . . . . . . . . . . . . 324 Administered objects . . . . . . . . . . 361
TopicRequestor . . . . . . . . . . . . . 327 Container-managed versus bean-managed
Constructors. . . . . . . . . . . . . 327 transactions . . . . . . . . . . . . . 362
Methods . . . . . . . . . . . . . . 327 Two-phase commit versus one-phase
TopicSession. . . . . . . . . . . . . . 329 optimization. . . . . . . . . . . . . 362
MQSeries constructor. . . . . . . . . . 329 Defining administered objects . . . . . . . 362
Methods . . . . . . . . . . . . . . 329 Retrieving administration objects . . . . . . 362
TopicSubscriber. . . . . . . . . . . . . 333 Samples . . . . . . . . . . . . . . . 362
Methods . . . . . . . . . . . . . . 333 Sample1 . . . . . . . . . . . . . . 363
XAConnection . . . . . . . . . . . . . 334 Sample2 . . . . . . . . . . . . . . 364
XAConnectionFactory . . . . . . . . . . 335 Sample3 . . . . . . . . . . . . . . 364
XAQueueConnection . . . . . . . . . . . 336
Methods . . . . . . . . . . . . . . 336 | Appendix F. Using MQ Java in applets
XAQueueConnectionFactory . . . . . . . . 337 | with Java 1.2 or later . . . . . . . . 367
Methods . . . . . . . . . . . . . . 337 | Changing browser security settings . . . . . . 367
XAQueueSession . . . . . . . . . . . . 339 | Copying package class files. . . . . . . . . 368
Methods . . . . . . . . . . . . . . 339
XASession . . . . . . . . . . . . . . 340
Methods . . . . . . . . . . . . . . 340
| Appendix G. Information for
XATopicConnection . . . . . . . . . . . 342 | SupportPac MA1G . . . . . . . . . 369
Methods . . . . . . . . . . . . . . 342 | Environments supported by SupportPac MA1G 369
XATopicConnectionFactory . . . . . . . . . 344 | Obtaining and installing SupportPac MA1G . . . 369
Methods . . . . . . . . . . . . . . 344 | Verifying installation using the sample program 370
XATopicSession. . . . . . . . . . . . . 346 | Features not provided by SupportPac MA1G . . . 370
Methods . . . . . . . . . . . . . . 346 | Running MQ base Java applications under CICS
| Transaction Server for OS/390 . . . . . . . . 371
| Restrictions under CICS Transaction Server . . . 371
Part 4. Appendixes . . . . . . . . 347
Appendix H. Notices . . . . . . . . 373
Appendix A. Mapping between Trademarks . . . . . . . . . . . . . . 374
Administration tool properties and
programmable properties . . . . . . 349 Glossary of terms and abbreviations 375
Bibliography . . . . . . . . . . . . 379
Contents vii
viii MQSeries Using Java
Figures
1. MQSeries classes for Java example applet 53 5. JMS to MQSeries mapping model . . . . . 206
2. MQSeries classes for Java example application 56 6. ServerSessionPool and ServerSession
3. MQSeries classes for Java Message Service functionality . . . . . . . . . . . . 216
topic name hierarchy . . . . . . . . . 182 7. MQSeries Integrator message flow . . . . 359
4. JMS to MQSeries mapping model . . . . . 195
Users intending to use the MQ base Java with CICS® Transaction Server for
OS/390® should also be familiar with:
v Customer Information Control System (CICS) concepts
v Using the CICS Java Application Programming Interface (API)
v Running Java programs from within CICS
First, read the chapters in Part 1 that introduce you to MQ base Java and MQ JMS.
Then, use the programming guidance in Part 2 or 3 to understand how to use the
classes to send and receive MQSeries messages in the environment you wish to
use.
| Remember to check the README file installed with the MQ Java code for later or
| more specific information for your environment.
It enables Java applets, applications, and servlets to issue calls and queries to
MQSeries. This gives access to mainframe and legacy applications, typically over
the Internet, without necessarily having any other MQSeries code on the client
machine. With MQ base Java, the user of an Internet terminal can become a true
participant in transactions, rather than just a giver and receiver of information.
The use of MQ JMS as the API to write MQSeries applications has a number of
benefits. Some advantages derive from JMS being an open standard with multiple
implementations. Other advantages result from additional features that are present
in MQ JMS, but not in MQ base Java.
MQSeries and MQSeries classes for Java Message Service provide an excellent
infrastructure for access to enterprise applications and for development of complex
Web applications. A service request from a Web browser can be queued then
processed when possible, thus allowing a timely response to be sent to the end
user, regardless of system loading. By placing this queue ’close’ to the user in
network terms, the load on the network does not impact the timeliness of the
response. Also, the transactional nature of MQSeries messaging means that a
simple request from the browser can be expanded safely into a sequence of
individual back-end processes in a transactional manner.
MQSeries classes for Java also enables application developers to exploit the power
of the Java programming language to create applets and applications that can run
on any platform that supports the Java runtime environment. These factors
combine to reduce the development time for multi-platform MQSeries applications
significantly. Also, if there are enhancements to applets in the future, end users
automatically pick these up as the applet code is downloaded.
Connection options
Programmable options allow MQ Java to connect to MQSeries in either of the
following ways:
v As an MQSeries client using Transmission Control Protocol/Internet Protocol
(TCP/IP)
v In bindings mode, connecting directly to MQSeries
MQ base Java on Windows NT® can also connect using VisiBroker for Java. Table 1
on page 5 shows the connection modes that can be used for each platform.
Notes:
1. HP-UX Java bindings support is available only for HP-UXv11 systems running
the POSIX draft 10 pthreaded version of MQSeries. You also require the HP-UX
Developer’s Kit for Java 1.1.7 (JDK™), Release C.01.17.01 or above.
2. On HP-UXv10.20, Linux, Windows 95, and Windows 98, only TCP/IP client
connectivity is supported.
Client connection
To use MQ Java as an MQSeries client, you can install it either on the MQSeries
server machine, which may also contain a Web server, or on a separate machine. If
you install MQ Java on the same machine as a Web server, an advantage is that
you can download and run MQSeries client applications on machines that do not
have MQ Java installed locally.
Wherever you choose to install the client, you can run it in three different modes:
From within any Java-enabled Web browser
In this mode, the locations of the MQSeries queue managers that can be
accessed may be constrained by the security restrictions of the browser that
is used.
Using an appletviewer
To use this method, you must have the Java Development Kit (JDK) or
Java Runtime Environment (JRE) installed on the client machine.
As a standalone Java program or in a Web application server
To use this method, you must have the Java Development Kit (JDK) or
Java Runtime Environment (JRE) installed on the client machine.
Bindings connection
When used in bindings mode, MQ Java uses the Java Native Interface (JNI) to call
directly into the existing queue manager API, rather than communicating through
a network. This provides better performance for MQSeries applications than using
network connections. Unlike the client mode, applications that are written using
the bindings mode cannot be downloaded as applets.
To use the bindings connection, MQ Java must be installed on the MQSeries server.
Prerequisites
To run MQ base Java, you require the following software:
v MQSeries for the server platform you wish to use.
v Java Development Kit (JDK) for the server platform.
v Java Development Kit, or Java Runtime Environment (JRE), or Java-enabled Web
browser for client platforms. (See “Client connection” on page 5.)
v VisiBroker for Java (only if running on Windows with a VisiBroker connection).
| v For z/OS & OS/390, OS/390 Version 2 Release 9 or higher, or z/OS, with UNIX
| System Services (USS).
v For OS/400, the AS/400 Developer Kit for Java, 5769-JV1, and the Qshell
Interpreter, OS/400 (5769-SS1) Option 30.
To use the MQ JMS administration tool (see “Chapter 5. Using the MQ JMS
administration tool” on page 31), you require the following additional software:
v At least one of the following service provider packages:
– Lightweight Directory Access Protocol (LDAP) - ldap.jar, providerutil.jar.
– File system - fscontext.jar, providerutil.jar.
v A Java Naming and Directory Service (JNDI) service provider. This is the
resource that stores physical representations of the administered objects. Users of
MQ JMS will probably use an LDAP server for this purpose, but the tool also
supports the use of the file system context service provider. If an LDAP server is
used, it must be configured to store JMS objects. For information to assist with
this configuration, refer to “Appendix C. LDAP schema definition for storing
Java objects” on page 353.
| Obtaining MQSeries classes for Java and MQSeries classes for Java
| Message Service
| This product is available for the AIX, iSeries & AS/400, HP-UX, Linux, Sun Solaris,
| z/OS & OS/390, and Windows platforms. It contains:
| v MQSeries classes for Java (MQ base Java) Version 5.2.0
| v MQSeries classes for Java Message Service (MQ JMS) Version 5.2
| The product is supplied as compressed files that are available from the MQSeries
| Web site, http://www.ibm.com/software/mqseries/. The files are supplied as part
| of SupportPac MA88. Follow links to “Download” and then “SupportPacs” to find
| the MQ Java code.
| Note: Before installing or using MQ Java, remember to consult the README file
| that is found in the doc subdirectory with the installed code. This may
| contain information that corrects or supplements this book.
|
Installing MQSeries classes for Java and MQSeries classes for Java
Message Service
For the latest versions of just the MQ base Java classes, you can install MQ base
Java Version 5.2.0 alone. To use MQ JMS applications, you must install both MQ
base Java and MQ JMS (together known as MQ Java).
The following Java libraries from Sun Microsystems are redistributed with the MQ
JMS product:
connector.jar Version 1.0 Public Draft
For installation instructions, see the section that is relevant to the platform you
require:
AIX, HP-UX, and Sun Solaris “Installing on UNIX”
| z/OS and OS/390 “Installing on z/OS & OS/390” on page 9
| iSeries & AS/400 “Installing on iSeries & AS/400” on page 9
Linux “Installing on Linux” on page 9
Windows “Installing on Windows” on page 10
When installation is complete, files and samples are installed in the locations
shown in “Installation directories” on page 10.
Note: Take care if you install the product, then subsequently install or reinstall
base MQSeries. Make sure that you do not install MQ base Java version 5.1,
because your MQSeries Java support will revert back a level.
Installing on UNIX
This section describes how to install MQ Java on AIX, HP-UX, and Sun Solaris. For
information about installing MQ base Java on Linux, see “Installing on Linux” on
page 9.
Note: Java does not support code page 1051 (which is the default for
HP-UX). To run the Publish/Subscribe broker on HP-UX, you may
need to change the CCSID of the broker’s queue manager to an
alternative value, for example 819.
v For Sun Solaris, enter the following command and select the options you
require:
pkgadd -d /tmp mqjava
| This creates and populates a directory named mqm in the current directory.
| Installing on Linux
This section describes how to install MQ Java on Linux.
For Linux, there are two installation files available, ma88_linux.tgz and
MQSeriesJava-5.2.0-1.noarch.rpm. Each file provides an identical installation.
If you do not have root access to the target system, or the target system does not
have RPM installed, use ma88_linux.tgz.
This creates and populates a directory named mqm in the current directory (for
example, /opt).
Installing on Windows
This section describes how to install MQ Java on Windows.
1. Create an empty directory called tmp and make it the current directory.
2. Copy the file ma88_win.zip to this directory.
3. Uncompress ma88_win.zip using InfoZip’s Unzip facility.
4. Run setup.exe from this directory and follow the prompts on the resulting
windows.
Note: If you wish to install MQ base Java only, select the relevant options at
this stage.
Installation directories
The MQ Java V5.2 files are installed in the directories shown in Table 2.
Table 2. Product installation directories
Platform Directory
AIX usr/mqm/java/
| z/OS & OS/390 install_dir/mqm/java/
| iSeries & AS/400 /QIBM/ProdData/mqm/java/
HP-UX and Sun Solaris opt/mqm/java/
Linux install_dir/mqm/java/
Windows 95, 98, 2000, and NT install_dir\
Environment variables
After installation, you must update your CLASSPATH environment variable to
include the MQ base Java code and samples directories. Table 3 shows typical
CLASSPATH settings for the various platforms.
Table 3. Sample CLASSPATH statements for the product
Platform Sample CLASSPATH
AIX CLASSPATH=/usr/mqm/java/lib/com.ibm.mq.jar:
/usr/mqm/java/lib/connector.jar:
/usr/mqm/java/lib:
/usr/mqm/java/samples/base:
HP-UX and CLASSPATH=/opt/mqm/java/lib/com.ibm.mq.jar:
Sun Solaris /opt/mqm/java/lib/connector.jar:
/opt/mqm/java/lib:
/opt/mqm/java/samples/base:
Windows 95, 98, CLASSPATH=install_dir\lib\com.ibm.mq.jar;
2000, and NT install_dir\lib\com.ibm.mq.iiop.jar;
install_dir\lib\connector.jar;
install_dir\lib\;
install_dir\samples\base\;
| z/OS & OS/390 CLASSPATH=install_dir/mqm/java/lib/com.ibm.mq.jar:
| install_dir/mqm/java/lib/connector.jar:
| install_dir/mqm/java/lib:
| install_dir/mqm/java/samples/base:
| iSeries & AS/400 CLASSPATH=/QIBM/ProdData/mqm/java/lib/com.ibm.mq.jar:
| /QIBM/ProdData/mqm/java/lib/connector.jar:
| /QIBM/ProdData/mqm/java/lib:
| /QIBM/ProdData/mqm/java/samples/base:
Linux CLASSPATH=install_dir/mqm/java/lib/com.ibm.mq.jar:
install_dir/mqm/java/lib/connector.jar:
install_dir/mqm/java/lib:
install_dir/mqm/java/samples/base:
Notes:
1. jdk_dir is the directory in which the JDK is installed
2. install_dir is the directory in which you installed the product
To use MQ JMS, you must include additional jar files in the classpath. These are
listed in “Post installation setup” on page 19.
Notes:
1. To use MQSeries Bindings for Java on OS/400, ensure that the library
QMQMJAVA is in your library list.
2. Ensure that you append the MQSeries variables and do not overwrite any of
the existing system environment variables. If you overwrite existing system
environment variables, the application might fail during compilation or at
runtime.
| Note: On z/OS & OS/390, the installed classes do not support client connection
and cannot be usefully downloaded to clients. However, jar files from
| another platform can be transferred to z/OS or OS/390 and served to
clients.
| Remember to check the README file installed with the MQ Java code for later or
| more specific information for your environment.
The procedures depend on the connection option you want to use. Follow the
instructions in the section that is appropriate for your requirements.
| In addition, the standard security settings for applets in Java 1.2 and higher require
| that all referenced classes are loaded from the same location as the applet you wish
| to run. For information on ways to get applets that use MQ Java to work, see
| “Appendix F. Using MQ Java in applets with Java 1.2 or later” on page 367.
The applet connects to a given queue manager, exercises all the MQSeries calls,
and produces diagnostic messages if there are any failures.
You can run the applet from the appletviewer supplied with your JDK. The
appletviewer can access a queue manager on any host.
In all cases, if the applet does not complete successfully, follow the advice given in
the diagnostic messages and try to run the applet again.
| Note: You must have the Client attachment feature installed on your
| target queue manager in order to connect via TCP/IP.
| a. Start your queue manager by using the START QMGR command.
| b. Define a sample channel called JAVA.CHANNEL by issuing the
| following command:
| DEF CHL('JAVA.CHANNEL') CHLTYPE(SVRCONN) TRPTYPE(TCP)
| DESCR('Sample channel for MQSeries Client for Java')
| For other platforms:
| a. Start your queue manager by using the strmqm command.
| b. Type the following command to start the runmqsc program:
| runmqsc
| c. Define a sample channel called JAVA.CHANNEL by issuing the
| following command:
| DEF CHL('JAVA.CHANNEL') CHLTYPE(SVRCONN) TRPTYPE(TCP) MCAUSER(' ') +
| DESCR('Sample channel for MQSeries Client for Java')
| 2. Start a listener program with the following commands:
For OS/2 and NT operating systems:
Issue the command:
runmqlsr -t tcp [-m QMNAME] -p 1414
Note: If you use the default queue manager, you can omit the -m
option.
Using VisiBroker for Java on the Windows NT operating system:
Start the IIOP (Internet Inter-ORB Protocol) server with the following
command:
java com.ibm.mq.iiop.Server
By using this technique, you should be able to connect to any queue manager
running on any host to which you have TCP/IP access.
To specify a parameter value, remove the initial exclamation mark, and edit the
value as desired. You can specify the following parameters:
hostname The value to display initially in the hostname edit box.
port The value to display initially in the port number edit box.
channel The value to display initially in the channel edit box.
queueManager
The value to display initially in the queue manager edit box.
userID Uses the specified user ID when connecting to the queue manager.
password Uses the specified password when connecting to the queue
manager.
trace Causes MQ base Java to write a trace log. Use this option only at
the direction of IBM service.
To test a bindings connection, carry out the rest of this procedure on the
MQSeries server machine.
2. Change to your samples directory.
3. Type:
java MQIVP
Here is an example of the prompts and responses you may see. The actual prompts
and your responses depend on your MQSeries network.
Please enter the type of connection (MQSeries) : (MQSeries)(1)
Please enter the IP address of the MQSeries server : myhost(2)
Please enter the port to connect to : (1414)(3)
Please enter the server connection channel name : JAVA.CHANNEL(3)
Please enter the queue manager name :
Success: Connected to queue manager.
Success: Opened SYSTEM.DEFAULT.LOCAL.QUEUE
Success: Put a message to SYSTEM.DEFAULT.LOCAL.QUEUE
Success: Got a message from SYSTEM.DEFAULT.LOCAL.QUEUE
Success: Closed SYSTEM.DEFAULT.LOCAL.QUEUE
Success: Disconnected from queue manager
Tests complete -
SUCCESS: This transport is functioning correctly.
Press Enter to continue...
Notes:
1. If you choose server connection, you do not see the prompts marked (3).
| 2. On z/OS & OS/390, leave the field blank at prompt (2).
3. On OS/400, you can run the command java MQIVP only from the Qshell
interactive interface (the Qshell is option 30 of OS/400, 5769-SS1). Alternatively,
you can run the application by using the CL command RUNJVA CLASS(MQIVP).
4. To use the MQSeries bindings for Java on OS/400, you must ensure that the
library QMQMJAVA is in your library list.
For information on writing MQ base Java applications and applets, see “Part 2.
Programming with MQ base Java” on page 45.
If the problems continue and you need to contact the IBM service team, you may
be asked to turn on the trace facility. The method to do this depends on whether
you are running in client mode or bindings mode. Refer to the following sections
for the appropriate procedures for your system.
Remove the exclamation mark and change the value from 1 to a number from 1 to
5, depending on the level of detail required. (The greater the number, the more
information is gathered.) The line should then read:
<PARAM name="trace" value="n">
The trace output appears in the Java console or in your Web browser’s Java log
file.
where “n” is a number between 1 and 5, depending on the level of detail required.
(The greater the number, the more information is gathered.)
For more information about how to use trace, see “Tracing MQ base Java
programs” on page 70.
To make all the necessary resources available to MQ JMS programs, you need to
update the following system variables:
Classpath
Successful operation of JMS programs requires a number of Java packages
to be available to the JVM. You must specify these on the classpath after
you have obtained and installed the necessary packages.
Add the following .jar files to the classpath:
v com.ibm.mq.jar
v com.ibm.mqjms.jar
v connector.jar
v jms.jar
| v jndi.jar1
v jta.jar
| v ldap.jar1
v providerutil.jar
Environment variables
There are a number of scripts in the bin subdirectory of the MQ JMS
installation. These are intended for use as convenient shortcuts for a
number of common actions. Many of these scripts assume that the
environment variable MQ_JAVA_INSTALL_PATH is defined, and that it points
to the directory in which MQ JMS is installed. It is not mandatory to set
this variable, but if you do not set it, you must edit the scripts in the bin
directory accordingly.
On Windows NT, you can set the classpath and new environment variable by
using the Environment tab of the System Properties. On UNIX, these would
1. For z/OS & OS/390, use ibmjndi.jar and jndi.jar from /usr/lpp/ldap/lib instead of jndi.jar and ldap.jar. These files are
supplied with the operating system.
If the operating system reports that it cannot run the dspmqbrk command,
ensure that the MQSeries Publish/Subscribe broker is installed properly.
If the operating system reports that the broker is not active, start it using
the command:
strmqbrk -m MY.QUEUE.MANAGER
Create the MQ JMS System Queues
For the MQ JMS Publish/Subscribe implementation to work correctly, a
number of system queues must be created. A script is supplied, in the bin
subdirectory of the MQ JMS installation, to assist with this task. To use the
script, enter the following commands:
| For iSeries & AS/400:
| 1. Copy the script from the integrated file system to a native file
| system library using a command similar to
| CPYFRMSTMF FROMSTMF('/QIBM/ProdData/mqm/java/bin/MQJMS_PSQ.mqsc')
| TOMBR('/QSYS.LIB/QGPL.LIB/QCLSRC.FILE/MQJMS_PSQ.MBR')
| 2. Call the script file using STRMQMMQSC:
| STRMQMMQSC SRCMBR(MQJMS_PSQ) SRCFILE(QGPL/QCLSRC)
| For z/OS & OS/390:
| 1. Copy the script from the HFS into a PDS using a TSO
| command similar to
| OGET '/usr/lpp/mqm/java/bin/MQJMS_PSQ.mqsc' 'USERID.MQSC(MQJMSPSQ)'
For JMS point-to-point mode, the access control issues are similar to those for the
MQSeries classes for Java:
v Queues that are used by QueueSender require put authority.
v Queues that are used by QueueReceivers and QueueBrowsers require get, inq
and browse authorities.
v The QueueSession.createTemporaryQueue method requires access to the model
queue that is defined in the QueueConnectionFactory temporaryModel field (by
default this will be SYSTEM.DEFAULT.MODEL.QUEUE).
For JMS publish/subscribe mode, the following system queues are used:
SYSTEM.JMS.ADMIN.QUEUE
SYSTEM.JMS.REPORT.QUEUE
SYSTEM.JMS.MODEL.QUEUE
SYSTEM.JMS.PS.STATUS.QUEUE
Chapter 4. Using MQSeries classes for Java Message Service (MQ JMS) 21
Publish/Subscribe setup
SYSTEM.JMS.ND.SUBSCRIBER.QUEUE
SYSTEM.JMS.D.SUBSCRIBER.QUEUE
SYSTEM.JMS.ND.CC.SUBSCRIBER.QUEUE
SYSTEM.JMS.D.CC.SUBSCRIBER.QUEUE
SYSTEM.BROKER.CONTROL.QUEUE
Also, any application that publishes messages requires access to the STREAM
queue that is specified in the topic connection factory being used. The default
value for this is:
SYSTEM.BROKER.DEFAULT.STREAM
The IVT attempts to verify the installation by connecting to the default queue
manager on the local machine, using the MQ JMS in bindings mode. It then sends
a message to the SYSTEM.DEFAULT.LOCAL.QUEUE queue and reads it back again.
For client mode, to run the test without JNDI, issue the following command:
IVTRun -nojndi -client -m <qmgr> -host <hostname> [-port <port>]
[-channel <channel>]
where:
If the test completes successfully, you should see output similar to the following:
5648-C60 (c) Copyright IBM Corp. 1999. All Rights Reserved.
MQSeries Classes for Java(tm) Message Service - Installation Verification Test
Creating a QueueConnectionFactory
Creating a Connection
Creating a Session
Creating a Queue
Creating a QueueSender
Creating a QueueReceiver
Creating a TextMessage
Sending the message to SYSTEM.DEFAULT.LOCAL.QUEUE
Reading the message back again
This message means that either the server is not storing Java objects, or the
permissions on the objects or the suffix are not correct. See “Checking your LDAP
server configuration” on page 353.
Chapter 4. Using MQSeries classes for Java Message Service (MQ JMS) 23
Point-to-point IVT
The script invokes the MQ JMS Administration tool (see “Chapter 5. Using the MQ
JMS administration tool” on page 31) and creates the objects in a JNDI namespace.
The MQQueue is bound under the name ivtQ (cn=ivtQ). The value of the QUEUE
property becomes QUEUE(SYSTEM.DEFAULT.LOCAL.QUEUE). All other properties have
default values:
PERSISTENCE(APP)
QUEUE(SYSTEM.DEFAULT.LOCAL.QUEUE)
EXPIRY(APP)
TARGCLIENT(JMS)
ENCODING(NATIVE)
VERSION(1)
CCSID(1208)
PRIORITY(APP)
QMANAGER()
Once the administered objects are created in the JNDI namespace, run the IVTRun
(IVTRun.bat on Windows NT) script using the following command:
IVTRun [ -t ] -url <"providerURL"> [ -icf <initCtxFact> ]
where:
-t means turn tracing on (by default, tracing is off)
providerURL is the JNDI location of the administered objects. If the default
initial context factory is in use, this is an LDAP URL of the form:
ldap://hostname.company.com/contextName
If the test completes successfully, the output is similar to the non-JNDI output,
except that the ’create’ QueueConnectionFactory and Queue lines indicate retrieval
of the object from JNDI. The following code fragment shows an example.
5648-C60 (c) Copyright IBM Corp. 1999. All Rights Reserved.
MQSeries Classes for Java(tm) Message Service - Installation Verification Test
Although not strictly necessary, it is good practice to remove objects that are
created by the IVTSetup script from the JNDI namespace. A script called IVTTidy
(IVTTidy.bat on Windows NT) is provided for this purpose.
Table 5 lists the classes that are tested by IVT, and the package that they come
from:
Table 5. Classes that are tested by IVT
Class Jar file
MQSeries JMS classes com.ibm.mqjms.jar
com.ibm.mq.MQMessage com.ibm.mq.jar
javax.jms.Message jms.jar
javax.naming.InitialContext jndi.jar
javax.resource.cci.Connection connector.jar
javax.transaction.xa.XAException jta.jar
com/sun/jndi/toolkit/ComponentDirContext providerutil.jar
com.sun.jndi.ldap.LdapCtxFactory ldap.jar
Chapter 4. Using MQSeries classes for Java Message Service (MQ JMS) 25
Publish/Subscribe IVT
2. Create a subscriber, s, subscribing on the topic MQJMS/PSIVT/Information
3. Use p to publish a simple text message
4. Use s to receive a message waiting on its input queue
When you run the PSIVT, the publisher publishes the message, and the subscriber
receives and displays the message. The publisher publishes to the broker’s default
stream. The subscriber is non-durable, does not perform message selection, and
accepts messages from local connections. It performs a synchronous receive,
waiting a maximum of 5 seconds for a message to arrive.
You can run the PSIVT, like the IVT, in either JNDI mode or standalone mode.
JNDI mode uses JNDI to retrieve a TopicConnectionFactory and a Topic from a
JNDI namespace. If JNDI is not used, these objects are created at runtime.
For client mode, to run the test without JNDI, issue the following command:
| PSIVTRun -nojndi -client -m <qmgr> -host <hostname> [-port <port>]
| [-channel <channel>] [-bqm <broker>] [-t]
where:
-nojndi means no JNDI lookup of the administered objects
qmgr is the name of the queue manager to which you wish to connect
hostname is the host on which the queue manager is running
port is the TCP/IP port on which the queue manager’s listener is
running (default 1414)
channel is the client connection channel (default SYSTEM.DEF.SVRCONN)
| broker is the name of the remote queue manager on which the broker is
| running. If this is not specified, the value used for qmgr is
| assumed.
-t means turn tracing on (default is off)
Got message:
You can define these objects by using the MQ JMS Administration Tool (see
“Chapter 5. Using the MQ JMS administration tool” on page 31) and using the
following commands:
DEFINE TCF(ivtTCF)
These definitions assume that a default queue manager, on which the broker is
running, is available. For details on configuring these objects to use a non-default
queue manager, see “Administering JMS objects” on page 35. These objects should
reside in a context pointed to by the -url command-line parameter described
below.
where:
-t means turn tracing on (by default, tracing is off)
-url <purl> is the URL of the JNDI location in which the administered objects
reside
Chapter 4. Using MQSeries classes for Java Message Service (MQ JMS) 27
Publish/Subscribe IVT
-icf <initcf> is the initialContextFactory for JNDI
[com.sun.jndi.ldap.LdapCtxFactory ]
If the test completes successfully, output is similar to the non-JNDI output, except
that the “create” QueueConnectionFactory and Queue lines indicate retrieval of the
object from JNDI.
this indicates that the broker is installed on the target queue manager, but its
control queue contains some outstanding messages. This indicates that the
broker is not running. To start it, use the strmqbrk command. (See “Additional
setup for Publish/Subscribe mode” on page 20.)
v If the following message is displayed:
Unable to connect to queue manager: <default>
ensure that your MQSeries system has configured a default queue manager.
v If the following message is displayed:
Unable to connect to queue manager: ...
MQ JMS includes a utility file, runjms (runjms.bat on Windows NT), to help you
to run the supplied programs and programs that you have written.
The utility provides default locations for the trace and log files, and enables you to
add any application runtime parameters that your application needs. The supplied
script assumes that the environment variable MQ_JAVA_INSTALL_PATH is set to
the directory in which the MQ JMS is installed. The script also assumes that the
subdirectories trace and log within that directory are used for trace and log
output, respectively. These are only suggested locations, and you can edit the script
to use any directory you choose.
Solving problems
If a program does not complete successfully, run the installation verification
program, which is described in “Chapter 4. Using MQSeries classes for Java
Message Service (MQ JMS)” on page 19, and follow the advice given in the
diagnostic messages.
Tracing programs
The MQ JMS trace facility is provided to help IBM staff to diagnose customer
problems.
Trace is disabled by default, because the output rapidly becomes large, and is
unlikely to be of use in normal circumstances.
If you are asked to provide trace output, you can enable it by setting the Java
property MQJMS_TRACE_LEVEL to one of the following values:
on traces MQ JMS calls only
base traces both MQ JMS calls and the underlying MQ base Java calls
For example:
java -DMQJMS_TRACE_LEVEL=base MyJMSProg
For example:
java -DMQJMS_TRACE_LEVEL=base -DMQJMS_TRACE_DIR=/somepath/tracedir MyJMSProg
The runjms utility script sets these properties by using the environment variables
MQJMS_TRACE_LEVEL and MQ_JAVA_INSTALL_PATH, as follows:
java -DMQJMS_LOG_DIR=%MQ_JAVA_INSTALL_PATH%\log
-DMQJMS_TRACE_DIR=%MQ_JAVA_INSTALL_PATH%\trace
-DMQJMS_TRACE_LEVEL=%MQJMS_TRACE_LEVEL% %1 %2 %3 %4 %5 %6 %7 %8 %9
Logging
The MQ JMS log facility is provided to report serious problems, particularly those
that may indicate configuration errors rather than programming errors. By default,
log output is sent to the System.err stream, which usually appears on the stderr
of the console in which the JVM is run.
You can redirect the output to a file by using a Java property that specifies the new
location, for example:
java -DMQJMS_LOG_DIR=/mydir/forlogs MyJMSProg
The utility script runjms, in the bin directory of the MQ JMSinstallation, sets this
property to:
Chapter 4. Using MQSeries classes for Java Message Service (MQ JMS) 29
Logging
<MQ_JAVA_INSTALL_PATH>/log
When the log is redirected to a file, it is output in a binary form. To view the log,
the utility formatLog (formatLog.bat on Windows NT) is provided, which converts
the file to plain text format. The utility is stored in the bin directory of your MQ
JMS installation. Run the conversion as follows:
formatLog <inputfile> <outputfile>
The JMS objects that you can administer by using the tool are:
v MQQueueConnectionFactory
v MQTopicConnectionFactory
v MQQueue
v MQTopic
v MQXAQueueConnectionFactory
v MQXATopicConnectionFactory
v JMSWrapXAQueueConnectionFactory
v JMSWrapXATopicConnectionFactory
For details about these objects, refer to “Administering JMS objects” on page 35.
where:
-t Enables trace (default is trace off)
-v Produces verbose output (default is terse output)
-cfg config_filename The name of an alternative configuration file (see
“Configuration” on page 32)
A command prompt is displayed, which indicates that the tool is ready to accept
administration commands. This prompt initially appears as:
InitCtx>
indicating that the current context (that is, the JNDI context to which all naming
and directory operations currently refer) is the initial context defined in the
PROVIDER_URL configuration parameter (see “Configuration” on page 32).
Configuration
You must configure the administration tool with values for the following three
parameters:
INITIAL_CONTEXT_FACTORY
This indicates the service provider that the tool uses. There are currently
three supported values for this property:
v com.sun.jndi.ldap.LdapCtxFactory (for LDAP)
v com.sun.jndi.fscontext.RefFSContextFactory (for file system context)
v com.ibm.ejs.ns.jndi.CNInitialContextFactory (to work with WebSphere’s
CosNaming repository)
These parameters are set in a configuration file. When you invoke the tool, you can
specify this configuration by using the -cfg command-line parameter, as described
in “Invoking the Administration tool” on page 31. If you do not specify a
configuration file name, the tool attempts to load the default configuration file
(JMSAdmin.config). It looks for this file first in the current directory, and then in the
| <MQ_JAVA_INSTALL_PATH>/bin directory, where “<MQ_JAVA_INSTALL_PATH>” is the
| path to your MQ JMS installation.
(A “#” in the first column of the line indicates a comment, or a line that is not
used.)
Security
Administrators need to know about the effect of the SECURITY_AUTHENTICATION
property described in “Configuration” on page 32.
v If this parameter is set to none, JNDI does not pass any security credentials to
the service provider, and “anonymous authentication” is performed.
v If the parameter is set to either simple or CRAM-MD5, security credentials are
passed through JNDI to the underlying service provider. These security
credentials are in the form of a user distinguished name (User DN) and
password.
If security credentials are required, then the user will be prompted for these when
the tool initializes.
Note: The text typed is echoed to the screen, and this includes the password.
Therefore, take care that passwords are not disclosed to unauthorized users.
The tool does no authentication itself; the task is delegated to the LDAP server. It
is the responsibility of the LDAP server administrator to set up and maintain
access privileges to different parts of the directory. If authentication fails, the tool
displays an appropriate error message and terminates.
Administration commands
When the command prompt is displayed, the tool is ready to accept commands.
Administration commands are generally of the following form:
verb [param]*
where verb is one of the administration verbs listed in Table 6. All valid commands
consist of at least one (and only one) verb, which appears at the beginning of the
command in either its standard or short form.
The parameters a verb may take depend on the verb. For example, the END verb
cannot take any parameters, but the DEFINE verb may take anything between 1 and
20 parameters. Details of the verbs that take at least one parameter are discussed
in later sections of this chapter.
Table 6. Administration verbs
Verb Short form Description
ALTER ALT Change at least one of the properties of a given
administered object
DEFINE DEF Create and store an administered object, or create a new
subcontext
DISPLAY DIS Display the properties of one or more stored administered
objects, or the contents of the current context
DELETE DEL Remove one or more administered objects from the
namespace, or remove an empty subcontext
CHANGE CHG Alter the current context, allowing the user to traverse the
directory namespace anywhere below the initial context
(pending security clearance)
COPY CP Make a copy of a stored administered object, storing it
under an alternative name
MOVE MV Alter the name under which an administered object is
stored
END Close the administration tool
Usually, to terminate commands, you press the carriage return key. However, you
can override this by typing the “+” symbol directly before the carriage return. This
enables you to enter multi-line commands, as shown in the following example:
DEFINE Q(BookingsInputQueue) +
QMGR(QM.POLARIS.TEST) +
QUEUE(BOOKINGS.INPUT.QUEUE) +
PORT(1415) +
CCSID(437)
Manipulating subcontexts
You can use the verbs CHANGE, DEFINE, DISPLAY and DELETE to manipulate directory
namespace subcontexts. Their use is described in Table 7.
Table 7. Syntax and description of commands used to manipulate subcontexts
Command syntax Description
DEFINE CTX(ctxName) Attempts to create a new child subcontext of the current
context, having the name ctxName. Fails if there is a
security violation, if the subcontext already exists, or if the
name supplied is invalid.
DISPLAY CTX Displays the contents of the current context. Administered
objects are annotated with ‘a’, subcontexts with ‘[D]’. The
Java type of each object is also displayed.
DELETE CTX(ctxName) Attempts to delete the current context’s child context
having the name ctxName. Fails if the context is not found,
is non-empty, or if there is a security violation.
CHANGE CTX(ctxName) Alters the current context, so that it now refers to the child
context having the name ctxName. One of two special
values of ctxName may be supplied:
=UP which moves to the current context’s parent
=INIT which moves directly to the initial context
Object types
Table 8 shows the eight types of administered objects. The Keyword column shows
the strings that you can substitute for TYPE in the commands shown in Table 9 on
page 36.
Table 8. The JMS object types that are handled by the administration tool
Object Type Keyword Description
MQQueueConnectionFactory QCF The MQSeries implementation of the
JMS QueueConnectionFactory
interface. This represents a factory
object for creating connections in the
point-to-point domain of JMS.
MQTopicConnectionFactory TCF The MQSeries implementation of the
JMS TopicConnectionFactory interface.
This represents a factory object for
creating connections in the
publish/subscribe domain of JMS.
MQQueue Q The MQSeries implementation of the
JMS Queue interface. This represents
a destination for messages in the
point-to-point domain of JMS.
1. These classes are provided for use by vendors of application servers. They are unlikely
to be directly useful to application programmers.
2. Use this style of ConnectionFactory if you wish your JMS sessions to participate in
global transactions that are coordinated by WebSphere.
Creating objects
Objects are created and stored in a JNDI namespace using the following command
syntax:
DEFINE TYPE(name) [property]*
That is, the DEFINE verb, followed by a TYPE(name) administered object reference,
followed by zero or more properties (see “Properties” on page 38).
The administration tool simplifies the use of LDAP service providers by allowing
you to refer to object and context names without a prefix. If you do not supply a
prefix, the tool automatically adds a default prefix (currently cn=) to the name you
supply.
Contents of InitCtx
a cn=testQueue com.ibm.mq.jms.MQQueue
1 Object(s)
0 Context(s)
1 Binding(s), 1 Administered
Note that although the object name supplied (testQueue) does not have a prefix,
the tool automatically adds one to ensure compliance with the LDAP naming
convention. Likewise, submitting the command DISPLAY Q(testQueue) also causes
this prefix to be added.
You may need to configure your LDAP server to store Java objects. Information to
assist with this configuration is provided in “Appendix C. LDAP schema definition
for storing Java objects” on page 353.
Properties
A property consists of a name-value pair in the format:
PROPERTY_NAME(property_value)
Property names are not case-sensitive, and are restricted to the set of recognized
names shown in Table 10. This table also shows the valid property values for each
property.
Table 10. Property names and valid values
Property Short form Valid values (defaults in bold)
DESCRIPTION DESC Any string
TRANSPORT TRAN v BIND - Connections use MQSeries bindings.
v CLIENT - Client connection is used
CLIENTID CID Any string
QMANAGER QMGR Any string
HOSTNAME HOST Any string
PORT Any positive integer
CHANNEL CHAN Any string
CCSID CCS Any positive integer
RECEXIT RCX Any string
RECEXITINIT RCXI Any string
SECEXIT SCX Any string
SECEXITINIT SCXI Any string
SENDEXIT SDX Any string
SENDXITINIT SDXI Any string
TEMPMODEL TM Any string
Many of the properties are relevant only to a specific subset of the object types.
| Table 11 on page 40 shows for each property which object types are valid, and
gives a brief description of each property. The object types are identified using
keywords; refer to Table 8 on page 35 for an explanation of these.
Notes:
1. For WSTCF, WSQCF, XATCF, and XAQCF objects, only the BIND transport
type is allowed.
2. “Appendix A. Mapping between Administration tool properties and
programmable properties” on page 349 shows the relationship between
properties set by the tool and programmable properties.
3. The TARGCLIENT property indicates whether the MQSeries RFH2 format is
used to exchange information with target applications.
The MQJMS_CLIENT_JMS_COMPLIANT constant indicates that the RFH2
format is used to send information. Applications that use MQ JMS understand
the RFH2 format. You should set the MQJMS_CLIENT_JMS_COMPLIANT
constant when you exchange information with a target MQ JMS application.
The MQJMS_CLIENT_NONJMS_MQ constant indicates that the RFH2 format is
not used to send information. Typically, this value is used for an existing
MQSeries application (that is, one that does not handle RFH2).
Property dependencies
Some properties have dependencies on each other. This may mean that it is
meaningless to supply a property unless another property is set to a particular
value. The two specific property groups where this can occur are Client properties
and Exit initialization strings.
Client properties
If the TRANSPORT(CLIENT) property has not been explicitly set on a
connection factory, the transport used on connections provided by the
factory is MQ Bindings. Consequently, none of the client properties on this
connection factory can be configured. These are:
v HOST
v PORT
v CHANNEL
v CCSID
v RECEXIT
If you attempt to set any of these properties without setting the TRANSPORT
property to CLIENT, there will be an error.
Exit initialization strings
It is invalid to set any of the exit initialization strings unless the
corresponding exit name has been supplied. The exit initialization
properties are:
v RECEXITINIT
v SECEXITINIT
v SENDEXITINIT
In this string:
v N denotes normal
v R denotes reversed
v 3 denotes System/390
v the first character represents integer encoding
v the second character represents decimal encoding
v the third character represents floating-point encoding
This provides a set of twelve possible values for the ENCODING property.
There is an additional value, the string NATIVE, which sets appropriate encoding
values for the Java platform.
When an update to the program is required, you update the copy on the Web
server. The next time that users access the applet, they automatically receive the
latest version. This can significantly reduce the costs involved in installing and
updating traditional client applications where a large number of desktops are
involved.
These verbs all take, as a parameter, a handle to the MQSeries object on which
they are to operate. Because Java is object-oriented, the Java programming interface
turns this round. Your program consists of a set of MQSeries objects, which you act
upon by calling methods on those objects, as in the following example.
When you use the procedural interface, you disconnect from a queue manager by
using the call MQDISC(Hconn, CompCode, Reason), where Hconn is a handle to
the queue manager.
You can download IBM Developer Kits for Java from the IBM Software Download
Catalog, which is available on the World Wide Web at location:
http://www.ibm.com/software/download
You can also develop applications by using the Developer Kit that is included with
the integrated development environment of IBM VisualAge for Java.
| To compile Java applications on the iSeries & AS/400 platforms, you must first
| install:
| v The AS/400 Developer Kit for Java, 5769-JV1
| v The Qshell Interpreter, OS/400 (5769-SS1) Option 30
Implementation of the following Java interfaces are also provided. However, these
interfaces are not intended for direct use by applications:
v MQConnectionManager
v javax.resource.spi.ManagedConnection
v javax.resource.spi.ManagedConnectionFactory
v javax.resource.spi.ManagedConnectionMetaData
In Java, a package is a mechanism for grouping sets of related classes together. The
MQSeries classes and interfaces are shipped as a Java package called com.ibm.mq.
To include the MQSeries classes for Java package in your program, add the
following line at the top of your source file:
import com.ibm.mq.*;
This chapter provides information to assist with writing Java applets, servlets, and
applications to interact with MQSeries systems. For details of individual classes,
see “Chapter 9. The MQ base Java classes and interfaces” on page 79.
Connection differences
The way you program for MQSeries classes for Java has some dependencies on the
connection modes you want to use.
Client connections
When MQSeries classes for Java is used as a client, it is similar to the MQSeries C
client, but has the following differences:
v It supports only TCP/IP.
v It does not support connection tables.
v It does not read any MQSeries environment variables at startup.
v Information that would be stored in a channel definition and in environment
variables is stored in a class called MQEnvironment. Alternatively, this
information can be passed as parameters when the connection is made.
v Error and exception conditions are written to a log specified in the MQException
class. The default error destination is the Java console.
For general information on MQSeries clients, see the MQSeries Clients book.
Note: When you use the VisiBroker connection, the userid and password settings
in MQEnvironment are not forwarded to the MQSeries server. The effective
userid is the one that applies to the IIOP server.
Bindings mode
The bindings mode of MQSeries classes for Java differs from the client modes in
the following ways:
v Most of the parameters provided by the MQEnvironment class are ignored
v The bindings support the MQBEGIN verb and fast bindings into the MQSeries
queue manager
Note: MQSeries for AS/400 does not support the use of MQBEGIN to initiate
global units of work that are coordinated by the queue manager.
} // end of init
try {
// Create a connection to the queue manager
qMgr = new MQQueueManager(qManager);
MQQueue system_default_local_queue =
qMgr.accessQueue("SYSTEM.DEFAULT.LOCAL.QUEUE",
openOptions);
// Define a simple MQSeries message, and write some text in UTF format..
system_default_local_queue.put(hello_world,pmo);
system_default_local_queue.get(retrievedMessage, gmo);
// And prove we have the message by displaying the UTF message text
system_default_local_queue.close();
qMgr.disconnect();
// If an error has occurred in the above, try to identify what went wrong.
// Was it an MQSeries error?
} // end of start
} // end of sample
to:
MQEnvironment.properties.put (MQC.TRANSPORT_PROPERTY,
MQC.TRANSPORT_VISIBROKER);
and add the following lines to initialize the ORB (object request broker):
ORB orb=ORB.init(this,null);
MQEnvironment.properties.put(MQC.ORB_PROPERTY,orb);
You also need to add the following import statement to the beginning of the file:
import org.omg.CORBA.ORB;
You do not need to specify port number or channel if you are using VisiBroker.
// ======================================================================
// Licensed Materials - Property of IBM
// 5639-C34
// (c) Copyright IBM Corp. 1995, 1999
// ======================================================================
// MQSeries classes for Java sample application
//
// This sample runs as a Java application using the command :- java MQSample
public MQSample() {
try {
MQQueue system_default_local_queue =
qMgr.accessQueue("SYSTEM.DEFAULT.LOCAL.QUEUE",
openOptions);
// Define a simple MQSeries message, and write some text in UTF format..
system_default_local_queue.put(hello_world,pmo);
system_default_local_queue.get(retrievedMessage, gmo);
// And prove we have the message by displaying the UTF message text
qMgr.disconnect();
}
// If an error has occurred in the above, try to identify what went wrong
// Was it an MQSeries error?
catch (MQException ex)
{
System.out.println("An MQSeries error occurred : Completion code " +
ex.completionCode + " Reason code " + ex.reasonCode);
}
// Was it a Java buffer space error?
catch (java.io.IOException ex)
{
System.out.println("An error occurred whilst writing to the message buffer: " + ex);
}
}
} // end of sample
The ″C″ based MQSeries clients rely on environment variables to control the
behavior of the MQCONN call. Because Java applets have no access to
environment variables, the Java programming interface includes a class
MQEnvironment. This class allows you to specify the following details that are to
be used during the connection attempt:
v Channel name
v Hostname
v Port number
v User ID
v Password
To specify the channel name and hostname, use the following code:
MQEnvironment.hostname = "host.domain.com";
MQEnvironment.channel = "java.client.channel";
By default, the Java clients attempt to connect to an MQSeries listener at port 1414.
To specify a different port, use the code:
MQEnvironment.port = nnnn;
Note: If you are setting up a connection using VisiBroker for Java, see “Changing
the connection to use VisiBroker for Java” on page 55.
To disconnect from a queue manager, call the disconnect() method on the queue
manager:
queueManager.disconnect();
The commit() and backout() methods on a queue manager replace the MQCMIT
and MQBACK calls that are used with the procedural interface.
The options parameter is the same as the Options parameter in the MQOPEN call.
When you have finished using the queue, use the close() method to close it, as in
the following example:
queue.close();
With MQSeries classes for Java, you can also create a queue by using the
MQQueue constructor. The parameters are exactly the same as for the accessQueue
method, with the addition of a queue manager parameter. For example:
MQQueue queue = new MQQueue(queueManager,
"qName",
MQC.MQOO_OUTPUT,
"qMgrName",
"dynamicQName",
"altUserId");
Constructing a queue object in this way enables you to write your own subclasses
of MQQueue.
When you have finished using the process object, use the close() method to close it,
as in the following example:
process.close();
With MQSeries classes for Java, you can also create a process by using the
MQProcess constructor. The parameters are exactly the same as for the
accessProcess method, with the addition of a queue manager parameter.
Constructing a process object in this way enables you to write your own subclasses
of MQProcess.
Handling messages
You put messages onto queues using the put() method of the MQQueue class. You
get messages from queues using the get() method of the MQQueue class. Unlike
the procedural interface, where MQPUT and MQGET put and get arrays of bytes,
the Java programming language puts and gets instances of the MQMessage class.
The MQMessage class encapsulates the data buffer that contains the actual
message data, together with all the MQMD (message descriptor) parameters that
describe that message.
To build a new message, create a new instance of the MQMessage class, and use
the writeXXX methods to put data into the message buffer.
When the new message instance is created, all the MQMD parameters are
automatically set to their default values, as defined in the MQSeries Application
Programming Reference. The put() method of MQQueue also takes an instance of the
MQPutMessageOptions class as a parameter. This class represents the MQPMO
structure. The following example creates a message and puts it onto a queue:
// Build a new message containing my age followed by my name
MQMessage myMessage = new MQMessage();
myMessage.writeInt(25);
You do not need to specify a maximum message size, because the get() method
automatically adjusts the size of its internal buffer to fit the incoming message. Use
the readXXX methods of the MQMessage class to access the data in the returned
message.
You can alter the number format that the read and write methods use by setting
the encoding member variable.
Handling errors
Methods in the Java interface do not return a completion code and reason code.
Instead, they throw an exception whenever the completion code and reason code
resulting from an MQSeries call are not both zero. This simplifies the program
logic so that you do not have to check the return codes after each call to MQSeries.
You can decide at which points in your program you want to deal with the
possibility of failure. At these points, you can surround your code with ’try’ and
’catch’ blocks, as in the following example:
try {
myQueue.put(messageA,putMessageOptionsA);
myQueue.put(messageB,putMessageOptionsB);
}
catch (MQException ex) {
// This block of code is only executed if one of
// the two put methods gave rise to a non-zero
// completion code or reason code.
System.out.println("An error occurred during the put operation:" +
"CC = " + ex.completionCode +
"RC = " + ex.reasonCode);
}
| The MQSeries call reason codes reported back in Java exceptions are documented
| in a chapter called “Return Codes” in the MQSeries Application Programming
| Reference book.
When you create a new queue manager object by using the new operator, it is
automatically opened for “inquiry”. When you use the accessProcess() method to
access a process object, that object is automatically opened for “inquiry”. When
you use the accessQueue() method to access a queue object, that object is not
automatically opened for either “inquire” or “set” operations. This is because
adding these options automatically can cause problems with some types of remote
queues. To use the inquire, set, getXXX, and setXXX methods on a queue, you
must specify the appropriate “inquire” and “set” flags in the openOptions
parameter of the accessQueue() method.
selectors[0] = MQIA_DEF_PRIORITY;
selectors[1] = MQCA_Q_DESC;
queue.inquire(selectors,intAttrs,charAttrs);
Multithreaded programs
Multithreaded programs are hard to avoid in Java. Consider a simple program that
connects to a queue manager and opens a queue at startup. The program displays
a single button on the screen. When a user presses that button, the program fetches
a message from the queue.
With the “C” based MQSeries client, this would cause a problem, because handles
cannot be shared across multiple threads. MQSeries classes for Java relaxes this
constraint, allowing a queue manager object (and its associated queue and process
objects) to be shared across multiple threads.
The implementation of MQSeries classes for Java ensures that, for a given
connection (MQQueueManager object instance), all access to the target MQSeries
queue manager is synchronized. Therefore, a thread wishing to issue a call to a
queue manager is blocked until all other calls in progress for that connection are
complete. If you require simultaneous access to the same queue manager from
multiple threads within your program, create a new MQQueueManager object for
each thread that requires concurrent access. (This is equivalent to issuing a
separate MQCONN call for each thread.)
To implement an exit, you define a new Java class that implements the appropriate
interface. Three exit interfaces are defined in the MQSeries package:
v MQSendExit
v MQReceiveExit
v MQSecurityExit
For a Send exit, the agentBuffer parameter contains the data that is about to be sent.
For a Receive exit or a Security exit, the agentBuffer parameter contains the data
that has just been received. You do not need a length parameter, because the
expression agentBuffer.length indicates the length of the array.
For the Send and Security exits, your exit code should return the byte array that
you wish to send to the server. For a Receive exit, your exit code should return the
modified data that you wish MQSeries classes for Java to interpret.
Connection pooling
MQSeries classes for Java Version 5.2 provides additional support for applications
that deal with multiple connections to MQSeries queue managers. When a
connection is no longer required, instead of destroying it, it can be pooled, and
later reused. This can provide a substantial performance enhancement for
applications and middleware that connect serially to arbitrary queue managers.
MQApp1 takes a list of local queue managers from the command line, connects to
each in turn, and performs some operation. However, when the command line lists
the same queue manager many times, it is more efficient to connect only once, and
to reuse that connection many times.
MQEnvironment.removeConnectionPoolToken(token);
}
}
The first bold line activates the default connection pool, by registering an
MQPoolToken object with MQEnvironment.
The second highlighted line deactivates the default connection pool, which
destroys any queue manager connections stored in the pool. This is important
because otherwise, the application would terminate with a number of live queue
manager connections in the pool. This situation could cause errors that would
appear in the queue manager logs.
The default connection pool stores a maximum of ten unused connections, and
keeps unused connections active for a maximum of five minutes. The application
can alter this (for details, see “Supplying a different connection pool” on page 67).
For example, the example application MQApp3 creates ten threads and starts each
one. Each thread registers its own MQPoolToken, waits for a length of time, then
connects to the queue manager. After the thread disconnects, it removes its own
MQPoolToken.
The default connection pool remains active while there is at least one token in the
set of MQPoolTokens, so it will remain active for the duration of this application.
The application does not need to keep a master object in overall control of the
threads.
import com.ibm.mq.*;
public class MQApp3
{
public static void main(String[] args)
{
for (int i=0; i<10; i++) {
MQApp3_Thread thread=new MQApp3_Thread(i*60000);
thread.start();
}
}
}
MQEnvironment.removeConnectionPoolToken(token);
}
}
The second line enables the MQSimpleConnectionManager. The last line disables
MQSimpleConnectionManager, destroying any connections held in the pool. An
MQSimpleConnectionManager is, by default, in MODE_AUTO, which is described
later in this section.
In the last line, the application calls MQApp3.main(). This runs a number of
threads, where each thread uses MQSeries independently. These threads will now
use myConnMan when they forge connections.
MQ base Java complies with the Connection Management contract of the J2EE
Connector Architecture. Please read this section in conjunction with the Connection
Management contract of the J2EE Connector Architecture (refer to Sun’s Web site at
http://java.sun.com).
The listener is notified when an MQPoolToken is added or removed from the set,
or when the default ConnectionManager changes. The MQPoolServices object also
provides a way to query the current size of the set of MQPoolTokens.
Run your applet either by loading this HTML file into a Java enabled Web browser,
or by using the appletviewer that comes with the Java Development Kit (JDK).
If your program is an application, or if you run it from your local disk using the
appletviewer command, you can also redirect the trace output to a file of your
choice. The following code fragment shows an example of how to redirect the trace
output to a file called myapp.trc:
import java.io.*;
try {
FileOutputStream
traceFile = new FileOutputStream("myapp.trc");
MQEnvironment.enableTracing(2,traceFile);
}
catch (IOException ex) {
// couldn't open the file,
// trace to System.err instead
MQEnvironment.enableTracing(2);
}
In all cases, the MQSeries classes for Java code uses services that are provided by
the underlying MQSeries server. There are differences in the level of function (for
example, MQSeries V5 provides a superset of the function of V2). There are also
differences in the behavior of some API calls and options. Most behavior
differences are minor, and most of them are between the OS/390 servers and the
servers on other platforms.
| In the list of environments above, an MQSeries for OS/390 server can be running
| any of the following supported queue managers:
| v MQSeries for MVS/ESA™ V1R2
| v MQSeries for OS/390 V2R1
| v MQSeries for OS/390 V5R2
MQSeries classes for Java provides a “core” of classes, which provide consistent
function and behavior in all the environments. It also provides “V5 extensions”,
which are designed for use only in environments 2 and 4. The following sections
describe the core and extensions.
Core details
| MQSeries classes for Java contains the following core set of classes, which can be
used in all environments with only the minor variations listed in “Restrictions and
variations for core classes” on page 74.
v MQEnvironment
v MQException
v MQGetMessageOptions
Excluding:
– MatchOptions
– GroupStatus
– SegmentStatus
– Segmentation
v MQManagedObject
Excluding:
– inquire()
– set()
v MQMessage
Excluding:
Apart from these documented variations, the core classes provide consistent
behavior across all environments, even if the equivalent MQSeries classes normally
have environment differences. In general, the behavior will be the same as in
environments 2 and 4.
Table 12. Core classes restrictions and variations
Class or element Restrictions and variations
| MQGMO_LOCK Cause MQRC_OPTIONS_ERROR when used in environments 3 or 5.
MQGMO_UNLOCK
MQGMO_BROWSE_MSG_UNDER_CURSOR
MQPMO_NEW_MSG_ID Give errors except in environments 2 and 4. (See V5 extensions.)
MQPMO_NEW_CORREL_ID
MQPMO_LOGICAL_ORDER
MQGMO_LOGICAL_ORDER Give errors except in environments 2 and 4. (See V5 extensions.)
MQGMO_COMPLETE_MESSAGE
MQGMO_ALL_MSGS_AVAILABLE
MQGMO_ALL_SEGMENTS_AVAILABLE
| Note: With MQSeries for OS/390 V2R1 or MQSeries for OS/390 V5R2
| running on the server, the MatchOptions field does support the flags
| MQMO_MATCH_MSG_ID and MQMO_MATCH_CORREL_ID.
| Other flags cause the get() to fail with MQRC_GMO_ERROR.
Distribution Lists
The following classes are used to create Distribution Lists:
v MQDistributionList
v MQDistributionListItem
v MQMessageTracker
Although primarily intended for use with distribution lists, the MQSeries
V5 server also fills in the DestCount fields after an MQPUT to a single
queue. For example, if the queue resolves to a local queue,
knownDestCount is set to 1 and the other two fields are set to 0. In
environments 2 and 4, the values set by the V5 server are returned in the
MQPutMessageOptions class. In the other environments, return values are
simulated as follows:
v If the put() succeeds, unknownDestCount is set to 1, and the others are
set to 0.
v If the put() fails, invalidDestCount is set to 1, and the others are set to 0.
recordFields is used with distribution lists. A value may be written into
recordFields at any time, regardless of the environment. However, it is
ignored if the MQPutMessage options are used on a subsequent
MQQueue.put(), rather than MQDistributionList.put().
MQMD fields
The following MQMD fields are largely concerned with message
segmentation:
v GroupId
v MsgSeqNumber
v Offset MsgFlags
v OriginalLength
MQChannelDefinition
java.lang.Object
│
└─ com.ibm.mq.MQChannelDefinition
Note: This class does not apply when connecting directly to MQSeries in bindings
mode.
Variables
channelName
public String channelName
The name of the channel through which the connection is established.
queueManagerName
public String queueManagerName
The name of the queue manager to which the connection is made.
maxMessageLength
public int maxMessageLength
The maximum length of message that can be sent to the queue manager.
securityUserData
public String securityUserData
A storage area for the security exit to use. Information placed here is
preserved across invocations of the security exit, and is also available to
the send and receive exits.
sendUserData
public String sendUserData
A storage area for the send exit to use. Information placed here is
preserved across invocations of the send exit, and is also available to the
security and receive exits.
receiveUserData
public String receiveUserData
A storage area for the receive exit to use. Information placed here is
preserved across invocations of the receive exit, and is also available to the
send and security exits.
connectionName
public String connectionName
The TCP/IP hostname of the machine on which the queue manager
resides.
Constructors
MQChannelDefinition
public MQChannelDefinition()
MQChannelExit
java.lang.Object
│
└─ com.ibm.mq.MQChannelExit
This class defines context information passed to the send, receive, and security
exits when they are invoked. The exitResponse member variable should be set by
the exit to indicate what action the MQSeries Client for Java should take next.
Note: This class does not apply when connecting directly to MQSeries in bindings
mode.
Variables
MQXT_CHANNEL_SEC_EXIT
public final static int MQXT_CHANNEL_SEC_EXIT
MQXT_CHANNEL_SEND_EXIT
public final static int MQXT_CHANNEL_SEND_EXIT
MQXT_CHANNEL_RCV_EXIT
public final static int MQXT_CHANNEL_RCV_EXIT
MQXR_INIT
public final static int MQXR_INIT
MQXR_TERM
public final static int MQXR_TERM
MQXR_XMIT
public final static int MQXR_XMIT
MQXR_SEC_MSG
public final static int MQXR_SEC_MSG
MQXR_INIT_SEC
public final static int MQXR_INIT_SEC
MQXCC_OK
public final static int MQXCC_OK
MQXCC_SUPPRESS_FUNCTION
public final static int MQXCC_SUPPRESS_FUNCTION
MQXCC_SEND_AND_REQUEST_SEC_MSG
public final static int MQXCC_SEND_AND_REQUEST_SEC_MSG
MQXCC_SEND_SEC_MSG
public final static int MQXCC_SEND_SEC_MSG
MQXCC_SUPPRESS_EXIT
public final static int MQXCC_SUPPRESS_EXIT
MQXCC_CLOSE_CHANNEL
public final static int MQXCC_CLOSE_CHANNEL
Constructors
MQChannelExit
public MQChannelExit()
MQDistributionList
java.lang.Object
│
└─ com.ibm.mq.MQManagedObject
│
└─ com.ibm.mq.MQDistributionList
Note: You can use this class only when connected to an MQSeries Version 5 (or
higher) queue manager.
A distribution list represents a set of open queues to which messages can be sent
using a single call to the put() method. (See ″Distribution lists″ in the MQSeries
Application Programming Guide.)
Constructors
MQDistributionList
public MQDistributionList(MQQueueManager qMgr,
MQDistributionListItem[] litems,
int openOptions,
String alternateUserId)
throws MQException
Methods
put
public synchronized void put(MQMessage message,
MQPutMessageOptions putMessageOptions )
throws MQException
Parameters
message
An input/output parameter containing the message descriptor
information and the returned message data.
putMessageOptions
Options that control the action of MQPUT. (See
“MQPutMessageOptions” on page 129 for details.)
Throws MQException if the put fails.
MQDistributionListItem
java.lang.Object
│
└─ com.ibm.mq.MQMessageTracker
│
└─ com.ibm.mq.MQDistributionListItem
Note: You can use this class only when connected to an MQSeries Version 5 (or
higher) queue manager.
Variables
completionCode
public int completionCode
The completion code resulting from the last operation on this item. If this
was the construction of an MQDistributionList, the completion code relates
to the opening of the queue. If it was a put operation, the completion code
relates to the attempt to put a message onto this queue.
The initial value is ″0″.
queueName
public String queueName
The name of a queue you want to use with a distribution list. This cannot
be the name of a model queue.
The initial value is ″″.
queueManagerName
public String queueManagerName
The name of the queue manager on which the queue is defined.
The initial value is ″″.
reasonCode
public int reasonCode
The reason code resulting from the last operation on this item. If this was
the construction of an MQDistributionList, the reason code relates to the
opening of the queue. If it was a put operation, the reason code relates to
the attempt to put a message onto this queue.
The initial value is ″0″.
Constructors
MQDistributionListItem
public MQDistributionListItem()
Construct a new MQDistributionListItem object.
MQEnvironment
java.lang.Object
│
└─ com.ibm.mq.MQEnvironment
Note: All the methods and attributes of this class apply to the MQSeries classes for
Java client connections, but only enableTracing, disableTracing, properties,
and version_notice apply to bindings connections.
Values set in the MQEnvironment class take effect when the MQQueueManager
constructor is called, so you should set the values in the MQEnvironment class
before you construct an MQQueueManager instance.
Variables
Note: Variables marked with * do not apply when connecting directly to MQSeries
in bindings mode.
version_notice
public final static String version_notice
The current version of MQSeries classes for Java.
securityExit*
public static MQSecurityExit securityExit
A security exit allows you to customize the security flows that occur
when an attempt is made to connect to a queue manager.
To provide your own security exit, define a class that implements
the MQSecurityExit interface, and assign securityExit to an instance
of that class. Otherwise, you can leave securityExit set to null, in
which case no security exit will be called.
See also “MQSecurityExit” on page 157.
sendExit*
public static MQSendExit sendExit
A send exit allows you to examine, and possibly alter, the data sent
to a queue manager. It is normally used in conjunction with a
corresponding receive exit at the queue manager.
To provide your own send exit, define a class that implements the
MQSendExit interface, and assign sendExit to an instance of that
class. Otherwise, you can leave sendExit set to null, in which case
no send exit will be called.
See also “MQSendExit” on page 159.
Key Value
MQC.CCSID_PROPERTY Integer (overrides MQEnvironment.CCSID)
MQC.CHANNEL_PROPERTY String (overrides MQEnvironment.channel)
MQC.CONNECT_OPTIONS_PROPERTY Integer, defaults to MQC.MQCNO_NONE
MQC.HOST_NAME_PROPERTY String (overrides MQEnvironment.hostname)
MQC.ORB_PROPERTY org.omg.CORBA.ORB (optional)
MQC.PASSWORD_PROPERTY String (overrides MQEnvironment.password)
MQC.PORT_PROPERTY Integer (overrides MQEnvironment.port)
MQC.RECEIVE_EXIT_PROPERTY MQReceiveExit (overrides
MQEnvironment.receiveExit)
MQC.SECURITY_EXIT_PROPERTY MQSecurityExit (overrides
MQEnvironment.securityExit)
MQC.SEND_EXIT_PROPERTY MQSendExit (overrides
MQEnvironment.sendExit.)
MQC.TRANSPORT_PROPERTY MQC.TRANSPORT_MQSERIES_BINDINGS
or
MQC.TRANSPORT_MQSERIES_CLIENT
or
MQC.TRANSPORT_VISIBROKER
or
MQC.TRANSPORT_MQSERIES (the default,
which selects bindings or client, based on
the value of ″hostname″.)
MQC.USER_ID_PROPERTY String (overrides MQEnvironment.userID.)
CCSID*
public static int CCSID
The CCSID used by the client.
Changing this value affects the way that the queue manager you
connect to translates information in the MQSeries headers. All data
in MQSeries headers is drawn from the invariant part of the ASCII
codeset, except for the data in the applicationIdData and the
putApplicationName fields of the MQMessage class. (See
“MQMessage” on page 102.)
If you avoid using characters from the variant part of the ASCII
codeset for these two fields, you are then safe to change the CCSID
from 819 to any other ASCII codeset.
Constructors
MQEnvironment
public MQEnvironment()
Methods
disableTracing
public static void disableTracing()
Turns off the MQSeries Client for Java trace facility.
enableTracing
public static void enableTracing(int level)
Turns on the MQSeries Client for Java trace facility.
Parameters
level The level of tracing required, from 1 to 5 (5 being the most
detailed).
enableTracing
public static void enableTracing(int level,
OutputStream stream)
Parameters:
level The level of tracing required, from 1 to 5 (5 being the most
detailed).
stream The stream to which the trace is written.
setDefaultConnectionManager
public static void setDefaultConnectionManager(MQConnectionManager cxManager)
Parameters:
cxManager
The MQConnectionManager to be the default ConnectionManager.
This method requires a JVM at Java 2 v1.3 or later, with JAAS 1.0 or later
installed.
Parameters:
cxManager
The default ConnectionManager (which implements the
javax.resource.spi.ConnectionManager interface).
getDefaultConnectionManager
public static javax.resource.spi.ConnectionManager
getDefaultConnectionManager()
Parameters:
token The MQPoolToken to add to the set of tokens.
addConnectionPoolToken
public static MQPoolToken addConnectionPoolToken()
Parameters:
token The MQPoolToken to remove from the set of tokens.
MQException
java.lang.Object
│
└─ java.lang.Throwable
│
└─ java.lang.Exception
│
└─ com.ibm.mq.MQException
Variables
log public static java.io.outputStreamWriter log
Stream to which exceptions are logged. (The default is System.err.) If you
set this to null, no logging occurs.
completionCode
public int completionCode
MQSeries completion code giving rise to the error. The possible values are:
v MQException.MQCC_WARNING
v MQException.MQCC_FAILED
reasonCode
public int reasonCode
MQSeries reason code describing the error. For a full explanation of the
reason codes, refer to the MQSeries Application Programming Reference.
exceptionSource
public Object exceptionSource
The object instance that threw the exception. You can use this as part of
your diagnostics when determining the cause of an error.
Constructors
MQException
public MQException(int completionCode,
int reasonCode,
Object source)
Parameters
completionCode
The MQSeries completion code.
MQGetMessageOptions
java.lang.Object
│
└─ com.ibm.mq.MQGetMessageOptions
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” on page 73 for details.
Variables
options
public int options
Options that control the action of MQQueue.get. Any or none of the
following values can be specified. If more than one option is required, the
values can be added together or combined using the bitwise OR operator.
MQC.MQGMO_NONE
MQC.MQGMO_WAIT
Wait for a message to arrive.
MQC.MQGMO_NO_WAIT
Return immediately if there is no suitable message.
MQC.MQGMO_SYNCPOINT
Get the message under syncpoint control; the message is marked
as being unavailable to other applications, but it is deleted from
the queue only when the unit of work is committed. The message
is made available again if the unit of work is backed out.
MQC.MQGMO_NO_SYNCPOINT
Get message without syncpoint control.
MQC.MQGMO_BROWSE_FIRST
Browse from start of queue.
MQC.MQGMO_BROWSE_NEXT
Browse from the current position in the queue.
MQC.MQGMO_BROWSE_MSG_UNDER_CURSOR*
Browse message under browse cursor.
MQC.MQGMO_MSG_UNDER_CURSOR
Get message under browse cursor.
MQC.MQGMO_LOCK*
Lock the message that is browsed.
MQC.MQGMO_UNLOCK*
Unlock a previously locked message.
MQC.MQGMO_ACCEPT_TRUNCATED_MSG
Allow truncation of message data.
Each piece of data that is sent is known as a physical message, which can
be a complete logical message, or a segment of a longer logical message.
Each physical message usually has a different MsgId. All the segments of a
single logical message have the same groupId value and MsgSeqNumber
value, but the Offset value is different for each segment. The Offset field
gives the offset of the data in the physical message from the start of the
logical message. The segments usually have different MsgId values, because
they are individual physical messages.
Logical messages that form part of a group have the same groupId value,
but each message in the group has a different MsgSeqNumber value.
Messages in a group can also be segmented.
The following options can be used for dealing with segmented or grouped
messages:
MQC.MQGMO_LOGICAL_ORDER*
Return messages in groups, and segments of logical messages, in
logical order.
MQC.MQGMO_COMPLETE_MSG*
Retrieve only complete logical messages.
MQC.MQGMO_ALL_MSGS_AVAILABLE*
Retrieve messages from a group only when all the messages in the
group are available.
MQC.MQGMO_ALL_SEGMENTS_AVAILABLE*
Retrieve the segments of a logical message only when all the
segments in the group are available.
waitInterval
public int waitInterval
The maximum time (in milliseconds) that an MQQueue.get call waits for a
suitable message to arrive (used in conjunction with
MQC.MQGMO_WAIT). A value of MQC.MQWI_UNLIMITED indicates
that an unlimited wait is required.
Constructors
MQGetMessageOptions
public MQGetMessageOptions()
Construct a new MQGetMessageOptions object with options set to
MQC.MQGMO_NO_WAIT, a wait interval of zero, and a blank resolved
queue name.
MQManagedObject
java.lang.Object
│
└─ com.ibm.mq.MQManagedObject
Variables
alternateUserId
public String alternateUserId
The alternate user id (if any) specified when this resource was opened.
Setting this attribute has no effect.
name public String name
The name of this resource (either the name supplied on the access method,
or the name allocated by the queue manager for a dynamic queue). Setting
this attribute has no effect.
openOptions
public int openOptions
The options specified when this resource was opened. Setting this attribute
has no effect.
isOpen
public boolean isOpen
Indicates whether this resource is currently open. This attribute is
deprecated and setting it has no effect.
connectionReference
public MQQueueManager connectionReference
The queue manager to which this resource belongs. Setting this attribute
has no effect.
closeOptions
public int closeOptions
Set this attribute to control the way the resource is closed. The default
value is MQC.MQCO_NONE, and this is the only permissible value for all
resources other than permanent dynamic queues, and temporary dynamic
queues that are being accessed by the objects that created them. For these
queues, the following additional values are permissible:
MQC.MQCO_DELETE
Delete the queue if there are no messages.
MQC.MQCO_DELETE_PURGE
Delete the queue, purging any messages on it.
Methods
getDescription
public String getDescription()
Throws MQException.
If this method is called after the resource has been closed, an MQException
is thrown.
inquire
public void inquire(int selectors[],
int intAttrs[],
byte charAttrs[])
throws MQException.
The attributes to be queried are specified in the selectors array. Refer to the
MQSeries Application Programming Reference for details of the permissible
selectors and their corresponding integer values.
Note that many of the more common attributes can be queried using the
getXXX() methods defined in MQManagedObject, MQQueue,
MQQueueManager, and MQProcess.
Parameters
selectors
Integer array identifying the attributes with values to be inquired
on.
intAttrs
The array in which the integer attribute values are returned.
Integer attribute values are returned in the same order as the
integer attribute selectors in the selectors array.
charAttrs
The buffer in which the character attributes are returned,
concatenated. Character attributes are returned in the same order
as the character attribute selectors in the selectors array. The length
of each attribute string is fixed for each attribute.
throws MQException.
The attributes to be set are specified in the selectors array. Refer to the
MQSeries Application Programming Reference for details of the permissible
selectors and their corresponding integer values.
Note that some queue attributes can be set using the setXXX() methods
defined in MQQueue.
Parameters
selectors
Integer array identifying the attributes with values to be set.
intAttrs
The array of integer attribute values to be set. These values must
be in the same order as the integer attribute selectors in the
selectors array.
charAttrs
The buffer in which the character attributes to be set are
concatenated. These values must be in the same order as the
character attribute selectors in the selectors array. The length of
each character attribute is fixed.
throws MQException.
Close the object. No further operations against this resource are permitted
after this method has been called. The behavior of the close method may
be altered by setting the closeOptions attribute.
MQMessage
java.lang.Object
│
└─ com.ibm.mq.MQMessage
MQMessage represents both the message descriptor and the data for an MQSeries
message. There is group of readXXX methods for reading data from a message,
and a group of writeXXX methods for writing data into a message. The format of
numbers and strings used by these read and write methods can be controlled by
the encoding and characterSet member variables. The remaining member variables
contain control information that accompanies the application message data when a
message travels between sending and receiving applications. The application can
set values into the member variable before putting a message to a queue and can
read values after retrieving a message from a queue.
Variables
report public int report
A report is a message about another message. This member variable
enables the application sending the original message to specify which
report messages are required, whether the application message data is to
be included in them, and also how the message and correlation identifiers
in the report or reply are to be set. Any, all or none of the following report
types can be requested:
v Exception
v Expiration
v Confirm on arrival
v Confirm on delivery
For each type, only one of the three corresponding values below should be
specified, depending on whether the application message data is to be
included in the report message.
Note: Values marked with ** in the following list are not supported by
MVS queue managers and should not be used if your application is
likely to access an MVS queue manager, regardless of the platform
on which the application is running.
You can specify one of the following to control how the correlation Id of
the report or reply message is to be set:
v MQC.MQRO_COPY_MSG_ID_TO_CORREL_ID
v MQC.MQRO_PASS_CORREL_ID
You can specify one of the following to control the disposition of the
original message when it cannot be delivered to the destination queue:
v MQC.MQRO_DEAD_LETTER_Q
v MQC.MQRO_DISCARD_MSG **
You can specify one or both of the following to request that the receiving
application send a positive action or negative action report message.
v MQRO_PAN
v MQRO_NAN
messageType
public int messageType
Indicates the type of the message. The following values are currently
defined by the system:
v MQC.MQMT_DATAGRAM
v MQC.MQMT_REQUEST
v MQC.MQMT_REPLY
v MQC.MQMT_REPORT
Note that a loss in precision can occur when converting from IEEE format
floating points to System/390 format floating points.
characterSet
public int characterSet
This specifies the coded character set identifier of character data in the
application message data. The behavior of the readString, readLine and
writeString methods is altered accordingly.
The default value for this field is MQC.MQCCSI_Q_MGR. If the default
value is used, CharacterSet 819 (iso-8859-1/latin/ibm819) is assumed. The
character set values shown in Table 13 are supported.
Table 13. Character set identifiers
characterSet Description
870 ibm870
871 ibm871
874 ibm874
875 ibm875
918 ibm918
921 ibm921
922 ibm922
930 ibm930
933 ibm933
935 ibm935
937 ibm937
939 ibm939
942 ibm942
948 ibm948
949 ibm949
950 ibm950 / Big 5 Traditional Chinese
964 ibm964 / CNS 11643 Traditional Chinese
970 ibm970
1006 ibm1006
1025 ibm1025
1026 ibm1026
1097 ibm1097
1098 ibm1098
1112 ibm1112
1122 ibm1122
1123 ibm1123
1124 ibm1124
1381 ibm1381
1383 ibm1383
2022 JIS
932 PC Japanese
954 EUCJIS
1250 Windows Latin 2
1251 Windows Cyrillic
1252 Windows Latin 1
1253 Windows Greek
1254 Windows Turkish
1255 Windows Hebrew
1256 Windows Arabic
1257 Windows Baltic
1258 Windows Vietnamese
33722 ibm33722
5601 ksc-5601 Korean
1200 Unicode
1208 UTF-8
Constructors
MQMessage
public MQMessage()
Create a new message with default message descriptor information and an
empty message buffer.
Methods
getTotalMessageLength
public int getTotalMessageLength()
The total number of bytes in the message as stored on the message queue
from which this message was retrieved (or attempted to be retrieved).
When an MQQueue.get() method fails with a message-truncated error
code, this method tells you the total size of the message on the queue.
See also “MQQueue.get” on page 133.
getMessageLength
public int getMessageLength
Throws IOException.
Throws MQException.
Throws IOException.
Move the cursor to the absolute position in the message buffer given by
pos. Subsequent reads and writes will act at this position in the buffer.
Throws IOException.
Move the cursor to the absolute position in the message buffer. This
method is a synonym for seek(), and is provided for cross-language
compatibility with the other MQSeries APIs.
getDataOffset
public int getDataOffset()
Throws IOException.
Return the current cursor position within the message data (the point at
which read and write operations take effect).
clearMessage
public void clearMessage()
Throws IOException.
Discard any data in the message buffer and set the data offset back to zero.
getVersion
public int getVersion()
Returns the version of the structure in use.
resizeBuffer
public void resizeBuffer(int size)
Throws IOException.
A hint to the MQMessage object about the size of buffer that may be
required for subsequent get operations. If the message currently contains
message data, and the new size is less than the current size, the message
data is truncated.
readBoolean
public boolean readBoolean()
Throws IOException.
Read a (signed) byte from the current position in the message buffer.
Read a Unicode character from the current position in the message buffer.
readDouble
public double readDouble()
Read a double from the current position in the message buffer. The value
of the encoding member variable determines the behavior of this method.
Read a float from the current position in the message buffer. The value of
the encoding member variable determines the behavior of this method.
Fill the byte array b with data from the message buffer.
readFully
public void readFully(byte b[],
int off,
int len)
Fill len elements of the byte array b with data from the message buffer,
starting at offset off.
Read an integer from the current position in the message buffer. The value
of the encoding member variable determines the behavior of this method.
Throws IOException.
Read a long from the current position in the message buffer. The value of
the encoding member variable determines the behavior of this method.
Read an object from the message buffer. The class of the object, the
signature of the class, and the value of the non-transient and non-static
fields of the class are all read.
Throws IOException.
Read a UTF string, prefixed by a 2-byte length field, from the current
position in the message buffer.
readUnsignedByte
public int readUnsignedByte()
Read an unsigned byte from the current position in the message buffer.
readUnsignedShort
public int readUnsignedShort()
Read an unsigned short from the current position in the message buffer.
The value of the encoding member variable determines the behavior of this
method.
Parameters:
length The number of characters to read (which may differ from the
number of bytes according to the codeset, because some codesets
use more than one byte per character).
readDecimal2
public short readDecimal2()
Throws IOException.
Throws IOException.
Write an array of bytes into the message buffer at the current position.
write
public void write(byte b[],
int off,
int len)
Throws IOException.
Write a series of bytes into the message buffer at the current position. len
bytes will be written, taken from offset off in the array b.
writeBoolean
public void writeBoolean(boolean v)
Throws IOException.
Throws IOException.
Throws IOException.
Writes out the string to the message buffer as a sequence of bytes. Each
character in the string is written out in sequence by discarding its high
eight bits.
writeChar
public void writeChar(int v)
Throws IOException.
Write a Unicode character into the message buffer at the current position.
writeChars
public void writeChars(String s)
Throws IOException.
Throws IOException
Write a double into the message buffer at the current position. The value of
the encoding member variable determines the behavior of this method.
Throws IOException.
Write a float into the message buffer at the current position. The value of
the encoding member variable determines the behavior of this method.
Throws IOException.
Write an integer into the message buffer at the current position. The value
of the encoding member variable determines the behavior of this method.
Throws IOException.
Throws IOException.
Write a long into the message buffer at the current position. The value of
the encoding member variable determines the behavior of this method.
Throws IOException.
Throws IOException.
Write the specified object to the message buffer. The class of the object, the
signature of the class, and the values of the non-transient and non-static
fields of the class and all its supertypes are all written.
Throws IOException.
Write a short into the message buffer at the current position. The value of
the encoding member variable determines the behavior of this method.
Throws IOException.
Throws IOException.
Write a 2-byte packed decimal format number into the message buffer at
the current position. The value of the encoding member variable
determines the behavior of this method.
Parameters
v can be in the range -999 to 999.
writeDecimal4
public void writeDecimal4(int v)
Throws IOException.
Write a 4-byte packed decimal format number into the message buffer at
the current position. The value of the encoding member variable
determines the behavior of this method.
Parameters
v can be in the range -9999999 to 9999999.
Throws IOException.
Write an 8-byte packed decimal format number into the message buffer at
the current position. The value of the encoding member variable
determines the behavior of this method.
Parameters:
v can be in the range -999999999999999 to 999999999999999.
writeUTF
public void writeUTF(String str)
Throws IOException.
Write a UTF string, prefixed by a 2-byte length field, into the message
buffer at the current position.
writeString
public void writeString(String str)
Throws IOException.
Write a string into the message buffer at the current position, converting it
to the codeset identified by the characterSet member variable.
MQMessageTracker
java.lang.Object
│
└─ com.ibm.mq.MQMessageTracker
Note: You can use this class only when connected to an MQSeries Version 5 (or
higher) queue manager.
Variables
feedback
public int feedback
This is used with a message of type MQC.MQMT_REPORT to indicate the
nature of the report. The following feedback codes are defined by the
system:
v MQC.MQFB_EXPIRATION
v MQC.MQFB_COA
v MQC.MQFB_COD
v MQC.MQFB_QUIT
v MQC.MQFB_PAN
v MQC.MQFB_NAN
v MQC.MQFB_DATA_LENGTH_ZERO
v MQC.MQFB_DATA_LENGTH_NEGATIVE
v MQC.MQFB_DATA_LENGTH_TOO_BIG
v MQC.MQFB_BUFFER_OVERFLOW
v MQC.MQFB_LENGTH_OFF_BY_ONE
v MQC.MQFB_IIH_ERROR
MQPoolServices
java.lang.Object
│
└─ com.ibm.mq.MQPoolServices
Constructors
MQPoolServices
public MQPoolServices()
Methods
addMQPoolServicesEventListener
public void addMQPoolServicesEventListener
(MQPoolServicesEventListener listener)
Remove an MQPoolServicesEventListener.
getTokenCount
public int getTokenCount()
MQPoolServicesEvent
java.lang.Object
│
└─ java.util.EventObject
│
└─ com.ibm.mq.MQPoolServicesEvent
Variables
TOKEN_ADDED
public static final int TOKEN_ADDED
The event ID used when an MQPoolToken is added to the set.
TOKEN_REMOVED
public static final int TOKEN_REMOVED
The event ID used when an MQPoolToken is removed from the set.
DEFAULT_POOL_CHANGED
public static final int DEFAULT_POOL_CHANGED
The event ID used when the default ConnectionManager changes.
ID protected int ID
The event ID. Valid values are:
TOKEN_ADDED
TOKEN_REMOVED
DEFAULT_POOL_CHANGED
token protected MQPoolToken token
The token. When the event ID is DEFAULT_POOL_CHANGED, this is
null.
Constructors
MQPoolServicesEvent
public MQPoolServicesEvent(Object source, int eid, MQPoolToken token)
MQPoolToken
java.lang.Object
│
└─ com.ibm.mq.MQPoolToken
Constructors
MQPoolToken
public MQPoolToken()
MQProcess
java.lang.Object
│
└─ com.ibm.mq.MQManagedObject
│
└─ com.ibm.mq.MQProcess
Constructors
MQProcess
public MQProcess(MQQueueManager qMgr,
String processName,
int openOptions,
String queueManagerName,
String alternateUserId)
throws MQException
Methods
getApplicationId
public String getApplicationId()
A character string that identifies the application to be started. This
information is for use by a trigger monitor application that processes
messages on the initiation queue; the information is sent to the initiation
queue as part of the trigger message.
Throws MQException if you call this method after you have closed the
process.
getApplicationType
public int getApplicationType()
Throws MQException (see page 93).
This identifies the nature of the program to be started in response to the
receipt of a trigger message. The application type can take any value, but
the following values are recommended for standard types:
v MQC.MQAT_AIX
v MQC.MQAT_CICS
v MQC.MQAT_DOS
v MQC.MQAT_IMS
v MQC.MQAT_MVS
v MQC.MQAT_OS2
v MQC.MQAT_OS400
v MQC.MQAT_UNIX
v MQC.MQAT_WINDOWS
v MQC.MQAT_WINDOWS_NT
v MQC.MWQAT_USER_FIRST (lowest value for user-defined application
type)
Throws MQException.
Throws MQException.
Throws MQException.
MQPutMessageOptions
java.lang.Object
│
└─ com.ibm.mq.MQPutMessageOptions
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 “Version 5 extensions operating in other environments” on page 75 for
details.
Variables
options
public int options
Options that control the action of MQQueue.put. Any or none of the
following values can be specified. If more than one option is required the
values can be added together or combined using the bitwise OR operator.
MQC.MQPMO_SYNCPOINT
Put a message with syncpoint control. The message is not visible
outside the unit of work until the unit of work is committed. If the
unit of work is backed out, the message is deleted.
MQC.MQPMO_NO_SYNCPOINT
Put a message without syncpoint control. Note that, if the
syncpoint control option is not specified, a default of ‘no
syncpoint’ is assumed. This applies for all supported platforms,
including OS/390.
MQC.MQPMO_NO_CONTEXT
No context is to be associated with the message.
MQC.MQPMO_DEFAULT_CONTEXT
Associate default context with the message.
MQC.MQPMO_SET_IDENTITY_CONTEXT
Set identity context from the application.
MQC.MQPMO_SET_ALL_CONTEXT
Set all context from the application.
MQC.MQPMO_FAIL_IF_QUIESCING
Fail if the queue manager is quiescing.
MQC.MQPMO_NEW_MSG_ID*
Generate a new message id for each sent message.
MQC.MQPMO_NEW_CORREL_ID*
Generate a new correlation id for each sent message.
MQC.MQPMO_LOGICAL_ORDER*
Put logical messages and segments in message groups into their
logical order.
Constructors
MQPutMessageOptions
public MQPutMessageOptions()
Construct a new MQPutMessageOptions object with no options set, and a
blank resolvedQueueName and resolvedQueueManagerName.
MQQueue
java.lang.Object
│
└─ com.ibm.mq.MQManagedObject
│
└─ com.ibm.mq.MQQueue
MQQueue provides inquire, set, put, and get operations for MQSeries queues. The
inquire and set capabilities are inherited from MQ.MQManagedObject.
Constructors
MQQueue
public MQQueue(MQQueueManager qMgr, String queueName, int openOptions,
String queueManagerName, String dynamicQueueName,
String alternateUserId )
throws MQException
Methods
get
public synchronized void get(MQMessage message,
MQGetMessageOptions getMessageOptions,
int MaxMsgSize)
Throws MQException.
Throws MQException.
Retrieves a message from the queue, regardless of the size of the message.
For large messages, the get method may have to issue two calls to
MQSeries on your behalf, one to establish the required buffer size and one
to get the message data itself.
Parameters
MQMessage
An input/output parameter containing the message descriptor
information and the returned message data.
Throws MQException.
Modifications to the MQMessage object after the put has completed do not
affect the actual message on the MQSeries queue.
puts two messages. The first contains ″a″ and the second ″ab″.
Parameters
MQMessage
Message Buffer containing the Message Descriptor data and
message to be sent.
Note: All the following methods throw MQException if you call the method after
you have closed the queue.
getCreationDateTime
public GregorianCalendar getCreationDateTime()
Throws MQException.
Throws MQException.
Throws MQException.
Throws MQException.
The maximum number of messages that can exist on the queue at any one
time. An attempt to put a message to a queue that already contains this
many messages fails with reason code MQException.MQRC_Q_FULL.
getMaximumMessageLength
public int getMaximumMessageLength()
Throws MQException.
This is the maximum length of the application data that can exist in each
message on this queue. An attempt to put a message larger than this value
fails with reason code MQException.MQRC_MSG_TOO_BIG_FOR_Q.
getOpenInputCount
public int getOpenInputCount()
Throws MQException.
The number of handles that are currently valid for removing messages
from the queue. This is the total number of such handles known to the
local queue manager, not just those created by the MQSeries classes for
Java (using accessQueue).
getOpenOutputCount
public int getOpenOutputCount()
Throws MQException.
The number of handles that are currently valid for adding messages to the
queue. This is the total number of such handles known to the local queue
manager, not just those created by the MQSeries classes for Java (using
accessQueue).
Throws MQException.
Indicates whether the queue can be opened for input multiple times.
Returns
One of the following:
v MQC.MQQA_SHAREABLE
v MQC.MQQA_NOT_SHAREABLE
getInhibitPut
public int getInhibitPut()
Throws MQException.
Indicates whether or not put operations are allowed for this queue.
Returns
One of the following:
v MQC.MQQA_PUT_INHIBITED
v MQC.MQQA_PUT_ALLOWED
setInhibitPut
public void setInhibitPut(int inhibit)
Throws MQException.
Controls whether or not put operations are allowed for this queue. The
permissible values are:
v MQC.MQQA_PUT_INHIBITED
v MQC.MQQA_PUT_ALLOWED
getInhibitGet
public int getInhibitGet()
Throws MQException.
Indicates whether or not get operations are allowed for this queue.
Returns
The possible values are:
v MQC.MQQA_GET_INHIBITED
v MQC.MQQA_GET_ALLOWED
setInhibitGet
public void setInhibitGet(int inhibit)
Throws MQException.
Controls whether or not get operations are allowed for this queue. The
permissible values are:
v MQC.MQQA_GET_INHIBITED
v MQC.MQQA_GET_ALLOWED
Throws MQException.
Throws MQException.
Throws MQException.
The free-format data that the queue manager inserts into the trigger
message when a message arriving on this queue causes a trigger message
to be written to the initiation queue.
setTriggerData
public void setTriggerData(String data)
Throws MQException.
Sets the free-format data that the queue manager inserts into the trigger
message when a message arriving on this queue causes a trigger message
to be written to the initiation queue. The maximum permissible length of
the string is given by MQC.MQ_TRIGGER_DATA_LENGTH.
getTriggerDepth
public int getTriggerDepth()
Throws MQException.
Throws MQException.
Sets the number of messages that have to be on the queue before a trigger
message is written when trigger type is set to MQC.MQTT_DEPTH.
Throws MQException.
This is the message priority below which messages do not contribute to the
generation of trigger messages (that is, the queue manager ignores these
messages when deciding whether a trigger should be generated). A value
of zero causes all messages to contribute to the generation of trigger
messages.
setTriggerMessagePriority
public void setTriggerMessagePriority(int priority)
Throws MQException.
Sets the message priority below which messages do not contribute to the
generation of trigger messages (that is, the queue manager ignores these
messages when deciding whether a trigger should be generated). A value
of zero causes all messages to contribute to the generation of trigger
messages.
getTriggerType
public int getTriggerType()
Throws MQException.
Throws MQException.
Sets the conditions under which trigger messages are written as a result of
messages arriving on this queue. The possible values are:
v MQC.MQTT_NONE
v MQC.MQTT_FIRST
v MQC.MQTT_EVERY
v MQC.MQTT_DEPTH
close
public synchronized void close()
Throws MQException.
MQQueueManager
java.lang.Object
│
└─ com.ibm.mq.MQManagedObject
│
└─ com.ibm.mq.MQQueueManager
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” on page 73 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.
Note: When using MQSeries 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.
If the queue manager name is left blank (null or ″″), a connection is made
to the default queue manager.
Throws MQException.
Throws MQException.
This method requires a JVM at Java 2 v1.3 or later, with JAAS 1.0 or later
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:
v MQC.MQCNO_FASTPATH_BINDING for fast bindings *.
v MQC.MQCNO_STANDARD_BINDING for normal bindings.
MQQueueManager
public MQQueueManager(String queueManagerName,
int options,
MQConnectionManager cxManager)
Throws MQException.
Throws MQException.
This method requires a JVM at Java 2 v1.3 or later, with JAAS 1.0 or later
installed.
Throws MQException.
Throws MQException.
This method requires a JVM at Java 2 v1.3 or later, with JAAS 1.0 or later
installed.
Methods
getCharacterSet
public int getCharacterSet()
Throws MQException.
Throws MQException if you call this method after disconnecting from the
queue manager.
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.
Throws MQException if you call this method after disconnecting from the
queue manager.
Returns
One of the MQC.MQCMDL_LEVEL_xxx constants
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.
getMaximumPriority
public int getMaximumPriority()
Throws MQException.
Throws MQException if you call this method after disconnecting from the
queue manager.
getSyncpointAvailability
public int getSyncpointAvailability()
Throws MQException.
Returns
v MQC.MQSP_AVAILABLE if syncpointing is available.
v MQC.MQSP_NOT_AVAILABLE if syncpointing is not available.
Throws MQException if you call this method after disconnecting from the
queue manager.
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.
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.
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.
Throws MQException.
Parameters
queueName
Name of queue to open.
openOptions
Options that control the opening of the queue. Valid options are:
MQC.MQOO_BROWSE
Open to browse message.
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_OUTPUT
Open to put messages.
MQC.MQOO_INQUIRE
Open for inquiry - required if you wish to query
properties.
MQC.MQOO_SET
Open to set attributes.
MQC.MQOO_SAVE_ALL_CONTEXT
Save context when message retrieved*.
MQC.MQOO_SET_IDENTITY_CONTEXT
Allows identity context to be set.
MQC.MQOO_SET_ALL_CONTEXT
Allows all context to be set.
MQC.MQOO_ALTERNATE_USER_AUTHORITY
Validate with the specified user identifier.
MQC.MQOO_FAIL_IF_QUIESCING
Fail if the queue manager is quiescing.
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
Throws MQException.
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
Parameters
processName
The name of the process to open.
openOptions
Options that control the opening of the process.
Throws MQException.
Parameters
litems The items to be included in the distribution list.
openOptions
Options that control the opening of the distribution list.
Parameters
litems The items to be included in the distribution list.
openOptions
Options that control the opening of the distribution list.
MQSimpleConnectionManager
java.lang.Object com.ibm.mq.MQConnectionManager
│ │
└─ com.ibm.mq.MQSimpleConnectionManager
Connections are destroyed (by a separate thread) when they are unused for a
specified period, or when there are more than a specified number of unused
connections in the pool. You can specify the timeout period and the maximum
number of unused connections.
Variables
MODE_AUTO
public static final int MODE_AUTO. See “setActive”.
MODE_ACTIVE
public static final int MODE_ACTIVE. See “setActive”.
MODE_INACTIVE
public static final int MODE_INACTIVE. See “setActive”.
Constructors
MQSimpleConnectionManager
public MQSimpleConnectionManager()
Constructs an MQSimpleConnectionManager.
Methods
setActive
public void setActive(int mode)
Sets the active mode of the connection pool.
Parameters
mode The required active mode of the connection pool. Valid values are:
MODE_AUTO
The connection pool is active while the Connection
Manager is the default Connection Manager and there is at
least one token in the set of MQPoolTokens held by
MQEnvironment. This is the default mode.
MODE_ACTIVE
The connection pool is always active. When
MQQueueManager.disconnect() is called, the underlying
connection is pooled, and potentially reused the next time
that an MQQueueManager object is constructed.
MQC
public interface MQC
extends Object
The MQC interface defines all the constants used by the MQ Java programming
interface (except for completion code constants and error code constants). To refer
to one of these constants from within your programs, prefix the constant name
with ″MQC.″. For example, you can set the close options for a queue as follows:
MQQueue queue;
...
queue.closeOptions = MQC.MQCO_DELETE; // delete the
// queue when
// it is closed
...
Completion code and error code constants are defined in the MQException class.
See “MQException” on page 93.
MQPoolServicesEventListener
public interface MQPoolServicesEventListener
extends Object
Methods
tokenAdded
public void tokenAdded(MQPoolServicesEvent event)
MQConnectionManager
This is a private interface that cannot be implemented by applications. MQSeries
classes for Java supplies an implementation of this interface
(MQSimpleConnectionManager), which you can specify on the MQQueueManager
constructor, or through MQEnvironment.setDefaultConnectionManager.
MQReceiveExit
public interface MQReceiveExit
extends Object
The receive exit interface allows you to examine and possibly alter the data
received from the queue manager by the MQSeries classes for Java.
Note: This interface does not apply when connecting directly to MQSeries in
bindings mode.
To provide your own receive exit, define a class that implements this interface.
Create a new instance of your class and assign the MQEnvironment.receiveExit
variable to it before constructing your MQQueueManager object. For example:
// in MyReceiveExit.java
class MyReceiveExit implements MQReceiveExit {
// you must provide an implementation
// of the receiveExit method
public byte[] receiveExit(
MQChannelExit channelExitParms,
MQChannelDefinition channelDefinition,
byte[] agentBuffer)
{
// your exit code goes here...
}
}
// in your main program...
MQEnvironment.receiveExit = new MyReceiveExit();
... // other initialization
MQQueueManager qMgr = new MQQueueManager("");
Methods
receiveExit
public abstract byte[] receiveExit(MQChannelExit channelExitParms,
MQChannelDefinition channelDefinition,
byte agentBuffer[])
The receive exit method that your class must provide. This method will be
invoked whenever the MQSeries classes for Java receives some data from
the queue manager.
Parameters
channelExitParms
Contains information regarding the context in which the exit is
being invoked. The exitResponse member variable is an output
parameter that you use to tell the MQSeries classes for Java what
action to take next. See “MQChannelExit” on page 82 for further
details.
channelDefinition
Contains details of the channel through which all communications
with the queue manager take place.
agentBuffer
If the channelExitParms.exitReason is
MQChannelExit.MQXR_XMIT, agentBuffer contains the data
received from the queue manager; otherwise agentBuffer is null.
If the exit response code (in channelExitParms) is set so that the MQSeries
classes for Java can now process the data (MQXCC_OK), your receive exit
method must return the data to be processed. The simplest receive exit,
therefore, consists of the single line ″return agentBuffer;″.
See also:
v “MQC” on page 152
v “MQChannelDefinition” on page 80
MQSecurityExit
public interface MQSecurityExit
extends Object
The security exit interface allows you to customize the security flows that occur
when an attempt is made to connect to a queue manager.
Note: This interface does not apply when connecting directly to MQSeries in
bindings mode.
To provide your own security exit, define a class that implements this interface.
Create a new instance of your class and assign the MQEnvironment.securityExit
variable to it before constructing your MQQueueManager object. For example:
// in MySecurityExit.java
class MySecurityExit implements MQSecurityExit {
// you must provide an implementation
// of the securityExit method
public byte[] securityExit(
MQChannelExit channelExitParms,
MQChannelDefinition channelDefinition,
byte[] agentBuffer)
{
// your exit code goes here...
}
}
// in your main program...
MQEnvironment.securityExit = new MySecurityExit();
... // other initialization
MQQueueManager qMgr = new MQQueueManager("");
Methods
securityExit
public abstract byte[] securityExit(MQChannelExit channelExitParms,
MQChannelDefinition channelDefinition,
byte agentBuffer[])
Parameters
channelExitParms
Contains information regarding the context in which the exit is
being invoked. The exitResponse member variable is an output
parameter that you use to tell the MQSeries Client for Java what
action to take next. See the “MQChannelExit” on page 82 for
further details.
channelDefinition
Contains details of the channel through which all communications
with the queue manager take place.
agentBuffer
If the channelExitParms.exitReason is
MQChannelExit.MQXR_SEC_MSG, agentBuffer contains the
security message received from the queue manager; otherwise
agentBuffer is null.
See also:
v “MQC” on page 152
v “MQChannelDefinition” on page 80
MQSendExit
public interface MQSendExit
extends Object
The send exit interface allows you to examine and possibly alter the data sent to
the queue manager by the MQSeries Client for Java.
Note: This interface does not apply when connecting directly to MQSeries in
bindings mode.
To provide your own send exit, define a class that implements this interface. Create
a new instance of your class and assign the MQEnvironment.sendExit variable to it
before constructing your MQQueueManager object. For example:
// in MySendExit.java
class MySendExit implements MQSendExit {
// you must provide an implementation of the sendExit method
public byte[] sendExit(
MQChannelExit channelExitParms,
MQChannelDefinition channelDefinition,
byte[] agentBuffer)
{
// your exit code goes here...
}
}
// in your main program...
MQEnvironment.sendExit = new MySendExit();
... // other initialization
MQQueueManager qMgr = new MQQueueManager("");
Methods
sendExit
public abstract byte[] sendExit(MQChannelExit channelExitParms,
MQChannelDefinition channelDefinition,
byte agentBuffer[])
The send exit method that your class must provide. This method is
invoked whenever the MQSeries classes for Java wishes to transmit some
data to the queue manager.
Parameters
channelExitParms
Contains information regarding the context in which the exit is
being invoked. The exitResponse member variable is an output
parameter that you use to tell the MQSeries classes for Java what
action to take next. See “MQChannelExit” on page 82 for further
details.
channelDefinition
Contains details of the channel through which all communications
with the queue manager take place.
agentBuffer
If the channelExitParms.exitReason is
MQChannelExit.MQXR_XMIT, agentBuffer contains the data to be
transmitted to the queue manager; otherwise agentBuffer is null.
See also:
v “MQC” on page 152
v “MQChannelDefinition” on page 80
ManagedConnection
public interface javax.resource.spi.ManagedConnection
Note: Normally, applications do not use this class; it is intended for use by
implementations of ConnectionManager.
Methods
getConnection
public Object getConnection(javax.security.auth.Subject subject,
ConnectionRequestInfo cxRequestInfo)
Throws ResourceException.
Throws ResourceException.
Throws ResourceException.
Closes all open connection handles, and resets the physical connection to
an initial state ready to be pooled. Any pending local transaction is rolled
back. For more details, see “getLocalTransaction” on page 162.
associateConnection
public void associateConnection(Object connection)
Throws ResourceException.
MQSeries classes for Java does not currently support this method. A
javax.resource.NotSupportedException is thrown.
Throws ResourceException.
MQSeries classes for Java does not currently support this method. A
javax.resource.NotSupportedException is thrown.
getLocalTransaction
public LocalTransaction getLocalTransaction()
| Throws ResourceException.
MQSeries classes for Java does not currently support this method. A
javax.resource.NotSupportedException is thrown.
Throws ResourceException.
Gets the meta data information for the underlying Queue Manager. See
“ManagedConnectionMetaData” on page 166.
Throws ResourceException.
MQSeries classes for Java does not currently use the log writer. See
“MQException.log” on page 93 for more information about logging.
getLogWriter
public java.io.PrintWriter getLogWriter()
Throws ResourceException.
MQSeries classes for Java does not currently use the log writer. See
“MQException.log” on page 93 for more information about logging.
ManagedConnectionFactory
public interface javax.resource.spi.ManagedConnectionFactory
Methods
createConnectionFactory
public Object createConnectionFactory()
Throws ResourceException.
Throws ResourceException.
Throws ResourceException.
Throws ResourceException.
Throws ResourceException.
MQSeries classes for Java does not currently use the log writer. See
“MQException.log” on page 93 for more information about logging.
getLogWriter
public java.io.PrintWriter getLogWriter()
Throws ResourceException.
MQSeries classes for Java does not currently use the log writer. See
“MQException.log” on page 93 for more information about logging.
hashCode
public int hashCode()
ManagedConnectionMetaData
public interface javax.resource.spi.ManagedConnectionMetaData
Note: Normally, applications do not use this class; it is intended for use by
implementations of ConnectionManager.
A ConnectionManager can use this class to retrieve meta data that is related to an
underlying physical connection to a Queue Manager. An implementation of this
class is returned from ManagedConnection.getMetaData().
Methods
getEISProductName
public String getEISProductName()
Throws ResourceException.
Throws ResourceException.
Returns a string that describes the command level of the MQSeries Queue
Manager to which the ManagedConnection is connected.
getMaxConnections
public int getMaxConnections()
Throws ResourceException.
Returns 0.
getUserName
public String getUserName()
Throws ResourceException.
The generic JMS model is based around the following interfaces that are defined in
Sun’s javax.jms package:
Connection
Provides access to the underlying transport, and is used to create Sessions.
Session
Provides a context for producing and consuming messages, including the
methods used to create MessageProducers and MessageConsumers.
MessageProducer
Used to send messages.
MessageConsumer
Used to receive messages.
In MQSeries terms:
Connection
Provides a scope for temporary queues. Also, it provides a place to hold
the parameters that control how to connect to MQSeries. Examples of these
parameters are the name of the queue manager, and the name of the
remote host if you use the MQSeries Java client connectivity.
Session
Contains an HCONN and therefore defines a transactional scope.
MessageProducer and MessageConsumer
Contain an HOBJ that defines a particular queue for writing to, or reading
from.
These are known as “administered objects”, that is, objects that can be built using a
vendor-supplied administration tool and can be stored in a JNDI namespace. A
JMS application can retrieve these objects from the namespace and use them
without needing to know which vendor provided the implementation.
Building a connection
Connections are not created directly, but are built using a connection factory.
Factory objects can be stored in a JNDI namespace, thus insulating the JMS
application from provider-specific information. Details of how to create and store
factory objects are in “Chapter 5. Using the MQ JMS administration tool” on
page 31.
If you do not have a JNDI namespace available, see “Creating factories at runtime”
on page 171.
where:
icf defines a factory class for the initial context
url defines a context specific URL
For more details about JNDI usage, see Sun’s JNDI documentation.
Once an initial context is obtained, objects are retrieved from the namespace by
using the lookup() method. The following code retrieves a
QueueConnectionFactory named ivtQCF from an LDAP-based namespace:
QueueConnectionFactory factory;
factory = (QueueConnectionFactory)ctx.lookup("cn=ivtQCF");
(You can omit the com.ibm.mq.jms. prefix if you import the com.ibm.mq.jms
package instead.)
A connection created from the above factory uses the Java bindings to connect to
the default queue manager on the local machine. The set methods shown in
Table 14 can be used to customize the factory with MQSeries specific information.
The contents of the connection factory object determine which transport to use.
“Chapter 5. Using the MQ JMS administration tool” on page 31 describes how to
define a factory object for use with client or bindings transport.
The following code fragment illustrates how you can define the transport within
an application:
String HOSTNAME = "machine1";
String QMGRNAME = "machine1.QM1";
String CHANNEL = "SYSTEM.DEF.SVRCONN";
Obtaining a session
Once a connection is made, use the createQueueSession method on the
QueueConnection to obtain a session.
2. However, client transport is not supported on the z/OS & OS/390 platform.
Note: A connection is thread safe, but sessions (and objects that are created from
them) are not. The recommended practice for multi-threaded applications is
to use a separate session for each thread.
Sending a message
Messages are sent using a MessageProducer. For point-to-point this is a
QueueSender that is created using the createSender method on QueueSession. A
QueueSender is normally created for a specific queue, so that all messages sent
using that sender are sent to the same destination. The destination is specified
using a Queue object. Queue objects can be either created at runtime, or built and
stored in a JNDI namespace.
Note that the name of the queue manager is omitted. This is interpreted as the
queue manager to which the owning QueueConnection is connected at the time
when the Queue object is used.
Table 15 lists the names that can be used in the name-value part of the URI. A
disadvantage of this format is that it does not support symbolic names for the
values, so where appropriate, the table also indicates ’special’ values. Note that
these special values may be subject to change. (See “Setting properties with the
‘set’ method” for an alternative method to set properties.)
Table 15. Property names for queue URIs
Property Description Values
expiry Lifetime of the message in 0 for unlimited, positive integers
milliseconds for timeout (ms)
priority Priority of the message 0 through 9, -1=QDEF, -2=APP
persistence Whether the message should be 1=non-persistent, 2=persistent,
’hardened’ to disk -1=QDEF, -2=APP
CCSID Character set of the destination integers - valid values listed in
base MQSeries documentation
targetClient Whether the receiving application 0=JMS, 1=MQ
is JMS compliant or not
encoding How to represent numeric fields An integer value as described in
the base MQSeries documentation
QDEF - a special value that means the property should be determined by the
configuration of the MQSeries queue.
APP - a special value that means the JMS application can control this property.
Once the Queue object is obtained (either using createQueue as above or from
JNDI), it must be passed into the createSender method to create a QueueSender:
QueueSender queueSender = session.createSender(ioQueue);
The resulting queueSender object is used to send messages by using the send
method:
queueSender.send(outMessage);
The following code fragment shows the setting of a queue property with a set
method.
com.ibm.mq.jms.MQQueue q1 = new com.ibm.mq.jms.MQQueue();
q1.setBaseQueueManagerName("HOST1.QM1");
q1.setBaseQueueName("Q1");
q1.setPersistence(DeliveryMode.NON_PERSISTENT);
q1.setPriority(5);
Message types
JMS provides several message types, each of which embodies some knowledge of
its content. To avoid referencing the vendor-specific class names for the message
types, methods are provided on the Session object for message creation.
Details of these types are in “Chapter 14. JMS interfaces and classes” on page 227.
Receiving a message
Messages are received by using a QueueReceiver. This is created from a Session by
using the createReceiver() method. This method takes a Queue parameter that
defines where the messages are received from. See “Sending a message” on
page 173 for details of how to create a Queue object.
The receive methods return a message of the appropriate type. For example, if a
TextMessage is put on a queue, when the message is received, the object that is
returned is an instance of TextMessage.
To extract the content from the body of the message, it is necessary to cast from
the generic Message class (which is the declared return type of the receive
methods) to the more specific subclass, such as TextMessage. If the received
message type is not known, you can use the “instanceof” operator to determine
which type it is. It is good practice always to test the message class before casting,
so that unexpected errors can be handled gracefully.
The following code illustrates the use of “instanceof”, and extraction of the content
from a TextMessage:
if (inMessage instanceof TextMessage) {
String replyString = ((TextMessage) inMessage).getText();
.
.
.
} else {
// Print error message if Message was not a TextMessage.
System.out.println("Reply message was not a TextMessage");
}
Message selectors
JMS provides a mechanism to select a subset of the messages on a queue so that
this subset is returned by a receive call. When creating a QueueReceiver, a string
can be provided that contains an SQL (Structured Query Language) expression to
determine which messages to retrieve. The selector can refer to fields in the JMS
message header as well as fields in the message properties (these are effectively
application-defined header fields). Details of the header field names, as well as the
syntax for the SQL selector, are in “Chapter 12. JMS messages” on page 191.
The following example shows how to select for a user-defined property named
myProp:
queueReceiver = session.createReceiver(ioQueue, "myProp = 'blue'");
Note: The JMS specification does not permit the selector associated with a receiver
to be changed. Once a receiver is created, the selector is fixed for the lifetime
of that receiver. This means that if you require different selectors, you must
create new receivers.
.
.
.
// In Main program (possibly of some other class)
MyClass listener = new MyClass();
queueReceiver.setMessageListener(listener);
Closing down
Garbage collection alone cannot release all MQSeries resources in a timely manner.
This is especially true if the application needs to create many short-lived JMS
objects at the Session level or lower. It is therefore important to call the close()
methods of the various classes (QueueConnection, QueueSession, QueueSender,
and QueueReceiver) when the resources are no longer required.
Handling errors
Any runtime errors in a JMS application are reported by exceptions. The majority
of methods in JMS throw JMSExceptions to indicate errors. It is good programming
practice to catch these exceptions and display them on a suitable output.
Exception listener
For asynchronous message delivery, the application code cannot catch exceptions
raised by failures to receive messages. This is because the application code does
not make explicit calls to receive() methods. To cope with this situation, it is
possible to register an ExceptionListener, which is an instance of a class that
implements the onException() method. When a serious error occurs, this method
is called with the JMSException passed as its only parameter. Further details are in
Sun’s JMS documentation.
Many of these processes are similar to those that are used for point-to-point, as
shown in the following:
Obtain a TopicConnectionFactory
The preferred way to do this is to use JNDI lookup, so that portability of
the application code is maintained. The following code initializes a JNDI
context:
String CTX_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
String INIT_URL = "ldap://server.company.com/o=company_us,c=us";
Receive subscriptions
Subscribers must be able to read the subscriptions that are delivered to them, as in
the following code:
// Retrieve the next waiting subscription
TextMessage inMsg = (TextMessage)sub.receive();
This fragment of code performs a ’get-with-wait’, which means that the receive call
will block until a message is available. Alternative versions of the receive call are
available (such as ’receiveNoWait’). For details, see “TopicSubscriber” on page 333.
Using topics
This section discusses the use of JMS Topic objects in MQSeries classes for Java
Message Service applications.
Topic names
This section describes the use of topic names within MQSeries classes for Java
Message Service.
Note: The JMS specification does not specify exact details about the use and
maintenance of topic hierarchies. Therefore, this area may well vary from
one provider to the next.
Sport
Spurs Arsenal
Figure 3. MQSeries classes for Java Message Service topic name hierarchy
In a topic name, levels in the tree are separated by the “/” character. This means
| that the “Signings” node in Figure 3 is identified by the topic name:
Sport/Football/Spurs/Signings
A powerful feature of the topic system in MQSeries classes for Java Message
Service is the use of wildcards. These allow subscribers to subscribe to more than
one topic at a time. The “*” wildcard matches zero or more characters, while the
“?” wildcard matches a single character.
There is no need to administer the topic hierarchies that you use on the broker-side
of your system explicitly. When the first publisher or subscriber on a given topic
comes into existence, the broker automatically creates the state of the topics
currently being published on, and subscribed to.
For further details on URIs and the permitted name-value pairs, see
“Sending a message” on page 173.
Note: The topic name used here is the non-URI form, and cannot include
name-value pairs. Set these by using the ’set’ methods, as described
in “Setting properties with the ‘set’ method” on page 174. The
following code uses this method to create a topic:
// Create a Topic using the default MQTopic constructor
Topic rtTopic = new MQTopic();
Subscriber options
There are a number of different ways to use JMS subscribers. This section describes
some examples of their use.
In MQ JMS V5.2, you can choose which approach to use, and configure which
queues to use.
In general, the shared queue approach gives a modest performance advantage. For
systems with a high throughput, there are also large architectural and
administrative advantages, because of the significant reduction in the number of
queues required.
In some situations, there are still good reasons for using the multiple queue
approach:
v The theoretical physical capacity for message storage is greater.
An MQSeries queue cannot hold more than 640000 messages, and in the shared
queue approach, this must be divided between all the subscribers that share the
queue. This issue is more significant for durable subscribers, because the lifetime
of a durable subscriber is usually much longer than that of a non-durable
subscriber. Therefore, more messages might accumulate for a durable subscriber.
v External administration of subscription queues is easier.
For certain application types, administrators may wish to monitor the state and
depth of particular subscriber queues. This task is much simpler when there is
one to one mapping between a subscriber and a queue.
Default configuration
The default configuration uses the following shared subscription queues:
v SYSTEM.JMS.ND.SUBSCRIPTION.QUEUE for non-durable subscriptions
v SYSTEM.JMS.D.SUBSCRIPTION.QUEUE for durable subscriptions
These are created for you when you run the MQJMS_PSQ.MQSC script.
If required, you can specify alternative physical queues. You can also change the
configuration to use the multiple queue approach.
For non-durable subscriptions, the queue name you provide should start with the
following characters:
SYSTEM.JMS.ND.
To select a shared queue approach, specify an explicit queue name, where the
named queue is the one to use for the shared queue. The queue that you specify
must already physically exist before you create the subscription.
To select the multiple queue approach, specify a queue name that ends with the *
character. Subsequently, each subscriber that is created with this queue name
creates an appropriate dynamic queue, for exclusive use by that particular
subscriber. MQ JMS uses its own internal model queue to create such queues.
Therefore, with the multiple queue approach, all required queues are created
dynamically.
When you use the multiple queue approach, you cannot specify an explicit queue
name. However, you can specify the queue prefix. This enables you to create
different subscriber queue domains. For example, you could use:
SYSTEM.JMS.ND.MYDOMAIN.*
The characters that precede the * character are used as the prefix, so that all
dynamic queues that are associated with this subscription will have queue names
that start with SYSTEM.JMS.ND.MYDOMAIN.
Therefore, the durable subscriber queue name property is set in the Topic object
(that is, at a more manageable level than TopicConnectionFactory). This enables
you to specify a number of different subscriber queue names, without needing to
re-create multiple objects starting from the TopicConnectionFactory.
You can set the durable subscriber queue name in either of the following ways:
v Use the MQ JMS administration tool (for JNDI retrieved objects) to set the
BROKERDURSUBQ property
v Use the setBrokerDurSubQueue() method in your program:
// Set the MQTopic durable subscriber queue name using
// the multi-queue approach
sportsTopic.setBrokerDurSubQueue("SYSTEM.JMS.D.FOOTBALL.*");
To select a shared queue approach, specify an explicit queue name, where the
named queue is the one to use for the shared queue. The queue that you specify
must already physically exist before you create the subscription.
To select the multiple queue approach, specify a queue name that ends with the *
character. Subsequently, each subscriber that is created with this queue name
creates an appropriate dynamic queue, for exclusive use by that particular
subscriber. MQ JMS uses its own internal model queue to create such queues.
Therefore, with the multiple queue approach, all required queues are created
dynamically.
When you use the multiple queue approach, you cannot specify an explicit queue
name. However, you can specify the queue prefix. This enables you to create
different subscriber queue domains. For example, you could use:
SYSTEM.JMS.D.MYDOMAIN.*
The characters that precede the * character are used as the prefix, so that all
dynamic queues that are associated with this subscription will have queue names
that start with SYSTEM.JMS.D.MYDOMAIN.
However, if you created a subscriber using MQ JMS V1.1, that subscriber will be
recognized when you migrate to the current level. You do not need to delete the
subscription. The subscription continues to operate using a multiple queue
approach.
The MQSeries classes for Java Message Service implementation eases this task
through the use of a “cascading close”. With this process, a call to “close” on a
There are some circumstances where this “close” procedure may not complete.
These include:
v Loss of an MQSeries client connection
v Unexpected application termination
In these circumstances, the close() is not called, and external resources remain
open on the terminated application’s behalf. The main consequences of this are:
Broker state inconsistency
The MQSeries Message Broker may well contain registration information
for subscribers and publishers that no longer exist. This means that the
broker may continue forwarding messages to subscribers that will never
receive them.
Subscriber messages and queues remain
Part of the subscriber deregistration procedure is the removal of subscriber
messages. If appropriate, the underlying MQSeries queue that was used to
receive subscriptions is also removed. If normal closure has not occurred,
these messages and queues remain. If there is broker state inconsistency,
the queues continue to fill up with messages that will never be read.
The cleanup utility runs transparently in the background and only persists for a
short time. It should not affect other MQ JMS operations. If a large number of
problems are detected against a given queue manager, there might be a small delay
at initialization time while resources are cleaned up.
Note: We still strongly recommend that whenever possible, you close all subscriber
objects gracefully to avoid a build up of subscriber problems.
where:
-m queueManager
= specify the name of the queue manager to use
-clear = clear the queue of messages after dumping its contents
The JMSCorrelationID header field is used to link one message with another. It
typically links a reply message with its requesting message. JMSCorrelationID can
hold a provider-specific message ID, an application-specific String, or a
provider-native byte[] value.
Message selectors
A Message contains a built-in facility to support application-defined property
values. In effect, this provides a mechanism to add application-specific header
fields to a message. Properties allow an application, via message selectors, to have
a JMS provider select or filter messages on its behalf, using application-specific
criteria. Application-defined properties must obey the following rules:
v Property names must obey the rules for a message selector identifier.
v Property values can be boolean, byte, short, int, long, float, double, and string.
v The following name prefixes are reserved: JMSX, JMS_.
Property values are set before sending a message. When a client receives a
message, the message properties are read-only. If a client attempts to set properties
at this point, a MessageNotWriteableException is thrown. If clearProperties is
called, the properties can now be both read from, and written to.
A property value may duplicate a value in a message’s body, or it may not. JMS
does not define a policy for what should or should not be made into a property.
A JMS message selector allows a client to specify the messages that it is interested
in by using the message header. Only messages whose headers match the selector
are delivered.
A message selector matches a message when the selector evaluates to true when
the message’s header field and property values are substituted for their
corresponding identifiers in the selector.
The following message selector selects messages with a message type of car, color
of blue, and weight greater than 2500 lbs:
"JMSType = 'car' AND color = 'blue' AND weight > 2500"
Although SQL supports fixed decimal comparison and arithmetic, JMS message
selectors do not. This is why exact numeric literals are restricted to those without a
decimal. It is also why there are numerics with a decimal as an alternate
representation for an approximate numeric value.
MQSeries Message
JMS Client JMS Client
Mapping MQMD Mapping
JMS Message JMS Message
Data
Header Header
RFH2
Properties Properties
There are two parts of the header, a fixed portion, and a variable portion.
Fixed portion
The fixed portion is modelled on the “standard” MQSeries header pattern
and consists of the following fields:
StrucId (MQCHAR4)
Structure identifier.
Must be MQRFH_STRUC_ID (value: “RFH ”) (initial value).
MQRFH_STRUC_ID_ARRAY (value: “R”,“F”,“H”,“ ”) is also
defined in the usual way.
Version (MQLONG)
Structure version number.
Must be MQRFH_VERSION_2 (value: 2) (initial value).
StrucLength (MQLONG)
Total length of MQRFH2, including the NameValueData fields.
The value set into StrucLength must be a multiple of 4 (the data in
the NameValueData fields may be padded with space characters to
achieve this).
Encoding (MQLONG)
Data encoding.
Encoding of any numeric data in the portion of the message
following the MQRFH2 (the next header, or the message data
following this header).
CodedCharSetId (MQLONG)
Coded character set identifier.
Representation of any character data in the portion of the message
following the MQRFH2 (the next header, or the message data
following this header).
Format (MQCHAR8)
Format name.
Format name for the portion of the message following the
MQRFH2.
Flags (MQLONG)
Flags.
MQRFH_NO_FLAGS =0. No flags set.
NameValueCCSID (MQLONG)
The coded character set identifier (CCSID) for the NameValueData
character strings contained in this header. The NameValueData
may be coded in a character set that differs from the other
character strings that are contained in the header (StrucID and
Format).
Variable Portion
The variable portion follows the fixed portion. The variable portion
contains a variable number of MQRFH2 Folders. Each folder contains a
variable number of elements or properties. Folders group together related
properties. The MQRFH2 headers created by JMS can contain up to three
folders:
The <mcd> folder
This contains properties that describe the “shape” or “format” of
the message. For example the Msd property identifies the message
as being Text, Bytes, Stream. Map, Object, or “Null”. This folder is
always present in a JMS MQRFH2.
The <jms> folder
This is used to transport JMS header fields, and JMSX properties
that cannot be fully expressed in the MQMD. This folder is always
present in a JMS MQRFH2.
The <usr> folder
This is used to transport any application-defined properties
associated with the message. This folder is only present if the
application has set some application-defined properties.
A string value may contain spaces. You must use the following
escape sequences in a string value:
& for the & character
< for the < character
You can use the following escape sequences, but they are not
required:
> for the > character
' for the ' character
" for the " character
For fields marked ’Set by Message Object’, the value transmitted is the value held
in the JMS message immediately before the send/publish(). The value in the JMS
Message is left unchanged by the send/publish().
For fields marked ’Set by Send Method’, a value is assigned when the
send/publish() is executed (any value held in the JMS Message is ignored). The
value in the JMS message is updated to show the value used.
Fields marked as ’Receive-only’ are not transmitted and are left unchanged in the
message by send() or publish().
MQRO_EXCEPTION or
MQRO_EXCEPTION_WITH_DATA or
MQRO_EXCEPTION_WITH_FULL_DATA
JMS_IBM_Report_Expiration
MQRO_EXPIRATION or
MQRO_EXPIRATION_WITH_DATA or
MQRO_EXPIRATION_WITH_FULL_DATA
JMS_IBM_Report_COA
MQRO_COD or
MQRO_COD_WITH_DATA or
MQRO_COD_WITH_FULL_DATA
JMS_IBM_Report_PAN
MQRO_PAN
JMS_IBM_Report_NAN
MQRO_NAN
JMS_IBM_Report_Pass_Msg_ID
MQRO_PASS_MSG_ID
JMS_IBM_Report_Pass_Correl_ID
MQRO_PASS_CORREL_ID
JMS_IBM_Report_Discard_Msg
MQRO_DISCARD_MSG
v JMS_IBM_MsgType to MQMD MsgType: Value maps directly onto MQMD
MsgType. If the application has not set an explicit value of JMS_IBM_MsgType,
then a default value is used. This default value is determined as follows:
– If JMSReplyTo is set to an MQSeries queue destination, MSGType is set to the
value MQMT_REQUEST
– If JMSReplyTo is not set, or is set to anything other than an MQSeries queue
destination, MsgType is set to the value MQMT_DATAGRAM
v JMS_IBM_Feedback to MQMD Feedback: Value maps directly onto MQMD
Feedback.
v JMS_IBM_Format to MQMD Format: Value maps directly onto MQMD Format.
v JMS_IBM_Encoding to MQMD Encoding: If set, this property overrides the
numeric encoding of the Destination Queue or Topic.
v JMS_IBM_Character_Set to MQMD CodedCharacterSetId: If set, this property
overrides the coded character set property of the Destination Queue or Topic.
The mapping from JMS to MQMD targeted at a Native MQSeries application is the
same as mapping from JMS to MQMD targeted at a true JMS client. If JMS receives
an MQSeries message with the MQMD Format field set to other than
MQFMT_RFH2, we know that we are receiving data from a non-JMS application. If
the Format is MQFMT_STRING, the message is received as a JMS Text Message.
Otherwise, it is received as a JMS Bytes message. Because there is no MQRFH2,
only those JMS properties that are transmitted in the MQMD can be restored.
Message body
This section discusses the encoding of the message body itself. The encoding
depends on the type of JMS message:
ObjectMessage
is an object serialized by the Java Runtime in the normal way.
TextMessage
is an encoded string. For an outgoing message, the string is encoded in the
character set given by the Destination object. This defaults to UTF8
encoding (the UTF8 encoding starts with the first character of the message
- there is no length field at the start). It is, however, possible to specify any
other character set supported by MQ Java. Such character sets are used
mainly when you send a message to a non-JMS application.
If the character set is a double-byte set (including UTF16), the Destination
object’s integer encoding specification determines the order of the bytes.
An incoming message is interpreted using the character set and encoding
that are specified in the message itself. These specifications are in the
rightmost MQSeries header (or MQMD if there are no headers). For JMS
messages, the rightmost header will usually be the MQRFH2.
BytesMessage
is, by default, a sequence of bytes as defined by the JMS 1.0.2 specification,
and associated Java documentation.
For an outgoing message that was assembled by the application itself, the
Destination object’s encoding property may be used to override the
where:
datatype can take one of the values described in Table 19 on page 198.
string is the default datatype, so dt='string' is omitted.
The character set used to encode or interpret the XML string that makes up
the MapMessage body is determined following the rules that apply to a
TextMessage.
StreamMessage
is like a map, but without element names:
<stream><elt dt='datatype'>value</elt>
<elt dt='datatype'>value</elt>.....</stream>
Every element is sent using the same tagname (elt). The default type is
string, so dt='string' is omitted for string elements.
The character set used to encode or interpret the XML string that makes up
the StreamMessage body is determined following the rules that apply to a
TextMessage.
The following sections contain details about how MQ JMS implements ASF:
v “ASF classes and functions” describes how MQ JMS implements the
ConnectionConsumer class and advanced functionality in the Session class.
v “Application server sample code” on page 215 describes the sample
ServerSessionPool and ServerSession code that is supplied with MQ JMS.
v “Examples of ASF use” on page 219 describes supplied ASF samples and
examples of ASF use from the perspective of a client application.
Note: The Java Message Service 1.0.2 specification for ASF also describes JMS
support for distributed transactions using the X/Open XA protocol. For
details of the XA support that MQ JMS provides, see “Appendix E. JMS
JTA/XA interface with WebSphere” on page 361.
ConnectionConsumer
The JMS specification enables an application server to integrate closely with a JMS
implementation by using the ConnectionConsumer interface. This feature provides
concurrent processing of messages. Typically, an application server creates a pool
of threads, and the JMS implementation makes messages available to these threads.
A JMS-aware application server can use this feature to provide high-level
messaging functionality, such as message processing beans.
Normal applications do not use the ConnectionConsumer, but expert JMS clients
might use it. For such clients, the ConnectionConsumer provides a
You can achieve the same effect by constructing multiple Session and
MessageConsumer objects, each with a registered MessageListener. However, the
ConnectionConsumer provides better performance, less use of resources, and
greater flexibility. In particular, fewer Session objects are required.
Planning an application
General principles for point-to-point messaging
When an application creates a ConnectionConsumer from a QueueConnection
object, it specifies a JMS Queue object and a selector string. The
ConnectionConsumer then begins to receive messages (or, more accurately, to
provide messages to Sessions in the associated ServerSessionPool). Messages arrive
on the queue, and if they match the selector, they are delivered to Sessions in the
associated ServerSessionPool.
When you set up the MQSeries Queue Manager, consider the following points:
v The underlying QLOCAL must be enabled for shared input. To do this, use the
following MQSC command:
ALTER QLOCAL(your.qlocal.name) SHARE GET(ENABLED)
For durable subscriptions, the CCDSUB property of the Topic specifies the queue
to use. Again, this may be a queue that already exists or a queue name prefix
followed by a ‘*’. If you specify a queue that already exists, all durable
ConnectionConsumers that subscribe to the Topic use this queue. If you specify a
queue name prefix followed by a ‘*’, a queue is generated the first time that a
durable ConnectionConsumer is created with a given name. This queue is reused
later when a durable ConnectionConsumer is created with the same name.
When you set up the MQSeries Queue Manager, consider the following points:
v Your queue manager must have an enabled dead-letter queue. If a
ConnectionConsumer experiences a problem when it puts a message on the
dead-letter queue, message delivery from the underlying QLOCAL stops. To
define a dead-letter queue, use:
ALTER QMGR DEADQ(your.dead.letter.queue.name)
v The user that runs the ConnectionConsumer must have authority to perform
MQOPEN with MQOO_SAVE_ALL_CONTEXT and
MQOO_PASS_ALL_CONTEXT. For details, see the MQSeries documentation for
your specific platform.
v You can optimize performance for an individual ConnectionConsumer by
creating a separate, dedicated, queue for it. This is at the cost of extra resource
usage.
The MQSeries Queue Manager keeps a record of the number of times that each
message has been backed out. When this number reaches a configurable threshold,
the ConnectionConsumer requeues the message on a named Backout Queue. If this
requeue fails for any reason, the message is removed from the queue and either
requeued to the dead-letter queue, or discarded. See “Removing messages from the
queue” on page 213 for more details.
On most platforms, the threshold and requeue queue are properties of the
MQSeries QLOCAL. For point-to-point messaging, this should be the underlying
QLOCAL. For publish/subscribe messaging, this is the CCSUB queue defined on
the TopicConnectionFactory, or the CCDSUB queue defined on the Topic. To set the
threshold and requeue Queue properties, issue the following MQSC command:
ALTER QLOCAL(your.queue.name) BOTHRESH(threshold) BOQUEUE(your.requeue.queue.name)
For publish/subscribe messaging, if your system creates a dynamic queue for each
subscription, these settings are obtained from the MQ JMS model queue. To alter
these settings, you can use:
ALTER QMODEL(SYSTEM.JMS.MODEL.QUEUE) BOTHRESH(threshold) BOQUEUE(your.requeue.queue.name)
If the threshold is zero, poison message handling is disabled, and poison messages
will remain on the input queue. Otherwise, when the backout count reaches the
threshold, the message is sent to the named requeue queue. If the backout count
reaches the threshold, but the message cannot go to the requeue queue, the
message is sent to the dead-letter queue or discarded. This situation occurs if the
requeue queue is not defined, or if the ConnectionConsumer cannot send the
message to the requeue queue. On some platforms, you cannot specify the
threshold and requeue queue properties. On these platforms, messages are sent to
The ConnectionConsumer also generates a report message, and this also depends
on the report field of the message’s MQMD. This message is sent to the message’s
ReplyToQ on the ReplyToQmgr. If there is an error while the report message is
being sent, the message is sent to the dead-letter queue instead. The exception
report options in the report field of the message’s MQMD set details of the report
message. These options are:
MQRO_EXCEPTION
A report message is generated that contains the MQMD of the original
message. It does not contain any message body data.
MQRO_EXCEPTION_WITH_DATA
A report message is generated that contains the MQMD, any MQ headers,
and 100 bytes of body data.
MQRO_EXCEPTION_WITH_FULL_DATA
A report message is generated that contains all data from the original
message.
default
No report message is generated.
When report messages are generated, the following options are honoured:
v MQRO_NEW_MSG_ID
v MQRO_PASS_MSG_ID
v MQRO_COPY_MSG_ID_TO_CORREL_ID
v MQRO_PASS_CORREL_ID
These fields are in the MQDLH of messages on the dead-letter queue, and the
MQMD of report messages. The feedback field of the MQMD, and the Reason field
of the MQDLH, contain a code describing the error. For details about these codes,
see “Error handling”. Other fields are as described in the MQSeries Application
Programming Reference.
Error handling
Recovering from error conditions
If a ConnectionConsumer experiences a serious error, message delivery to all
ConnectionConsumers with an interest in the same QLOCAL stops. Typically, this
occurs if the ConnectionConsumer cannot requeue a message to the dead-letter
queue, or it experiences an error when reading messages from the QLOCAL.
When this occurs, the application and application server are notified in the
following way:
v Any ExceptionListener that is registered with the affected Connection is notified.
You can use these to identify the cause of the problem. In some cases, the system
administrator must intervene to resolve the problem.
There are two ways in which an application can recover from these error
conditions:
v Call close() on all affected ConnectionConsumers. The application can create
new ConnectionConsumers only after all affected ConnectionConsumers are
closed and any system problems are resolved.
v Call stop() on all affected Connections. Once all Connections are stopped and
any system problems are resolved, the application should be able to start() all
Connections successfully.
Other codes that appear in these fields are caused by a failed attempt to requeue
the message to a Backout Queue. In this situation, the code describes the reason
that the requeue failed. To diagnose the cause of these errors, refer to the MQSeries
Application Programming Reference.
If the report message cannot be put on the ReplyToQ, it is put on the dead-letter
queue. In this situation, the feedback field of the MQMD is filled in as described
above. The reason field in the MQDLH explains why the report message could not
be placed on the ReplyToQ.
2
ConnectionConsumer
ConnectionConsumer
A B C D E
ConnectionConsumer
A B C D E
3
A B C D E
4
6
JMS Session 5
8
ServerSessionPool
A B SSt
1
8
C D E SSu
Server sessions
A B C D E F G
Message queue
These samples enable you to use the MQ JMS ASF in a standalone environment
(that is, you do not need a suitable application server). Also, they provide
examples of how to implement these interfaces and take advantage of the MQ JMS
ASF. These examples are intended to aid both MQ JMS users, and vendors of other
application servers.
MyServerSession.java
This class implements the javax.jms.ServerSession interface. Its basic function is
to associate a thread with a JMS Session. Instances of this class are pooled by a
ServerSessionPool (see “MyServerSessionPool.java”). As a ServerSession, it must
implement the following two methods:
v getSession(), which returns the JMS Session this associated with this
ServerSession
v start(), which starts this ServerSession’s thread and results in the JMS Session’s
run() method being invoked
The class uses a wait()-notify() mechanism that is based on the values of two
boolean flags, ready and quit. This mechanism means that the ServerSession
creates and starts its associated thread during its construction. However, it does
not automatically execute the body of the run() method. The body of the run()
method is executed only when the ready flag is set to true by the start() method.
The ASF calls the start() method when it is necessary to deliver messages to the
associated JMS Session.
For delivery, the run() method of the JMS Session is called. The MQ JMS ASF will
have already loaded the run() method with messages.
After delivery completes, the ready flag is reset to false, and the owning
ServerSessionPool is notified that delivery is complete. The ServerSession then
remains in a wait state until either the start() method is called again, or the
close() method is invoked and ends this ServerSession’s thread.
MyServerSessionPool.java
This class implements the javax.jms.ServerSessionPool interface, and exists to
create and control access to a pool of ServerSessions.
This sample implementation is a static model. That is, all the ServerSessions in the
pool are created when the pool is created, and after this, the pool cannot grow or
shrink. This approach is just for simplicity. It is possible for a ServerSessionPool to
use a sophisticated algorithm to create ServerSessions dynamically, as needed.
MessageListenerFactory.java
In this sample, a message listener factory object is associated with each
ServerSessionPool instance. The MessageListenerFactory class represents a very
simple interface that is used to obtain an instance of a class that implements the
javax.jms.MessageListener interface. The class contains a single method:
javax.jms.MessageListener createMessageListener();
These samples provide three examples of ASF use from the perspective of a client
application:
v A simple point-to-point example uses:
– ASFClient1.java
– Load1.java
– CountingMessageListenerFactory.java
v A more complex point-to-point example uses:
– ASFClient2.java
– Load2.java
– CountingMessageListenerFactory.java
– LoggingMessageListenerFactory.java
v A simple publish/subscribe example uses:
– ASFClient3.java
– TopicLoad.java
– CountingMessageListenerFactory.java
v A more complex publish/subscribe example uses:
– ASFClient4.java
– TopicLoad.java
– CountingMessageListenerFactory.java
– LoggingMessageListenerFactory.java
Load1.java
This class is a simple generic JMS application that loads a given queue with a
number of messages, then terminates. It can either retrieve the required
administered objects from a JNDI namespace, or create them explicitly, using the
MQ JMS classes that implement these interfaces. The administered objects that are
required are a QueueConnectionFactory and a Queue. You can use the command
line options to set the number of messages with which to load the queue, and the
sleep time between individual message puts.
If there are any errors, an error message is displayed, and the application
terminates.
You can use this application to simulate message load on an MQSeries queue. In
turn, this message load could trigger the ASF-enabled applications described in the
following sections. The messages put to the queue are simple JMS TextMessage
objects. These objects do not contain user-defined message properties, which could
be useful to make use of different message listeners. The source code is supplied so
that you can modify this load application if necessary.
CountingMessageListenerFactory.java
This file contains definitions for two classes:
v CountingMessageListener
v CountingMessageListenerFactory
ASFClient1.java
This application acts as a client of the MQ JMS ASF. It sets up a single
ConnectionConsumer to consume the messages in a single MQSeries queue. It
displays throughput statistics for each message listener that is used, and terminates
after one minute.
The client application displays throughput statistics for each message listener that
is used, displaying statistics every 10 seconds. After one minute, the connection is
closed, the server session pool is stopped, and the application terminates.
Load2.java
This class is a JMS application that loads a given queue with a number of
messages, then terminates, in a similar way to Load1.java. The command line
syntax is also similar to that for Load1.java (substitute Load2 for Load1 in the
syntax). For details, see “Load1.java” on page 219.
The difference is that each message contains a user property called value, which
takes a randomly selected integer value between 0 and 100. This property means
that you can apply message selectors to the messages. Consequently, the messages
can be shared between the two consumers that are created in the client application
described in “ASFClient2.java”.
LoggingMessageListenerFactory.java
This file contains definitions for two classes:
v LoggingMessageListener
v LoggingMessageListenerFactory
ASFClient2.java
ASFClient2.java is a slightly more complicated client application than
ASFClient1.java. It creates two ConnectionConsumers that feed off the same queue,
but that apply different message selectors. The application uses a
CountingMessageListenerFactory for one consumer, and a
LoggingMessageListenerFactory for the other. Use of two different message listener
factories means that each consumer must have its own server session pool.
There should be an uneven distribution of messages. The messages loaded onto the
source queue by Load2 contain a user property, where the value should be
between 0 and 100, evenly and randomly distributed. The message selector
value>75 is applied to highConnectionConsumer, and the message selector
value≤75 is applied to normalConnectionConsumer. The
highConnectionConsumer’s messages (approximately 25% of the total load) are
sent to a LoggingMessageListener. The normalConnectionConsumer’s messages
(approximately 75% of the total load) are sent to a CountingMessageListener.
You can inspect the screen and the log file to see the real destination of the
messages. Add the totals for each of the CountingMessageListeners. As long as the
client application does not terminate before all the messages are consumed, this
should account for approximately 75% of the load. The number of log file entries
should account for the remainder of the load. (If the client application terminates
before all the messages are consumed, you can increase the application timeout.)
TopicLoad.java
This class is a JMS application that is a publish/subscribe version of the Load2
queue loader described in “Load2.java” on page 222. It publishes the required
number of messages under the given topic, then it terminates. Each message
contains a user property called value, which takes a randomly selected integer
value between 0 and 100.
To use this application, ensure that the broker is running and that the required
setup is complete. For details, see “Additional setup for Publish/Subscribe mode”
on page 20.
If there are any errors, an error message is displayed, and the application
terminates.
ASFClient3.java
ASFClient3.java is a client application that is a publish/subscribe version of
“ASFClient1.java” on page 220. It sets up a single ConnectionConsumer to consume
the messages published on a single Topic. It displays throughput statistics for each
message listener that is used, and terminates after one minute.
Like ASFClient1, the client application displays throughput statistics for each
message listener that is used, displaying statistics every 10 seconds. After one
minute, the connection is closed, the server session pool is stopped, and the
application terminates.
ASFClient4.java
ASFClient4.java is a more complex publish/subscribe client application. It creates
three ConnectionConsumers that all feed off the same topic, but each one applies
different message selectors.
The first two consumers use ‘high’ and ‘normal’ message selectors, in the same
way as the application “ASFClient2.java” on page 222. The third consumer does
not use any message selector. The application uses two
CountingMessageListenerFactories for the two selector-based consumers, and a
LoggingMessageListenerFactory for the third consumer. Because the application
uses different message listener factories, each consumer must have its own server
session pool.
The application displays statistics that relate to the two selector-based consumers
on screen. It writes statistics that relate to the third ConnectionConsumer to a log
file.
The command line syntax is similar to that for “ASFClient3.java” on page 224
(substitute ASFClient4 for ASFClient3 in the syntax). Each of the three server
session pools contains the number of ServerSessions set by the poolSize parameter.
You can inspect the screen and the log file to see the real destination of the
messages. Add the totals for each of the CountingMessageListeners and inspect the
number of log file entries.
| Notes:
| 1. These classes implementing the XA function are not supported with MQ Java for iSeries
| & AS/400
BytesMessage
public interface BytesMessage
extends Message
java.lang.Object
|
+----com.ibm.jms.JMSMessage
|
+----com.ibm.jms.JMSBytesMessage
Note: This message type is for client encoding of existing message formats. If
possible, one of the other self-defining message types should be used
instead.
Methods
readBoolean
public boolean readBoolean() throws JMSException
Read in a string that has been encoded using a modified UTF-8 format
from the bytes message. The first two bytes are interpreted as a 2-byte
length field.
Returns:
a Unicode string from the bytes message.
Throws:
v MessageNotReadableException - if the message is in write-only
mode.
v MessageEOFException - if it is the end of the message bytes.
v JMSException - if JMS fails to read the message because of an
internal JMS error.
readBytes
public int readBytes(byte[] value) throws JMSException
Read a byte array from the bytes message. If there are sufficient bytes
remaining in the stream the entire buffer is filled, if not, the buffer is
partially filled.
Parameters:
value - the buffer into which the data is read.
Returns:
the total number of bytes read into the buffer, or -1 if there is no
more data because the end of the bytes has been reached.
Throws:
v MessageNotReadableException - if the message is in write-only
mode.
v JMSException - if JMS fails to read the message because of an
internal JMS error.
readBytes
public int readBytes(byte[] value, int length)
throws JMSException
Write a boolean to the bytes message as a 1-byte value. The value true is
written out as the value (byte)1; the value false is written out as the
value (byte)0.
Parameters:
value - the boolean value to be written.
Throws:
v MessageNotWriteableException - if message in read-only mode.
v JMSException - if JMS fails to write the message because of an
internal JMS error.
writeByte
public void writeByte(byte value) throws JMSException
Write a char to the bytes message as a 2-byte value, high byte first.
Parameters:
value - the char value to be written.
Throws:
v MessageNotWriteableException - if message in read-only mode.
v JMSException - if JMS fails to write the message because of an
internal JMS error.
writeInt
public void writeInt(int value) throws JMSException
Note: This method only works for the primitive object types (such as
Integer, Double, and Long), Strings, and byte arrays.
Parameters:
value - the Java object to be written.
Throws:
v MessageNotWriteableException - if message in read-only
mode.
v MessageFormatException - if object is invalid type.
v JMSException - if JMS fails to write the message because
of an internal JMS error.
reset
public void reset() throws JMSException
Put the message body in read-only mode, and reposition the bytes of bytes
to the beginning.
Throws:
v JMSException - if JMS fails to reset the message because of an
internal JMS error.
v MessageFormatException - if message has an invalid format
Connection
public interface Connection
Subinterfaces: QueueConnection, TopicConnection, XAQueueConnection, and
XATopicConnection
java.lang.Object
|
+----com.ibm.mq.jms.MQConnection
Methods
getClientID
public java.lang.String getClientID()
throws JMSException
Get the client identifier for this connection. The client identifier can either
be preconfigured by the administrator in a ConnectionFactory, or assigned
by calling setClientId.
Returns:
the unique client identifier.
Throws:
JMSException - if the JMS implementation fails to return the client
ID for this Connection because of an internal error.
setClientID
public void setClientID(java.lang.String clientID)
throws JMSException
Because a provider may allocate some resources outside the JVM on behalf
of a Connection, clients should close them when they are not needed. You
cannot rely on garbage collection to reclaim these resources eventually,
because this may not occur soon enough. There is no need to close the
sessions, producers, and consumers of a closed connection.
ConnectionConsumer
public interface ConnectionConsumer
java.lang.Object
|
+----com.ibm.mq.jms.MQConnectionConsumer
Methods
close()
public void close() throws JMSException
ConnectionFactory
public interface ConnectionFactory
Subinterfaces: QueueConnectionFactory, TopicConnectionFactory,
XAQueueConnectionFactory, and XATopicConnectionFactory
java.lang.Object
|
+----com.ibm.mq.jms.MQConnectionFactory
MQSeries constructor
MQConnectionFactory
public MQConnectionFactory()
Methods
setDescription *
public void setDescription(String x)
Sets the client Identifier to be used for all connections created using this
Connection.
Get the client Identifier that is used for all connections that are created
using this ConnectionFactory.
setQueueManager *
public void setQueueManager(String x) throws JMSException
Set the character set to be used when connecting to the queue manager. See
Table 13 on page 105 for a list of allowed values. We recommend that you
use the default value (819) for most situations.
Get the initialization string that was passed to the receive exit class.
setSecurityExit *
public void setSecurityExit(String securityExit)
ConnectionMetaData
public interface ConnectionMetaData
java.lang.Object
|
+----com.ibm.mq.jms.MQConnectionMetaData
MQSeries constructor
MQConnectionMetaData
public MQConnectionMetaData()
Methods
getJMSVersion
public java.lang.String getJMSVersion() throws JMSException
DeliveryMode
public interface DeliveryMode
Fields
NON_PERSISTENT
public static final int NON_PERSISTENT
This is the lowest overhead delivery mode because it does not require that
the message be logged to stable storage.
PERSISTENT
public static final int PERSISTENT
This mode instructs the JMS provider to log the message to stable storage
as part of the client’s send operation.
Destination
public interface Destination
Subinterfaces: Queue, TemporaryQueue, TemporaryTopic, and Topic
java.lang.Object
|
+----com.ibm.mq.jms.MQDestination
MQSeries constructors
MQDestination
public MQDestination()
Methods
setDescription *
public void setDescription(String x)
Get the name of the character set that is used by this destination.
setEncoding *
public void setEncoding(int x) throws JMSException
ExceptionListener
public interface ExceptionListener
If a JMS provider detects a serious problem with a Connection, it will inform the
Connection’s ExceptionListener if one has been registered. It does this by calling
the listener’s onException() method, passing it a JMSException that describes the
problem.
Methods
onException
public void onException(JMSException exception)
MapMessage
public interface MapMessage
extends Message
java.lang.Object
|
+----com.ibm.jms.JMSMessage
|
+----com.ibm.jms.JMSMapMessage
A MapMessage is used to send a set of name-value pairs where names are Strings
and values are Java primitive types. The entries can be accessed sequentially or
randomly by name. The order of the entries is undefined.
Methods
getBoolean
public boolean getBoolean(java.lang.String name)
throws JMSException
Return the Java object value with the given name. This method returns in
object format, a value that has been stored in the Map either using the
setObject method call, or the equivalent primitive set method.
Parameters:
name - the name of the Java object.
Returns:
a copy of the Java object value with the given name, in object
format (if it is set as an int, then a Integer is returned). If there is
no item by this name, a null value is returned.
Throws:
JMSException - if JMS fails to read the message because of an
internal JMS error.
getMapNames
public java.util.Enumeration getMapNames() throws JMSException
Set a boolean value with the given name into the Map.
Parameters:
v name - the name of the boolean.
v value - the boolean value to set in the Map.
Throws:
v JMSException - if JMS fails to write message due to some
internal JMS error.
v MessageNotWriteableException - if the message is in read-only
mode.
Set a byte value with the given name into the Map.
Parameters:
v name - the name of the byte.
v value - the byte value to set in the Map.
Throws:
v JMSException - if JMS fails to write message due to some
internal JMS error
v MessageNotWriteableException - if the message is in read-only
mode.
setShort
public void setShort(java.lang.String name,
short value) throws JMSException
Set a short value with the given name into the Map.
Parameters:
v name - the name of the short.
v value - the short value to set in the Map.
Throws:
v JMSException - if JMS fails to write message due to some
internal JMS error.
v MessageNotWriteableException - if the message is in read-only
mode.
setChar
public void setChar(java.lang.String name,
char value) throws JMSException
Set a Unicode character value with the given name into the Map.
Parameters:
v name - the name of the Unicode character.
v value - the Unicode character value to set in the Map.
Throws:
v JMSException - if JMS fails to write message due to some
internal JMS error.
v MessageNotWriteableException - if the message is in read-only
mode.
setInt
public void setInt(java.lang.String name,
int value) throws JMSException
Set an integer value with the given name into the Map.
Parameters:
v name - the name of the integer.
v value - the integer value to set in the Map.
Set a long value with the given name into the Map.
Parameters:
v name - the name of the long.
v value - the long value to set in the Map.
Throws:
v JMSException - if JMS fails to write message due to some
internal JMS error.
v MessageNotWriteableException - if the message is in read-only
mode.
setFloat
public void setFloat(java.lang.String name,
float value) throws JMSException
Set a float value with the given name into the Map.
Parameters:
v name - the name of the float.
v value - the float value to set in the Map.
Throws:
v JMSException - if JMS fails to write message due to some
internal JMS error.
v MessageNotWriteableException - if the message is in read-only
mode.
setDouble
public void setDouble(java.lang.String name,
double value) throws JMSException
Set a double value with the given name into the Map.
Parameters:
v name - the name of the double.
v value - the double value to set in the Map.
Throws:
v JMSException - if JMS fails to write message due to some
internal JMS error.
v MessageNotWriteableException - if the message is in read-only
mode.
Set a String value with the given name into the Map.
Parameters:
v name - the name of the String.
v value - the String value to set in the Map.
Throws:
v JMSException - if JMS fails to write message due to some
internal JMS error.
v MessageNotWriteableException - if the message is in read-only
mode.
setBytes
public void setBytes(java.lang.String name,
byte[] value) throws JMSException
Set a byte array value with the given name into the Map.
Parameters:
v name - the name of the byte array.
v value - the byte array value to set in the Map.
The array is copied, so the value in the map is not altered by
subsequent modifications to the array.
Throws:
v JMSException - if JMS fails to write message due to some
internal JMS error.
v MessageNotWriteableException - if the message is in read-only
mode.
setBytes
public void setBytes(java.lang.String name,
byte[] value,
int offset,
int length) throws JMSException
Set a portion of the byte array value with the given name into the Map.
The array is copied, so the value in the map is not altered by subsequent
modifications to the array.
Parameters:
v name - the name of the byte array.
v value - the byte array value to set in the Map.
v offset - the initial offset within the byte array.
v length - the number of bytes to be copied.
Throws:
v JMSException - if JMS fails to write message due to some
internal JMS error.
v MessageNotWriteableException - if the message is in read-only
mode.
Set a Java object value with the given name into the Map. This method
only works for object primitive types (Integer, Double, Long, for example),
Strings and byte arrays.
Parameters:
v name - the name of the Java object.
v value - the Java object value to set in the Map.
Throws:
v JMSException - if JMS fails to write message due to some
internal JMS error.
v MessageFormatException - if object is invalid.
v MessageNotWriteableException - if the message is in read-only
mode.
itemExists
public boolean itemExists(java.lang.String name)
throws JMSException
Message
public interface Message
Subinterfaces: BytesMessage, MapMessage, ObjectMessage,
StreamMessage, and TextMessage
java.lang.Object
|
+----com.ibm.jms.MQJMSMessage
The Message interface is the root interface of all JMS messages. It defines the JMS
header and the acknowledge method used for all messages.
Fields
DEFAULT_DELIVERY_MODE
public static final int DEFAULT_DELIVERY_MODE
Methods
getJMSMessageID
public java.lang.String getJMSMessageID()
throws JMSException
Any value set using this method is ignored when the message is sent, but
this method can be used to change the value in a received message.
Any value set using this method is ignored when the message is sent, but
this method can be used to change the value in a received message.
Parameters:
timestamp - the timestamp for this message.
Throws:
JMSException - if JMS fails to set the timestamp because of an
internal JMS error.
See also:
getJMSTimestamp()
getJMSCorrelationIDAsBytes
public byte[] getJMSCorrelationIDAsBytes()
throws JMSException
Set the correlation ID as an array of bytes for the message. A client can use
this call to set the correlationID equal either to a messageID from a
previous message, or to an application-specific string. Application-specific
strings must not start with the characters ID:
Parameters:
correlationID - the correlation ID as a string, or the message ID of
a message being referred to.
Throws:
JMSException - if JMS fails to set the correlation ID because of an
internal JMS error.
See also:
setJMSCorrelationID(), getJMSCorrelationID(),
getJMSCorrelationIDAsBytes()
getJMSCorrelationID
public java.lang.String getJMSCorrelationID()
throws JMSException
A client can use the JMSCorrelationID header field to link one message
with another. A typical use is to link a response message with its request
message.
Any value set using this method is ignored when the message is sent, but
this method can be used to change the value in a received message.
Parameters:
destination - the destination for this message.
Any value set using this method is ignored when the message is sent, but
this method can be used to change the value in a received message.
Any value set using this method is ignored when the message is sent, but
this method can be used to change the value in a received message.
Parameters:
redelivered - an indication of whether this message is being
redelivered.
Throws:
JMSException - if JMS fails to set JMSRedelivered flag because of
an internal JMS error.
See also:
getJMSRedelivered()
getJMSType
public java.lang.String getJMSType() throws JMSException
JMS clients should assign a value to type whether the application makes
use of it or not. This ensures that it is properly set for those providers that
require it.
Parameters:
type - the class of message.
Throws:
JMSException - if JMS fails to set JMS message type because of an
internal JMS error.
See also:
getJMSType()
getJMSExpiration
public long getJMSExpiration() throws JMSException
Any value set using this method is ignored when the message is sent, but
this method can be used to change the value in a received message.
Parameters:
expiration - the message’s expiration time.
Throws:
JMSException - if JMS fails to set JMS message expiration because
of an internal JMS error.
See also:
getJMSExpiration()
getJMSPriority
public int getJMSPriority() throws JMSException
JMS defines a ten level priority value, with 0 as the lowest priority, and 9
as the highest. In addition, clients should consider priorities 0-4 as
gradations of normal priority, and priorities 5-9 as gradations of expedited
priority.
Parameters:
priority - the priority of this message.
Throws:
JMSException - if JMS fails to set JMS message priority because of
an internal JMS error.
Clear a message’s properties. The header fields and message body are not
cleared.
Throws:
JMSException - if JMS fails to clear JMS message properties
because of an internal JMS error.
propertyExists
public boolean propertyExists(java.lang.String name)
throws JMSException
Return the Java object property value with the given name.
Parameters:
name - the name of the Java object property.
Returns:
the Java object property value with the given name, in object
format (for example, if it set as an int, an Integer is returned). If
there is no property by this name, a null value is returned.
Throws:
JMSException - if JMS fails to get the property because of an
internal JMS error.
Set a boolean property value with the given name into the Message.
Parameters:
v name - the name of the boolean property.
v value - the boolean property value to set in the Message.
Throws:
v JMSException - if JMS fails to set Property because of an internal
JMS error.
v MessageNotWriteableException - if the properties are read-only.
setByteProperty
public void setByteProperty(java.lang.String name,
byte value) throws JMSException
Set a byte property value with the given name into the Message.
Parameters:
v name - the name of the byte property.
v value - the byte property value to set in the Message.
Throws:
v JMSException - if JMS fails to set Property because of an internal
JMS error.
v MessageNotWriteableException - if the properties are read-only.
setShortProperty
public void setShortProperty(java.lang.String name,
short value) throws JMSException
Set a short property value with the given name into the Message.
Parameters:
v name - the name of the short property.
v value - the short property value to set in the Message.
Throws:
v JMSException - if JMS fails to set Property because of an internal
JMS error.
v MessageNotWriteableException - if the properties are read-only.
Set an integer property value with the given name into the Message.
Parameters:
v name - the name of the integer property.
v value - the integer property value to set in the Message.
Throws:
v JMSException - if JMS fails to set Property because of an internal
JMS error.
v MessageNotWriteableException - if the properties are read-only.
setLongProperty
public void setLongProperty(java.lang.String name,
long value) throws JMSException
Set a long property value with the given name into the Message.
Parameters:
v name - the name of the long property.
v value - the long property value to set in the Message.
Throws:
v JMSException - if JMS fails to set Property because of an internal
JMS error.
v MessageNotWriteableException - if the properties are read-only.
setFloatProperty
public void setFloatProperty(java.lang.String name,
float value) throws JMSException
Set a float property value with the given name into the Message.
Parameters:
v name - the name of the float property.
v value - the float property value to set in the Message.
Throws:
v JMSException - if JMS fails to set the property because of an
internal JMS error.
v MessageNotWriteableException - if the properties are read-only.
setDoubleProperty
public void setDoubleProperty(java.lang.String name,
double value) throws JMSException
Set a double property value with the given name into the Message.
Parameters:
v name - the name of the double property.
v value - the double property value to set in the Message.
Set a String property value with the given name into the Message.
Parameters:
v name - the name of the String property.
v value - the String property value to set in the Message.
Throws:
v JMSException - if JMS fails to set the property because of an
internal JMS error.
v MessageNotWriteableException - if the properties are read-only.
setObjectProperty
public void setObjectProperty(java.lang.String name,
java.lang.Object value) throws JMSException
Set a property value with the given name into the Message.
Parameters:
v name - the name of the Java object property.
v value - the Java object property value to set in the Message.
Throws:
v JMSException - if JMS fails to set Property because of an internal
JMS error.
v MessageFormatException - if the object is invalid.
v MessageNotWriteableException - if the properties are read-only.
acknowledge
public void acknowledge() throws JMSException
Clear out the message body. All other parts of the message are left
untouched.
Throws:
JMSException - if JMS fails to because of an internal JMS error.
MessageConsumer
public interface MessageConsumer
Subinterfaces: QueueReceiver and TopicSubscriber
java.lang.Object
|
+----com.ibm.mq.jms.MQMessageConsumer
The parent interface for all message consumers. A client uses a message consumer
to receive messages from a Destination.
Methods
getMessageSelector
public java.lang.String getMessageSelector()
throws JMSException
Receive the next message that arrives within the specified timeout interval.
A timeout value of zero causes the call to wait indefinitely until a message
arrives.
Parameters:
timeout - the timeout value (in milliseconds).
Returns:
the next message produced for this message consumer, or null if
one is not available.
Throws:
JMSException - if JMS fails to receive the next message because of
an error.
receiveNoWait
public Message receiveNoWait() throws JMSException
MessageListener
public interface MessageListener
Methods
onMessage
public void onMessage(Message message)
MessageProducer
public interface MessageProducer
Subinterfaces: QueueSender and TopicPublisher
java.lang.Object
|
+----com.ibm.mq.jms.MQMessageProducer
MQSeries constructors
MQMessageProducer
public MQMessageProducer()
Methods
setDisableMessageID
public void setDisableMessageID(boolean value)
throws JMSException
Note: This method is ignored in the MQSeries classes for Java Message
Service implementation.
Parameters:
value - indicates whether message IDs are disabled.
Throws:
JMSException - if JMS fails to set the disabled message ID
because of an internal error.
getDisableMessageID
public boolean getDisableMessageID() throws JMSException
Set the default length of time, in milliseconds from its dispatch time, that a
produced message should be retained by the message system.
Get the default length of time in milliseconds from its dispatch time that a
produced message should be retained by the message system.
Returns:
the message time to live in milliseconds; zero is unlimited.
Throws:
JMSException - if JMS fails to get the Time to Live because of an
internal error.
See also:
setTimeToLive
MQQueueEnumeration *
public class MQQueueEnumeration
extends Object
implements Enumeration
java.lang.Object
|
+----com.ibm.mq.jms.MQQueueEnumeration
Methods
hasMoreElements
public boolean hasMoreElements()
ObjectMessage
public interface ObjectMessage
extends Message
java.lang.Object
|
+----com.ibm.jms.JMSMessage
|
+----com.ibm.jms.JMSObjectMessage
Methods
setObject
public void setObject(java.io.Serializable object)
throws JMSException
Get the serializable object containing this message’s data. The default value
is null.
Returns:
the serializable object containing this message’s data.
Throws:
v JMSException - if JMS fails to get the object because of an
internal JMS error.
v MessageFormatException - if object deserialization fails.
Queue
public interface Queue
extends Destination
Subinterfaces: TemporaryQueue
java.lang.Object
|
+----com.ibm.mq.jms.MQDestination
|
+----com.ibm.mq.jms.MQQueue
MQSeries constructors
MQQueue *
public MQQueue()
Methods
getQueueName
public java.lang.String getQueueName()
throws JMSException
QueueBrowser
public interface QueueBrowser
java.lang.Object
|
+----com.ibm.mq.jms.MQQueueBrowser
Methods
getQueue
public Queue getQueue() throws JMSException
Get an enumeration for browsing the current queue messages in the order
that they would be received.
Returns:
an enumeration for browsing the messages.
Throws:
JMSException - if JMS fails to get the enumeration for this browser
because of a JMS error.
QueueConnection
public interface QueueConnection
extends Connection
Subinterfaces: XAQueueConnection
java.lang.Object
|
+----com.ibm.mq.jms.MQConnection
|
+----com.ibm.mq.jms.MQQueueConnection
Methods
createQueueSession
public QueueSession createQueueSession(boolean transacted,
int acknowledgeMode)
throws JMSException
Create a QueueSession.
Parameters:
v transacted - if true, the session is transacted.
v acknowledgeMode - indicates whether the consumer or the
client will acknowledge any messages it receives. Possible values
are:
Session.AUTO_ACKNOWLEDGE
Session.CLIENT_ACKNOWLEDGE
Session.DUPS_OK_ACKNOWLEDGE
This parameter is ignored if the session is transacted.
Returns:
a newly created queue session.
Throws:
JMSException - if JMS Connection fails to create a session because
of an internal error, or lack of support for specific transaction and
acknowledgement mode.
createConnectionConsumer
public ConnectionConsumer createConnectionConsumer
(Queue queue,
java.lang.String messageSelector,
ServerSessionPool sessionPool,
int maxMessages)
throws JMSException
QueueConnectionFactory
public interface QueueConnectionFactory
extends ConnectionFactory
Subinterfaces: XAQueueConnectionFactory
java.lang.Object
|
+----com.ibm.mq.jms.MQConnectionFactory
|
+----com.ibm.mq.jms.MQQueueConnectionFactory
MQSeries constructor
MQQueueConnectionFactory
public MQQueueConnectionFactory()
Methods
createQueueConnection
public QueueConnection createQueueConnection()
throws JMSException
QueueReceiver
public interface QueueReceiver
extends MessageConsumer
java.lang.Object
|
+----com.ibm.mq.jms.MQMessageConsumer
|
+----com.ibm.mq.jms.MQQueueReceiver
A client uses a QueueReceiver for receiving messages that have been delivered to a
queue.
Methods
getQueue
public Queue getQueue() throws JMSException
QueueRequestor
public class QueueRequestor
extends java.lang.Object
java.lang.Object
|
+----javax.jms.QueueRequestor
Constructors
QueueRequestor
public QueueRequestor(QueueSession session,
Queue queue)
throws JMSException
Methods
request
public Message request(Message message)
throws JMSException
Send a request and wait for a reply. The temporary queue is used for
replyTo, and only one reply per request is expected.
Parameters:
message - the message to send.
Returns:
the reply message.
Throws:
JMSException - if a JMS error occurs.
Note: This method closes the Session object passed to the QueueRequestor
constructor.
Throws:
JMSException - if a JMS error occurs.
QueueSender
public interface QueueSender
extends MessageProducer
java.lang.Object
|
+----com.ibm.mq.jms.MQMessageProducer
|
+----com.ibm.mq.jms.MQQueueSender
Methods
getQueue
public Queue getQueue() throws JMSException
Send a message specifying delivery mode, priority, and time to live to the
queue.
Send a message to the specified queue with delivery mode, priority, and
time to live.
QueueSession
public interface QueueSession
extends Session
java.lang.Object
|
+----com.ibm.mq.jms.MQSession
|
+----com.ibm.mq.jms.MQQueueSession
Methods
createQueue
public Queue createQueue(java.lang.String queueName)
throws JMSException
Create a Queue given a Queue name. This allows the creation of a queue
with a provider specific name. The string takes a URI format, as described
on page 173.
Session
public interface Session
extends java.lang.Runnable
Subinterfaces: QueueSession, TopicSession, XAQueueSession, XASession, and
XATopicSession
java.lang.Object
|
+----com.ibm.mq.jms.MQSession
A JMS Session is a single threaded context for producing and consuming messages.
Fields
AUTO_ACKNOWLEDGE
public static final int AUTO_ACKNOWLEDGE
Methods
createBytesMessage
public BytesMessage createBytesMessage()
throws JMSException
Create a Message. The Message interface is the root interface of all JMS
messages. It holds all the standard message header information. It can be
sent when a message containing only header information is sufficient.
Throws:
JMSException - if JMS fails to create this message because of an
internal error.
createObjectMessage
public ObjectMessage createObjectMessage()
throws JMSException
Commit all messages done in this transaction and release any locks
currently held.
Throws:
v JMSException - if JMS implementation fails to commit the
transaction because of an internal error.
v TransactionRolledBackException - if the transaction gets rolled
back because of an internal error during commit.
rollback
public void rollback() throws JMSException
Roll back any messages done in this transaction and release any locks
currently held.
Throws:
JMSException - if the JMS implementation fails to roll back the
transaction because of an internal error.
Stop message delivery in this session, and restart sending messages with
the oldest unacknowledged message.
Throws:
JMSException - if the JMS implementation fails to stop message
delivery and restart message send because of an internal error.
getMessageListener
public MessageListener getMessageListener()
throws JMSException
StreamMessage
public interface StreamMessage
extends Message
java.lang.Object
|
+----com.ibm.jms.JMSMessage
|
+----com.ibm.jms.JMSStreamMessage
Methods
readBoolean
public boolean readBoolean() throws JMSException
Read a byte array field from the stream message into the specified byte[]
object (the read buffer). If the buffer size is less than, or equal to, the size
of the data in the message field, an application must make further calls to
this method to retrieve the remainder of the data. Once the first readBytes
call on a byte[] field value has been done, the full value of the field must
be read before it is valid to read the next field. An attempt to read the next
field before that has been done will throw a MessageFormatException.
Parameters:
value - the buffer into which the data is read.
Returns:
the total number of bytes read into the buffer, or -1 if there is no
more data because the end of the byte field has been reached.
Throws:
v JMSException - if JMS fails to read the message because of an
internal JMS error.
v MessageEOFException - if an end of message stream is received.
v MessageFormatException - if this type conversion is invalid.
v MessageNotReadableException - if the message is in write-only
mode.
readObject
public java.lang.Object readObject() throws JMSException
Write a Java object to the stream message. This method only works for
object primitive types (Integer, Double, Long, for example), Strings, and
byte arrays.
Parameters:
value - the Java object to be written.
Throws:
v JMSException - if JMS fails to write the message because of an
internal JMS error.
v MessageNotWriteableException - if the message is in read-only
mode.
v MessageFormatException - if the object is invalid.
Put the message in read-only mode, and reposition the stream to the
beginning.
Throws:
v JMSException - if JMS fails to reset the message because of an
internal JMS error.
v MessageFormatException - if the message has an invalid format.
TemporaryQueue
public interface TemporaryQueue
extends Queue
java.lang.Object
|
+----com.ibm.mq.jms.MQDestination
|
+----com.ibm.mq.jms.MQQueue
|
+----com.ibm.mq.jms.MQTemporaryQueue
Methods
delete
public void delete() throws JMSException
Delete this temporary queue. If there are still existing senders or receivers
using it, a JMSException will be thrown.
Throws:
JMSException - if JMS implementation fails to delete a
TemporaryQueue because of an internal error.
TemporaryTopic
public interface TemporaryTopic
extends Topic
java.lang.Object
|
+----com.ibm.mq.jms.MQDestination
|
+----com.ibm.mq.jms.MQTopic
|
+----com.ibm.mq.jms.MQTemporaryTopic
MQSeries constructor
MQTemporaryTopic
MQTemporaryTopic() throws JMSException
Methods
delete
public void delete() throws JMSException
TextMessage
public interface TextMessage
extends Message
java.lang.Object
|
+----com.ibm.jms.JMSMessage
|
+----com.ibm.jms.JMSTextMessage
Methods
setText
public void setText(java.lang.String string)
throws JMSException
Get the string containing this message’s data. The default value is null.
Returns:
the String containing the message’s data.
Throws:
JMSException - if JMS fails to get the text because of an internal
JMS error.
Topic
public interface Topic
extends Destination
Subinterfaces: TemporaryTopic
java.lang.Object
|
+----com.ibm.mq.jms.MQDestination
|
+----com.ibm.mq.jms.MQTopic
MQSeries constructor
MQTopic
public MQTopic()
public MQTopic(string URItopic)
See TopicSession.createTopic.
Methods
getTopicName
public java.lang.String getTopicName() throws JMSException
Get the name of this topic in URI format. (URI format is described in
“Creating topics at runtime” on page 182.)
Note: Clients that depend upon the name are not portable.
Returns:
the topic name.
Throws:
JMSException - if JMS implementation for Topic fails to
return the topic name because of an internal error.
toString
public String toString()
TopicConnection
public interface TopicConnection
extends Connection
Subinterfaces: XATopicConnection
java.lang.Object
|
+----com.ibm.mq.jms.MQConnection
|
+----com.ibm.mq.jms.MQTopicConnection
Methods
createTopicSession
public TopicSession createTopicSession(boolean transacted,
int acknowledgeMode)
throws JMSException
Create a TopicSession.
Parameters:
v transacted - if true, the session is transacted.
v acknowledgeMode - one of:
Session.AUTO_ACKNOWLEDGE
Session.CLIENT_ACKNOWLEDGE
Session.DUPS_OK_ACKNOWLEDGE
TopicConnectionFactory
public interface TopicConnectionFactory
extends ConnectionFactory
Subinterfaces: XATopicConnectionFactory
java.lang.Object
|
+----com.ibm.mq.jms.MQConnectionFactory
|
+----com.ibm.mq.jms.MQTopicConnectionFactory
MQSeries constructor
MQTopicConnectionFactory
public MQTopicConnectionFactory()
Methods
createTopicConnection
public TopicConnection createTopicConnection()
throws JMSException
TopicPublisher
public interface TopicPublisher
extends MessageProducer
java.lang.Object
|
+----com.ibm.mq.jms.MQMessageProducer
|
+----com.ibm.mq.jms.MQTopicPublisher
Methods
getTopic
public Topic getTopic() throws JMSException
Publish a Message to the topic Use the topic’s default delivery mode, time
to live, and priority.
Parameters:
message - the message to publish
Throws:
v JMSException - if JMS fails to publish the message because of an
internal error.
v MessageFormatException - if an invalid message is specified.
v InvalidDestinationException - if a client uses this method with a
Topic Publisher with an invalid topic.
publish
public void publish(Message message,
int deliveryMode,
int priority,
long timeToLive) throws JMSException
Publish a Message to the topic specifying delivery mode, priority, and time
to live to the topic.
TopicRequestor
public class TopicRequestor
extends java.lang.Object
java.lang.Object
|
+----javax.jms.TopicRequestor
JMS provides this TopicRequestor class to assist with making service requests.
Constructors
TopicRequestor
public TopicRequestor(TopicSession session,
Topic topic) throws JMSException
Methods
request
public Message request(Message message) throws JMSException
TopicSession
public interface TopicSession
extends Session
java.lang.Object
|
+----com.ibm.mq.jms.MQSession
|
+----com.ibm.mq.jms.MQTopicSession
MQSeries constructor
MQTopicSession
public MQTopicSession(boolean transacted,
int acknowledgeMode) throws JMSException
See TopicConnection.createTopicSession.
Methods
createTopic
public Topic createTopic(java.lang.String topicName)
throws JMSException
Create a Topic given a URI format Topic name. (URI format is described in
“Creating topics at runtime” on page 182.) This allows the creation of a
topic with a provider specific name.
See TopicSession.unsubscribe
createDurableSubscriber
public TopicSubscriber createDurableSubscriber
(Topic topic,
java.lang.String name,
java.lang.String messageSelector,
boolean noLocal) throws JMSException
Note: Do not use this method while an active subscription exists. You
must close() your subscriber first.
Parameters:
name - the name used to identify this subscription.
TopicSubscriber
public interface TopicSubscriber
extends MessageConsumer
java.lang.Object
|
+----com.ibm.mq.jms.MQMessageConsumer
|
+----com.ibm.mq.jms.MQTopicSubscriber
A client uses a TopicSubscriber for receiving messages that have been published to
a topic. TopicSubscriber is the Pub/Sub variant of a JMS message consumer.
Methods
getTopic
public Topic getTopic() throws JMSException
Get the NoLocal attribute for this TopicSubscriber. The default value for
this attribute is false.
Returns:
set to true if locally published messages are being inhibited.
Throws:
JMSException - if JMS fails to get NoLocal attribute for this topic
subscriber because of an internal error.
XAConnection
public interface XAConnection
Subinterfaces: XAQueueConnection and XATopicConnection
java.lang.Object
|
+----com.ibm.mq.jms.MQXAConnection
XAConnectionFactory
public interface XAConnectionFactory
Subinterfaces: XAQueueConnectionFactory and XATopicConnectionFactory
java.lang.Object
|
+----com.ibm.mq.jms.MQXAConnectionFactory
Some application servers provide support to group JTS-capable resource use into a
distributed transaction. To include JMS transactions in a JTS transaction, an
application server requires a JTS-aware JMS provider. A JMS provider exposes its
JTS support by using a JMS XAConnectionFactory, which an application server
uses to create XASessions. XAConnectionFactories are JMS-administered objects
just like ConnectionFactories. It is expected that application servers use JNDI to
find them.
Refer to “Appendix E. JMS JTA/XA interface with WebSphere” on page 361 for
details about how MQ JMS uses XA classes.
XAQueueConnection
public interface XAQueueConnection
extends QueueConnection and XAConnection
java.lang.Object
|
+----com.ibm.mq.jms.MQConnection
|
+----com.ibm.mq.jms.MQQueueConnection
|
+----com.ibm.mq.jms.MQXAQueueConnection
Methods
createXAQueueSession
public XAQueueSession createXAQueueSession()
Create an XAQueueSession.
Throws:
JMSException - if JMS Connection fails to create an XA queue
session because of an internal error.
createQueueSession
public QueueSession createQueueSession(boolean transacted,
int acknowledgeMode)
throws JMSException
Create a QueueSession.
Parameters:
v transacted - if true, the session is transacted.
v acknowledgeMode - indicates whether the consumer or the
client will acknowledge any messages it receives. Possible values
are:
Session.AUTO_ACKNOWLEDGE
Session.CLIENT_ACKNOWLEDGE
Session.DUPS_OK_ACKNOWLEDGE
This parameter is ignored if the session is transacted.
Returns:
a newly created queue session (note that this is not an XA queue
session).
Throws:
JMSException - if JMS Connection fails to create a queue session
because of an internal error.
XAQueueConnectionFactory
public interface XAQueueConnectionFactory
extends QueueConnectionFactory and XAConnectionFactory
java.lang.Object
|
+----com.ibm.mq.jms.MQConnectionFactory
|
+----com.ibm.mq.jms.MQQueueConnectionFactory
|
+----com.ibm.mq.jms.MQXAQueueConnectionFactory
Methods
createXAQueueConnection
public XAQueueConnection createXAQueueConnection()
throws JMSException
XAQueueSession
public interface XAQueueSession
extends XASession
java.lang.Object
|
+----com.ibm.mq.jms.MQXASession
|
+----com.ibm.mq.jms.MQXAQueueSession
Methods
getQueueSession
public QueueSession getQueueSession()
throws JMSException
XASession
public interface XASession
extends Session
Subinterfaces: XAQueueSession and XATopicSession
java.lang.Object
|
+----com.ibm.mq.jms.MQXASession
Refer to “Appendix E. JMS JTA/XA interface with WebSphere” on page 361 for
details about how MQ JMS uses XA classes.
Methods
getXAResource
public javax.transaction.xa.XAResource getXAResource()
XATopicConnection
public interface XATopicConnection
extends TopicConnection and XAConnection
java.lang.Object
|
+----com.ibm.mq.jms.MQConnection
|
+----com.ibm.mq.jms.MQTopicConnection
|
+----com.ibm.mq.jms.MQXATopicConnection
Methods
createXATopicSession
public XATopicSession createXATopicSession()
throws JMSException
Create an XATopicSession.
Throws:
JMSException - if the JMS Connection fails to create an XA topic
session because of an internal error.
createTopicSession
public TopicSession createTopicSession(boolean transacted,
int acknowledgeMode)
throws JMSException
Create a TopicSession.
Specified by:
createTopicSession in interface TopicConnection.
Parameters:
v transacted - if true, the session is transacted.
v acknowledgeMode - one of:
Session.AUTO_ACKNOWLEDGE
Session.CLIENT_ACKNOWLEDGE
Session.DUPS_OK_ACKNOWLEDGE
XATopicConnectionFactory
public interface XATopicConnectionFactory
extends TopicConnectionFactory and XAConnectionFactory
java.lang.Object
|
+----com.ibm.mq.jms.MQConnectionFactory
|
+----com.ibm.mq.jms.MQTopicConnectionFactory
|
+----com.ibm.mq.jms.MQXATopicConnectionFactory
Methods
createXATopicConnection
public XATopicConnection createXATopicConnection()
throws JMSException
XATopicSession
public interface XATopicSession
extends XASession
java.lang.Object
|
+----com.ibm.mq.jms.MQXASession
|
+----com.ibm.mq.jms.MQXATopicSession
Methods
getTopicSession
public TopicSession getTopicSession()
throws JMSException
| Much of the data contained in this appendix has been taken from RFC 2713 Schema
| for Representing Java Objects in an LDAP Directory, which can be found at
| http://www.faqs.org/rfcs/rfc2713.html. LDAP server-specific information has been
| taken from Sun Microsystems’ JNDI 1.2.1 LDAP service provider, available at
| http://java.sun.com/products/jndi.
Attempt to create and display a test object using the following commands:
DEFINE QCF(ldapTest)
DISPLAY QCF(ldapTest)
| If no errors occur, your server is properly configured to store Java objects and you
| can proceed to store JMS objects. However, if your LDAP server contains older
| schema definitions (for example, from an earlier draft of RFC 2713 such as the
| now-obsolete “draft-ryan-java-schema-00” and “draft-ryan-java-schema-01”
| specifications), you should update them with those presented here.
| Attribute definitions
| Table 39. Attribute settings for javaCodebase
| Attribute Value
| OID (Object Identifier) 1.3.6.1.4.1.42.2.27.4.1.7
| Syntax IA5 String (1.3.6.1.4.1.1466.115.121.1.26)
| Maximum length 2048
| Single/multi-valued Multi-valued
| User modifiable? Yes
| Matching rules caseExactIA5Match
| Access class normal
| Usage userApplications
| Description URL(s) specifying the location of class definition
|
| Table 40. Attribute settings for javaClassName
| Attribute Value
| OID (Object Identifier) 1.3.6.1.4.1.42.2.27.4.1.6
| Syntax Directory String (1.3.6.1.4.1.1466.115.121.1.15)
| Maximum length 2048
| Single/multi-valued Single-valued
| User modifiable? Yes
| Matching rules caseExactMatch
| Access class normal
| Usage userApplications
| Description Fully qualified name of distinguished Java class or interface
|
| Table 41. Attribute settings for javaClassNames
| Attribute Value
| OID (Object Identifier) 1.3.6.1.4.1.42.2.27.4.1.13
| Syntax Directory String (1.3.6.1.4.1.1466.115.121.1.15)
| Maximum length 2048
| Single/multi-valued Multi-valued
| User modifiable? Yes
| Matching rules caseExactMatch
| Access class normal
| Usage userApplications
| Description Fully qualified Java class or interface name
|
| objectClass definitions
| Table 45. objectClass definition for javaSerializedObject
| Definition Value
| OID (Object Identifier) 1.3.6.1.4.1.42.2.27.4.2.5
| Extends/superior javaObject
| Type AUXILIARY
| Required (must) attrs javaSerializedData
|
| Instead of making these changes manually, you may wish to use the Sun-supplied
| schema modification applications described in “Sun Microsystems’ Schema
| Modification Applications” on page 357.
| These applications are not packaged with MQSeries classes for Java Message
| Service. Details on running them can be found in both the README and the
| application source contained in the Sun JNDI 1.2.1 LDAP service provider
| download.
| OS/400 V4R5 LDAP Server is shipped with an out of date version of RFC 2713
| schema for java objects. This schema must be updated to the schema as described
| above for correct operation with JMSAdmin. Modifying the schema requires the
| out of data definitions and any uses of those definitions to be deleted before the
| correct definitions can be added.
| OS/400 V5R1 is shipped with the current version of RFC 2713 and does not
| require these changes.
Publish/subscribe
You can use MQSeries Integrator V2 as the publish/subscribe broker for MQ JMS.
This requires the following setup activities:
v Base MQSeries
First, you must create a broker publication queue. This is an MQSeries queue on
the broker queue manager; it is used to submit publications to the broker. You
can choose your own name for this queue but it must match the queue name in
your TopicConnectionFactory’s BROKERPUBQ property. By default, a
TopicConnectionFactory’s BROKERPUBQ property is set to the value
SYSTEM.BROKER.DEFAULT.STREAM so, unless you want to configure a
different name in the TopicConnectionFactory, you should name the queue
SYSTEM.BROKER.DEFAULT.STREAM.
v MQSeries Integrator V2
The next step is to set up a message flow within an execution group for the
broker. The purpose of this message flow is to read messages from the broker
publication queue. (If you want, you can set up multiple publication queues;
each will need its own TopicConnectionFactory and message flow.)
The basic message flow consists of an MQInput node (configured to read from
the SYSTEM.BROKER.DEFAULT.STREAM queue) whose output is connected to
the input of a Publication (or MQOutput) node.
The message flow diagram would therefore look similar to the following:
When this message flow is deployed and the broker is started, from the JMS
application’s perspective the MQSeries Integrator V2 broker behaves like an
MQSeries Publish/Subscribe broker. The current subscription state can be
viewed using the MQSeries Integrator Control Center.
Notes:
1. No modifications are required to MQSeries classes for Java Message Service.
2. MQSeries Publish/Subscribe and MQSeries Integrator V2 brokers cannot
coexist on the same queue manager.
3. Details of the MQSeries Integrator V2 installation and setup procedure are
described in the MQSeries Integrator for Windows NT Version 2.0 Installation
Guide.
The MQSeries JMS implementation uses the mcd folder of the MQRFH2 to carry
information about the message, as described in “The MQRFH2 header” on
page 196. By default, the Message Domain (Msd) property is used to identify
| whether the message is a text, bytes, stream, map, or object message. This value is
| set depending on the type of the JMS message.
| If the application calls setJMSType it can set the mcd type field to a value of its
| choosing. This type field can be read by the MQSeries Integrator message flow,
| and a receiving JMS application can use the getJMSType method to retrieve its
| value. This applies to all kinds of JMS message.
| When a JMS application creates a text or bytes message, the application can set
| mcd folder fields explicitly by calling the setJMSType method and passing in a
| string argument in a special URI format as follows:
mcd://domain/[set]/[type][?format=fmt]
| This URI form allows an application to set the mcd to a domain that is not one of
| the standard “jms_xxxx” values; for example, to domain “mrm”. It also allows the
| application to set any or all of the mcd set, type and format fields if desired.
| When an MQ message is received with an Msd domain other than one of the
| standard “jms_xxxx” values, it is instantiated as a JMS text or bytes message and a
| URI-style JMSType is assigned to it. The receiving application can read this using
| the getJMSType method.
This section describes how to use these features with the WebSphere Application
Server, Advanced Edition, so that WebSphere can coordinate JMS send and receive
operations, and database updates, in a global transaction.
Notes:
1. Before you use MQ JMS and the XA classes with WebSphere, there might be
additional installation or configuration steps. Refer to the Readme.txt file on the
MQSeries Using Java SupportPac Web page for the latest information
(www.ibm.com/software/ts/mqseries/txppacs/ma88.html).
| 2. The functions described here are not supported in MQ Java for iSeries &
| AS/400.
You must already understand the basics of JMS programs, MQSeries, and EJB
beans. These details are in the JMS specification, the EJB V2 specification (both
available from Sun), this manual, the samples provided with MQ JMS, and other
manuals for MQSeries and WebSphere.
Administered objects
JMS uses administered objects to encapsulate vendor-specific information. This
minimizes the impact of vendor-specific details on end-user applications.
Administered objects are stored in a JNDI namespace, and can be retrieved and
used in a portable manner without knowledge of the vendor-specific contents.
You use these objects in exactly the same way as the MQQueueConnectionFactory
and MQTopicConnectionFactory. However, behind the scenes they use the XA
versions of the JMS classes, and enlist the MQ XAResource in the WebSphere
transaction.
MQ_install_dir is the installation directory for MQ JMS, and hostname is the name
or IP address of the machine that is running WebSphere.
To create the new factories, use the define verb with the following two new types:
def WSQCF(name) [properties]
def WSTCF(name) [properties]
These new types use the same properties as the equivalent QCF or TCF types,
except that only the BIND transport type is allowed (and therefore, client
properties cannot be configured). For details, see “Administering JMS objects” on
page 35.
The objects can be cast to, and used as, the generic JMS interfaces. Normally, there
is no need to program to the MQSeries specific classes in the application code.
Samples
There are three samples that illustrate the basics of using MQ JMS with WebSphere
Application Server Advanced Edition. These are in subdirectories of
MQ_install_dir/samples/ws, where MQ_install_dir is the installation directory for
MQ JMS.
v Sample1 demonstrates a simple put and get for a message in a queue by using
container-managed transactions.
v Sample2 demonstrates a simple put and get for a message in a queue by using
bean-managed transactions.
For details about how to build and deploy the EJB beans, please refer to the
WebSphere Application Server documentation.
The readme.txt files in each sample directory include example output from each
EJB bean. The scripts provided assume that a default queue manager is available
on the local machine. If your installation varies from the default, you can edit these
scripts as required.
Sample1
Sample1EJB.java, in the sample1 directory, defines two methods that use JMS:
v putMessage() sends a TextMessage to a queue, and returns the MessageID of the
sent message
v getMessage() reads the message with the specified MessageID back from the
queue
Before you run the sample, you must store two administered objects in the
WebSphere JNDI namespace:
QCF1 a WebSphere-specific queue connection factory
Q1 a queue
To set up the administered objects, you can either use the MQ JMS administration
tool and set them up manually, or you can use the script provided.
To set up the administered objects with typical default settings, you can enter the
following command to run the script admin.scp:
JMSAdmin < admin.scp
The bean must be deployed with the getMessage and putMessage methods marked
as TX_REQUIRED. This ensures that the container starts a transaction before
entering each method, and commits the transaction when the method completes.
Within the methods, you do not need any application code that relates to the
transactional state. However, remember that the message sent from putMessage
occurs under syncpoint, and will not become available until the transaction is
committed.
The client program (or script) takes a single parameter, which is used as the body
of a TextMessage that will be sent by the EJB bean putMessage method. Then, the
getMessage is called to read the message back off the queue and return the body to
the client for display. The EJB bean sends progress messages to the standard
output (stdout) of the application server, so you might wish to monitor that output
during the run.
Sample2
Sample2EJB.java, in the sample2 directory, performs the same task as sample1, and
requires the same administered objects. Unlike sample1, sample2 uses
bean-managed transactions to control the transactional boundaries.
If you have not already run sample1, ensure that you set up the administered
objects QCF1 and Q1, as described in “Sample1” on page 363.
Sample3
Sample3EJB.java, in the sample3 directory, demonstrates the use of the
publish/subscribe API with WebSphere. Publishing a message is very similar to the
point to point case. However, there are differences when receiving messages via a
TopicSubscriber.
To set up the administered objects, you can either use the MQ JMS administration
tool and set them up manually, or you can use a script. The script admin.scp is
provided in the sample3 directory.
To set up the administered objects with typical default settings, you can enter the
following command to run the script admin.scp:
JMSAdmin < admin.scp
If you have already run admin.scp to set up objects for sample1 or sample2, there
will be error messages when you run admin.scp for sample3. (These occur when
you attempt to create the jms and Samples sub-contexts.) You can safely ignore
these error messages.
Also, before you run sample3, ensure that the MQSeries publish/subscribe broker
(SupportPac MA0C) is installed and running.
| As a result, unless you make the changes described in “Changing browser security
| settings” on page 367, when an applet is executed, each and every class that it
| needs must also be available for download from the same location as the applet
| code itself.
| Users intending to use the MQ base Java with CICS Transaction Server for OS/390
| should be familiar with:
| v Customer Information Control System (CICS) concepts
| v Using the CICS Java Application Programming Interface (API)
| v Running Java programs from within CICS
| Users intending to use VisualAge for Java to develop OS/390 UNIX System
| Services High Performance Java (HPJ) applications should be familiar with the
| Enterprise Toolkit for OS/390 (supplied with VisualAge for Java Enterprise Edition
| for OS/390, Version 2).
|
| Environments supported by SupportPac MA1G
| SupportPac MA1G provides support for MQ base Java from the following
| environments:
| v OS/390 V2R6 or higher
| v Java for OS/390, V1.1.8 or higher
| v IBM MQSeries for MVS/ESA, Version 1.2 or higher
| v High Performance Java (HPJ)
| SupportPac MA1G also provides support for CICS TS1.3 or higher. Support for
| HPJ in this environment requires OS/390 V2R9 or higher.
| The following procedure installs the MQSeries classes for Java. The directory used
| for the installation needs at least 2MB of free storage. In the following, replace
| “/u/joe/mqm” with the path name of the directory you choose:
| 1. Remove any previous installation of this product using the following
| commands in the OpenEdition shell:
| cd /u/joe
| chmod -fR 700 mqm
| rm -rf mqm
| mkdir mqm
| 2. Using FTP binary mode, upload the file ma1g.tar.Z from your workstation to
| the HFS directory /u/joe/mqm.
| The program output is placed in the files used for standard and error output.
| Refer to CICS documentation for more information on running Java programs and
| setting the input and output files.
|
| Features not provided by SupportPac MA1G
| SupportPac MA1G provides a subset of features available to other MQ base Java
| applications. In particular, it does not support the ConnectionPooling feature
| described in “Chapter 7. Writing MQ base Java programs” on page 51. The
| following classes and methods are not supported:
| v Classes and Interfaces
| – MQPoolServices
| – MQPoolServicesEvent
| – MQPoolToken
| – MQSimpleConnectionManager
| – MQPoolServicesEventListener
| – MQConnectionManager
| – ManagedConnection
| – ManagedConnectionFactory
| – ManagedConnectionMetaData
| v Methods
| – MQEnvironment.getDefaultConnectionManager()
| – MQEnvironment.setDefaultConnectionManager()
| – MQEnvironment.addConnectionPoolToken()
| – MQEnvironment.removeConnectionPoolToken()
| – The six MQQueueManager constructors which allow a ConnectionManager or
| MQConnectionManager to be specified.
| Attempting to use these classes, interfaces or methods will result in compile-time
| errors or run-time exceptions.
| For more information on running CICS Java transactions, refer to your CICS
| system documentation.
|
| Restrictions under CICS Transaction Server
| In the CICS Transaction Server for OS/390 environment, only the main (first)
| thread is allowed to issue CICS or MQSeries calls. It is therefore not possible to
| share MQQueueManager or MQQueue objects between threads in this
| environment, or to create a new MQQueueManager on a child thread.
| Table 12 on page 74 lists the restrictions and variations which apply to the
| MQSeries classes for Java when running against an OS/390 MQSeries queue
| manager. Additionally, when running under CICS, the transaction control methods
| on MQQueueManager are not supported. Instead of issuing
| MQQueueManager.commit() or MQQueueManager.backout(), applications should
| use the JCICS task synchronization methods, Task.commit() and Task.rollback().
| The Task class is supplied by JCICS in the com.ibm.cics.server package.
IBM may have patents or pending patent applications covering subject matter
described in this information. The furnishing of this information does not give you
any license to these patents. You can send license inquiries, in writing, to:
IBM Director of Licensing
IBM Corporation
North Castle Drive
Armonk, NY 10504-1785
U.S.A.
For license inquiries regarding double-byte (DBCS) information, contact the IBM
Intellectual Property Department in your country or send inquiries, in writing, to:
IBM World Trade Asia Corporation
Licensing
2-31 Roppongi 3-chome, Minato-ku
Tokyo 106, Japan
The following paragraph does not apply to the United Kingdom or any other
country where such provisions are inconsistent with local law:
INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES THIS
PUBLICATION “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS
FOR A PARTICULAR PURPOSE. Some states do not allow disclaimer of express or
implied warranties in certain transactions, therefore this statement may not apply
to you.
Any references in this information to non-IBM Web sites are provided for
convenience only and do not in any manner serve as an endorsement of those Web
sites. The materials at those Web sites are not part of the materials for this IBM
product and use of those Web sites is at your own risk.
IBM may use or distribute any of the information you supply in any way it
believes appropriate without incurring any obligation to you.
The licensed program described in this information and all licensed material
available for it are provided by IBM under terms of the IBM Customer Agreement,
IBM International Programming License Agreement, or any equivalent agreement
between us.
Trademarks
The following terms are trademarks of International Business Machines
Corporation in the United States, or other countries, or both:
Java, HotJava, JDK, and all Java-based trademarks and logos are trademarks or
registered trademarks of Sun Microsystems, Inc. in the United States, other
countries, or both.
UNIX is a registered trademark of The Open Group in the United States and other
countries.
Other company, product, and service names may be trademarks or service marks
of others.
If you do not find the term you are looking for, IIOP. Internet Inter-ORB Protocol.
see the index or the IBM Dictionary of Computing,
Internet Inter-ORB Protocol (IIOP). A standard for
New York: McGraw-Hill, 1994. TCP/IP communications between ORBs from different
vendors.
Abstract Window Toolkit for Java (AWT). A
collection of Graphical User Interface (GUI) instance. An instance is an object. When a class is
components that are implemented using instantiated to produce an object, we say that the object
native-platform versions of the components. is an instance of the class.
applet. A Java program which is designed to run only interface. An interface is a class that contains only
on a Web page. abstract methods and no instance variables. An
interface provides a common set of methods that can
API. Application Programming Interface.
be implemented by subclasses of a number of different
Application Programming Interface (API). An classes.
Application Programming Interface consists of the
Internet. The Internet is a cooperative public network
functions and variables that programmers are allowed
of shared information. Physically, the Internet uses a
to use in their applications.
subset of the total resources of all the currently existing
AWT. Abstract Window Toolkit for Java. public telecommunication networks. Technically, what
distinguishes the Internet as a cooperative public
casting. A term used in Java to describe the explicit network is its use of a set of protocols called TCP/IP
conversion of the value of an object or primitive type (Transmission Control Protocol/Internet Protocol).
into another type.
JAAS. Java Authentication and Authorization Service.
channel. See MQI channel.
Java Authentication and Authorization Service
class. A class is an encapsulated collection of data and (JAAS). A Java service that provides entity
methods to operate on the data. A class may be authentication and access control.
instantiated to produce an object that is an instance of
the class. | Java Development Kit (JDK). A package of software
| distributed for Java developers, by Sun Microsystems
client. In MQSeries, a client is a runtime component | or others. It includes the Java interpreter, Java classes
that provides access to queuing services on a server for | and Java development tools: compiler, debugger,
local user applications. | disassembler, appletviewer, stub file generator, and
| documentation generator.
EJB. Enterprise JavaBeans.
Java Naming and Directory Service (JNDI). An API
encapsulation. Encapsulation is an object-oriented specified in the Java programming language. It
programming technique that makes an object’s data provides naming and directory functions to
private or protected and allows programmers to access applications written in the Java programming language.
and manipulate the data only through method calls.
Java Message Service (JMS). Sun Microsystem’s API
Enterprise JavaBeans (EJB). A server-side component for accessing enterprise messaging systems from Java
architecture, distributed by Sun Microsystems, for programs.
writing reusable business logic and portable enterprise
applications. Enterprise JavaBean components are Java Runtime Environment (JRE). A subset of the
written entirely in Java and run on any EJB compliant Java Development Kit (JDK) that contains the core
server. executables and files that constitute the standard Java
Java Transaction API (JTA). An API that allows MQSeries commands (MQSC). Human-readable
applications and J2EE servers to access transactions. commands, uniform across all platforms, that are used
to manipulate MQSeries objects.
Java Transaction Service (JTS). A transaction manager
that supports JTA and implements the Java mapping of MQSeries Message Descriptor (MQMD). Control
the OMG Object Transaction Service 1.1 specification information that describes the message format and
below the level of the API. properties, that is carried as part of an MQSeries
message.
Java Virtual Machine (JVM). A software
implementation of a central processing unit (CPU) that object. (1) In Java, an object is an instance of a class. A
runs compiled Java code (applets and applications). class models a group of things; an object models a
particular member of that group. (2) In MQSeries, an
Java 2 Platform, Enterprise Edition (J2EE). A set of object is a queue manager, a queue, or a channel.
services, APIs, and protocols that provide the
functionality to develop multi-tiered, Web-based Object Request Broker (ORB). An application
applications. framework that provides interoperability between
objects, built in different languages, running on
JDK. Java Development Kit. different machines, in heterogeneous distributed
environments.
JNDI. Java Naming and Directory Service.
Object Management Group (OMG). A consortium
JMS. Java Message Service. that sets standards in object-oriented programming.
JRE. Java Runtime Environment. OMG. Object Management Group.
JTA. Java Transaction API. ORB. Object Request Broker.
JTS. Java Transaction Service. overloading. The situation where one identifier refers
to multiple items in the same scope. In Java, methods
JVM. Java Virtual Machine.
can be overloaded, but not variables or operators.
J2EE. Java 2 Platform, Enterprise Edition.
package. A package in Java is a way of giving a piece
LDAP. Lightweight Directory Access Protocol. of Java code access to a specific set of classes. Java code
that is part of a particular package has access to all the
Lightweight Directory Access Protocol (LDAP). A classes in the package and to all non-private methods
client-server protocol for accessing a directory service. and fields in the classes.
message. In message queuing applications, a message private. A private field is not visible outside its own
is a communication sent between programs. class.
message queue. See queue. protected. A protected field is visible only within its
own class, within a subclass, or within packages of
message queuing. A programming technique in which which the class is a part
each program within an application communicates with
the other programs by putting messages on queues. public. A public class or interface is visible
everywhere. A public method or variable is visible
method. Method is the object-oriented programming everywhere that its class is visible
term for a function or procedure.
queue. A queue is an MQSeries object. Message
MQDLH. MQSeries dead letter header. See MQSeries queueing applications can put messages on, and get
Application Programming Reference. messages from, a queue
MQI channel. An MQI channel connects an MQSeries queue manager. a queue manager is a system
client to a queue manager on a server system and program the provides message queuing services to
transfers MQI calls and responses in a bidirectional applications.
manner.
Red Hat Package Manager (RPM). A software
MQMD. MQSeries Message Descriptor. packaging system for use on Red Hat Linux platforms,
and other Linux and UNIX platforms.
MQSC. MQSeries commands.
MQSeries for Windows User’s Guide, PDF versions of relevant MQSeries books are
GC33-1822 supplied with these MQSeries products:
MQSeries for Windows, V2.1 v MQSeries for AIX, V5.2
MQSeries for Windows User’s Guide, v MQSeries for AS/400, V5.2
GC33-1965 v MQSeries for Compaq Tru64 UNIX, V5.1
v MQSeries for HP-UX, V5.2
MQSeries for Windows NT and Windows 2000, v MQSeries for Linux, V5.2
V5.2 v MQSeries for OS/2 Warp, V5.1
v MQSeries for OS/390, V5.2
BookManager® format
The MQSeries library is supplied in IBM
BookManager format on a variety of online
library collection kits, including the Transaction
Processing and Data collection kit, SK2T-0730. You
can view the softcopy books in IBM BookManager
format using the following IBM licensed
programs:
BookManager READ/2
BookManager READ/6000
BookManager READ/DOS
BookManager READ/MVS
BookManager READ/VM
BookManager READ for Windows
PostScript format
The MQSeries library is provided in PostScript
(.PS) format with many MQSeries Version 2
products. Books in PostScript format can be
printed on a PostScript printer or viewed with a
suitable viewer.
Bibliography 381
MQSeries on the Internet
Index 385
MQTopicSubscriber class 333 PostScript format 381 QueueRequestor class 293
MQXAConnection class 334 prerequisite software 6 queues, accessing 59
MQXAConnectionFactory class 335 PRIORITY object property 39, 351 QueueSender interface 295
MQXAQueueConnection class 336 problems, solving 17, 29 QueueSession interface 298
MQXAQueueConnectionFactory problems, solving in Publish/Subscribe
class 337 mode 187
MQXAQueueSession class 339
MQXASession class 340
processes, accessing 59
programmers, introduction 47
R
reading strings 61
MQXATopicConnection class 342 programming
receiving
MQXATopicConnectionFactory class 344 bindings connection 52
messages 175
MQXATopicSession class 346 client connections 51
messages in Publish/Subscribe
MSGRETENTION object property 39, compiling 69
mode 181
351 connections 51
RECEXIT object property 39, 351
multithreaded programs 62 multithreaded 62
RECEXITINIT object property 39, 351
MyServerSession.java 217 tracing 70
report options, message 102, 213
MyServerSessionPool.java 217 writing 51
reports, broker 189
programming interface 48
resources, closing 177
programs
restrictions and variations
N JMS, writing 169
Publish/Subscribe, writing 179
to core classes 74, 371
names, of Topics 181 retrieving objects from JNDI 170
running 28, 70
naming considerations, LDAP 37 runjms utility 28, 351
tracing 29
Netscape Navigator, using 6 running
properties
non-durable subscribers 184 applets 70
client 41
applications under CICS Transaction
dependencies 41
Server 371
mapping between admin. tool and
O programs 349
in a Web browser 5
MQSeries classes for Java
object creation, error conditions 43 message 191
programs 70
ObjectMessage of exit strings 42
programs 28
interface 283 of JMS objects 38
standalone program 5
type 175 queue, setting 173
the IVT 22
objects properties and objects, valid
the PSIVT 25
administered 170 combinations 41
with appletviewer 5
JMS, administering 35 PROVIDER_URL parameter 32
your own programs 17
JMS, creating 37 providerutil.jar 7
runtime
JMS, properties 38 PSIVT (Installation Verification Test
creating factories 171
message 191 program) 25
creating Topics 182
retrieving from JNDI 170 PSIVTRun utility 26, 351
errors, handling 177
objects and properties, valid PSReportDump application 189
combinations 41 publications
obtaining MQSeries 379
MQSeries classes for Java 7 publications (Publish/Subscribe), local S
MQSeries classes for Java Message suppressing 184 sample applet
Service 7 publish/subscribe, sample customizing 15
obtaining a session 172 application 364 tracing 17
one-phase optimization, with Publish/Subscribe Installation Verification using to verify 13
WebSphere 362 Test program (PSIVT) 25 with appletviewer 15
operations on queue managers 58 publishing messages 181 sample application
options bean-managed transactions 364
connection 4 bindings mode 56
subscribers 183
OS/390, installing MQ base Java 9
Q container-managed transactions 363
MQ JMS with WebSphere 362
QMANAGER object property 39, 351
overview 3 publish/subscribe 179, 364
Queue
tracing 17
interface 284
using Application Server
object 170
P queue manager
Facilities 219
using to verify 16
package configuring for clients 13
sample classpath settings 11
com.ibm.jms 231 connecting to 58
sample code
com.mq.ibm.jms 230 disconnecting from 58
applet 52
javax.jms 227 operations on 58
ServerSession 215
PDF (Portable Document Format) 380 QUEUE object property 39, 351
ServerSessionPool 215
PERSISTENCE object property 39, 351 queue properties
Sample1EJB.java 363
platform differences 73, 371 setting 173
Sample2EJB.java 364
point-to-point installation verification 22 setting with set methods 174
Sample3EJB.java 364
poison messages 212 QueueBrowser interface 286
schema, LDAP server 353
PORT object property 39, 351 QueueConnection interface 288
schema definition, LDAP 353
Portable Document Format (PDF) 380 QueueReceiver interface 292
T V
V5 extensions 75
TARGCLIENT object property 39, 351
valid combinations of objects and
TCP/IP
properties 41
client verifying 16
verbs, MQSeries supported 48
connection, programming 51
TEMPMODEL object property 39, 351
Index 387
388 MQSeries Using Java
Sending your comments to IBM
If you especially like or dislike anything about this book, please use one of the
methods listed below to send your comments to IBM.
Feel free to comment on what you regard as specific errors or omissions, and on
the accuracy, organization, subject matter, or completeness of this book.
Please limit your comments to the information in this book and the way in which
the information is presented.
To make comments about the functions of IBM products or systems, talk to your
IBM representative or to your IBM authorized remarketer.
When you send comments to IBM, you grant IBM a nonexclusive right to use or
distribute your comments in any way it believes appropriate, without incurring
any obligation to you.
You can send your comments to IBM in any of the following ways:
v By mail, to this address:
User Technologies Department (MP095)
IBM United Kingdom Laboratories
Hursley Park
WINCHESTER,
Hampshire
SO21 2JN
United Kingdom
v By fax:
– From outside the U.K., after your international access code use
44–1962–842327
– From within the U.K., use 01962–842327
v Electronically, use the appropriate network ID:
– IBM Mail Exchange: GBIBM2Q9 at IBMMAIL
– IBMLink™: HURSLEY(IDRCF)
– Internet: [email protected]
SC34-5456-07
Spine information: