Sun Java SystemMessageQueue820-5205

Embed Size (px)

Citation preview

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    1/230

    Sun Java System Message Queue4.2 Developer's Guide or JavaClients

    Sun Microsystems, Inc.4150 Network CircleSanta Clara, CA 95054U.S.A.

    PartNo: 8205205September 2008

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    2/230

    Copyright2008 SunMicrosystems, Inc. 4150 Network Circle, Santa Clara,CA 95054 U.S.A. Allrightsreserved.

    SunMicrosystems, Inc. hasintellectual property rightsrelatingto technology embodied in theproduct that is describedin this document.In particular, andwithoutlimitation, these intellectualpropertyrights mayinclude oneor more U.S. patents or pending patentapplications in theU.S. andin other countries.

    U.S. Government Rights Commercial sotware. Government users are subject to the Sun Microsystems, Inc. standard license agreement and applicableprovisionso theFARand itssupplements.

    This distribution may include materials developed by thirdparties.Partso theproduct maybe derived rom Berkeley BSDsystems, licensed rom theUniversity o Caliornia. UNIXis a registered trademarkin theU.S. andothercountries, exclusivelylicensed through X/OpenCompany, Ltd.

    Sun, SunMicrosystems, theSun logo, theSolaris logo, theJavaCofeeCup logo, docs.sun.com,Java,and Solaris aretrademarks or registered trademarks o SunMicrosystems, Inc. or itssubsidiariesin theU.S. andothercountries. AllSPARC trademarks areused under license andare trademarks or registered trademarks oSPARCInternational,Inc. in theU.S. andothercountries. Products bearing SPARCtrademarks arebasedupon an architecturedeveloped by SunMicrosystems, Inc.

    TheOPEN LOOK andSun GraphicalUser Interacewas developedby SunMicrosystems, Inc. orits users andlicensees. Sunacknowledges thepioneering efortsoXerox in researching anddeveloping theconcept o visualor graphicaluser interaces orthe computer industry.Sun holds a non-exclusive license rom Xerox to theXerox GraphicalUser Interace, which license also coversSun'slicensees whoimplement OPEN LOOK GUIs andotherwise complywith Sun's written licenseagreements.

    Products covered by andinormationcontained in this publication arecontrolled by U.S. ExportControl laws andmay be subjectto theexport or importlaws inother countries. Nuclear,missile,chemicalor biological weapons or nuclear maritime enduses or endusers,whether director indirect,are strictly prohibited. Exportor reexport to countriessubject to U.S. embargo or to entities identiedon U.S. exportexclusion lists,including, butnot limited to,the deniedpersons andspeciallydesignated nationals lists is strictly prohibited.

    DOCUMENTATION IS PROVIDED AS IS AND ALL EXPRESS OR IMPLIEDCONDITIONS, REPRESENTATIONSAND WARRANTIES, INCLUDINGANYIMPLIEDWARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED,EXCEPT TOTHEEXTENTTHAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.

    Copyright2008 SunMicrosystems, Inc. 4150 Network Circle, Santa Clara,CA 95054 U.S.A. Tous droitsrservs.

    SunMicrosystems, Inc. dtient lesdroits de propritintellectuellerelatis la technologie incorpore dans le produit quiest dcritdans ce document.En particulier,

    et ce sans limitation, cesdroits de propritintellectuellepeuvent inclure un ou plusieursbrevets amricains ou desapplications de breveten attente auxEtats-Uniset dans d'autres pays.

    Cette distribution peut comprendredes composants dveloppspar des tierces personnes.

    Certainescomposants de ce produit peuvent tre drives du logiciel Berkeley BSD, licencispar l'Universitde Caliornie. UNIXest unemarque dpose auxEtats-Uniset dans d'autres pays; elle estlicencie exclusivementpar X/OpenCompany,Ltd.

    Sun, SunMicrosystems, le logo Sun, le logo Solaris, le logo Java Cofee Cup, docs.sun.com,Java et Solaris sont desmarques de abrique ou desmarques dposes deSunMicrosystems, Inc., ou sesliales, auxEtats-Uniset dans d'autres pays. Toutesles marques SPARC sont utilisessous licence et sontdes marques de abrique oudesmarques dposes de SPARCInternational,Inc. auxEtats-Uniset dans d'autres pays. Les produits portant lesmarques SPARCsont bass surune architecturedveloppepar Sun Microsystems, Inc.

    L'interace d'utilisation graphiqueOPEN LOOK et Suna tdveloppe parSun Microsystems, Inc. pour ses utilisateurset licencis. Sunreconnat leseforts de

    pionniersde Xerox pour la rechercheet le dveloppement du concept desinteraces d'utilisation visuelle ou graphiquepour l'industrie de l'inormatique.Sun dtientunelicence nonexclusive de Xerox surl'interaced'utilisation graphiqueXerox, cette licence couvrant galementles licencisde Sunqui mettent en place l'interaced'utilisation graphiqueOPEN LOOK et qui, en outre,se conorment auxlicencescrites de Sun.

    Les produits quiont l'objet de cette publication et lesinormations qu'il contient sontrgispar la legislation amricaine en matire de contrle desexportations etpeuvent tre soumisau droit d'autres pays dans le domaine desexportations et importations. Les utilisationsnales, ou utilisateursnaux, pour desarmesnuclaires,des missiles, des armeschimiques ou biologiquesou pour le nuclaire maritime, directementou indirectement, sont strictementinterdites. Les exportations ourexportations vers despays sous embargo desEtats-Unis,ou vers desentits gurantsur leslistes d'exclusion d'exportation amricaines, y compris, mais de manirenonexclusive, la liste de personnesqui ontobjet d'un ordre de ne pasparticiper,d'uneaondirecte ou indirecte, auxexportations desproduitsou desservicesquisont rgispar la legislationamricaine en matire de contrle des exportations et la listede ressortissants spciquement designs, sont rigoureusement interdites.

    LA DOCUMENTATION EST FOURNIE "EN L'ETAT" ET TOUTES AUTRES CONDITIONS, DECLARATIONSET GARANTIES EXPRESSES OU TACITESSONT FORMELLEMENT EXCLUES, DANS LA MESUREAUTORISEE PAR LA LOIAPPLICABLE, Y COMPRISNOTAMMENTTOUTE GARANTIEIMPLICITERELATIVE A LA QUALITE MARCHANDE, A L'APTITUDE A UNEUTILISATION PARTICULIEREOU A L'ABSENCE DE CONTREFACON.

    080901@20795

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    3/230

    Contents

    Preace .....................................................................................................................................................7

    1 Overview ...............................................................................................................................................17

    Setting Up Your Environment ........................................................................................................... 17

    Starting and Testing a Message Broker ............................................................................................. 19

    To Start a Broker .......................................................................................................................... 19

    To Test a Broker ........................................................................................................................... 20

    Developing a Client Application ....................................................................................................... 21

    To Produce Messages .................................................................................................................. 21

    To Consume Messages ................................................................................................................ 23

    Compiling and Running a Client Application ................................................................................. 26

    To Compile and Run the HelloWorldMessageApplication .................................................... 29

    Deploying a Client Application ......................................................................................................... 30

    Example Application Code ................................................................................................................ 31

    2 Usingthe JavaAPI ...............................................................................................................................33

    Messaging Domains ............................................................................................................................ 33

    Working With Connections .............................................................................................................. 34

    Obtaining a Connection Factory ................................................................................................ 35

    Using Connections ...................................................................................................................... 39

    Creating Secure Connctions (SSL) ............................................................................................ 42

    Working With Destinations .............................................................................................................. 43

    Looking Up a Destination With JNDI ....................................................................................... 43

    Instantiating a Destination ......................................................................................................... 45

    Temporary Destinations ............................................................................................................. 46

    Working With Sessions ...................................................................................................................... 47Acknowledgment Modes ............................................................................................................ 48

    3

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    4/230

    Transacted Sessions ..................................................................................................................... 50

    Working With Messages .................................................................................................................... 51

    Message Structure ........................................................................................................................ 51Composing Messages .................................................................................................................. 56

    Sending Messages ........................................................................................................................ . 62

    Receiving Messages ...................................................................................................................... 64

    Processing Messages .................................................................................................................... 71

    3 Message Queue Clients: Design andFeatures ................................................................................ 79Client Design Considerations ............................................................................................................ 79

    Developing Portable Clients ....................................................................................................... 80

    Choosing Messaging Domains ................................................................................................... 80

    Connections and Sessions ........................................................................................................... 81

    Producers and Consumers .......................................................................................................... 82

    Balancing Reliability and Perormance ..................................................................................... 84

    Managing Client Threads ................................................................................................................... 84

    JMS Threading Restrictions ........................................................................................................ 85

    Thread Allocation or Connections ........................................................................................... 85

    Managing Memory and Resources .................................................................................................... 86

    Managing Memory ...................................................................................................................... 86

    Managing Message Size ............................................................................................................... 86

    Managing the Dead Message Queue .......................................................................................... 88

    Managing Physical Destination Limits ..................................................................................... 92

    Programming Issues or Message Consumers ................................................................................. 92

    Using the Client Runtime Ping Feature .................................................................................... 92

    Preventing Message Loss or Synchronous Consumers .......................................................... 93

    Synchronous Consumption in Distributed Applications ....................................................... 93

    Factors Afecting Perormance .......................................................................................................... 94Delivery Mode (Persistent/Nonpersistent) ............................................................................... 95

    Use o Transactions ..................................................................................................................... 95

    Acknowledgment Mode .............................................................................................................. 95

    Durable vs. Nondurable Subscriptions ..................................................................................... 96

    Use o Selectors (Message Filtering) .......................................................................................... 97

    Connection Event Notication .......................................................................................................... 98Connection Events ....................................................................................................................... 98

    Contents

    Sun JavaSystemMessage Queue4.2 Developer's Guide or JavaClients September20084

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    5/230

    Creating an Event Listener .......................................................................................................... 99

    Event Listener Examples ........................................................................................................... 100

    Client Connection Failover (Auto-Reconnect) ............................................................................. 100Enabling Auto-Reconnect ......................................................................................................... 101

    Auto-Reconnect Behaviors ....................................................................................................... 104

    Auto-Reconnect Limitations .................................................................................................... 105

    Handling Exceptions When Failover Occurs ......................................................................... 106

    Custom Client Acknowledgment .................................................................................................... 135

    Using Client Acknowledge Mode ............................................................................................ 135

    Using No Acknowledge Mode .................................................................................................. 137

    Schema Validation o XML Payload Messages .............................................................................. 138

    Communicating with C Clients ....................................................................................................... 139

    Client Runtime Logging ........................................................................................................... ........ 139

    Logging Name Spaces, Levels, and Activities ......................................................................... 140

    Using the JRE Logging Conguration File .............................................................................. 142

    Using a Logging Conguration File or a Specic Application ............................................ 143Setting the Logging Conguration Programmatically .......................................................... 143

    4 Using the Metrics Monitoring API ...................................................................................................145

    Monitoring Overview ....................................................................................................................... 146

    Administrative Tasks ................................................................................................................. 147

    Implementation Summary ....................................................................................................... 147Creating a Metrics-Monitoring Client ............................................................................................ 148

    To Monitor Broker Metrics ....................................................................................................... 148

    Format o Metrics Messages ............................................................................................................. 149

    Broker Metrics ............................................................................................................................ 149

    Metrics Monitoring Client Code Examples ................................................................................... 153

    A Broker Metrics Example ........................................................................................................ 153

    5 WorkingwithSOAP Messages .........................................................................................................161

    What is SOAP? ...................................................................................................................... ............. 161

    SOAP with Attachments API or Java ...................................................................................... 162

    The SOAP Message .................................................................................................................... 164

    SOAP Packaging Models ........................................................................................................... 165SOAP Messaging in JAVA ................................................................................................................ 167

    Contents

    5

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    6/230

    The SOAP Message Object ........................................................................................................ 168

    Destination, Message Factory, and Connection Objects ...................................................... 173

    SOAP Messaging Models and Examples ......................................................................................... 175SOAP Messaging Programming Models ................................................................................. 175

    Working with Attachments ...................................................................................................... 176

    Exception and Fault Handling .................................................................................................. 177

    Writing a SOAP Client .............................................................................................................. 177

    Writing a SOAP Service ............................................................................................................ 179

    Integrating SOAP and Message Queue ........................................................................................... 185

    Example 1: Deerring SOAP Processing .................................................................................. 186

    Example 2: Publishing SOAP Messages .................................................................................. 189

    Code Samples ............................................................................................................................. 190

    A WarningMessagesand ClientError Codes .................................................................................... 197

    Warning Messages and Error Codes ............................................................................................... 198

    Index ................................................................................................................................................... 211

    Contents

    Sun JavaSystemMessage Queue4.2 Developer's Guide or JavaClients September20086

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    7/230

    Preace

    This book provides inormation about concepts and procedures or developing JavaTM

    messaging applications (Java clients) that work with Sun Java System Message Queue (ormerlySunTM ONE Message Queue).

    Who Should UseThis BookThis guide is meant principally or developers o Java applications that use Sun Java SystemMessage Queue.

    These applications use the Java Message Service (JMS) Application Programming Interace(API), and possibly the SOAP with Attachments API or Java (SAAJ), to create, send, receive,and read messages. As such, these applications are JMS clients and/or SOAP client applications,respectively. The JMS and SAAJ specications are open standards.

    This book assumes that you are amiliar with the JMS APIs and with JMS programmingguidelines. Its purpose is to help you optimize your JMS client applications by making best use

    o the eatures and exibility o a Message Queue messaging system.

    This book assumes no amiliarity, however, with SAAJ. This material is described in Chapter 5,Working with SOAP Messages, and assumes only basic knowledge o XML.

    Beore You Read This Book

    You must read the Sun Java System Message Queue 4.2 Technical Overview to become amiliarwith Message Queues implementation o the Java Message Specication, with the componentso the Message Queue service, and with the basic process o developing, deploying, andadministering a Message Queue application.

    7

    http://docs.sun.com/doc/820-4917http://docs.sun.com/doc/820-4917
  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    8/230

    How This Book Is Organized

    This guide is designed to be read rom beginning to end. The ollowing table briey describesthe contents o each chapter:

    TABLE P1 BookContents

    Chapter Description

    Chapter 1, Overview A high-level overview o the Message Queue Java interace. It includes a

    tutorial that acquaints you with the Message Queue development

    environment using a simple example JMS client application.Chapter 2, Using the Java API Explains howto use the Message Queue Java API in your client application.

    Chapter 3, Message Queue

    Clients: Designand Features

    Describes architectural and conguration issues that depend upon Message

    Queues implementation o the Java Message Specication.

    Chapter 4, Using the MetricsMonitoring API

    Describes message-based monitoring, a customized solution to metricsgathering that allows metrics data to be accessed programmatically and

    then to be processed in whatever way suits the consuming client.

    Chapter 5, Working with SOAPMessages

    Explains howyou send and receive SOAP messages with andwithoutMessage Queue support.

    Appendix A, Warning

    Messages and Client Error

    Codes

    Provides reerence inormation or warning messages and error codes

    returned by the Message Queue client runtime when it raisesa JMS

    exception.

    Related DocumentationThe inormation resources listed in this section provide urther inormation about Message

    Queue in addition to that contained in this manual.

    Message Queue Documentation SetThe documents that comprise the Message Queue documentation set are listed in the ollowing

    table in the order in which you might normally use them. These documents are available

    through the Sun documentation Web site at

    http://www.sun.com/documentation/

    Click Sotware, ollowed by Application & Integration Services, and then Message Queue.

    Preace

    Sun JavaSystemMessage Queue4.2 Developer's Guide or JavaClients September20088

    http://www.sun.com/documentation/http://www.sun.com/documentation/
  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    9/230

    TABLE P2 Message QueueDocumentation Set

    Document Audience Description

    Sun Java System Message

    Queue 4.2 Technical

    Overview

    Developers and administrators Describes Message Queue concepts,eatures, and components.

    Sun Java System Message

    Queue 4.2 Release Notes

    Developers and administrators Includes descriptions o new eatures,

    limitations, andknown bugs, as well as

    technical notes.

    Sun Java System Message

    Queue 4.2 Installation Guide

    Developers and administrators Explains how to install Message Queue

    sotware on Solaris, Linux, and Windowsplatorms.

    Sun Java System Message

    Queue 4.2 Developers Guide

    or JavaClients

    Developers Provides a quick-start tutorial and

    programming inormation or developers o

    Java client programs using the MessageQueue implementation o the JMS or

    SOAP/JAXM APIs.

    Sun Java System Message

    Queue 4.2 AdministrationGuide

    Administrators, also

    recommended or developers

    Provides background and inormation

    needed to perorm administration tasksusing Message Queue administration tools.

    Sun Java System Message

    Queue 4.2 Developers Guideor C Clients

    Developers Provides programming and reerence

    documentation ordevelopers o C clientprograms using the Message Queue C

    implementation o the JMSAPI (C-API).

    Sun Java System Message

    Queue 4.2 Developers Guide

    or JMX Clients

    Administrators Provides programming a nd r eerence

    documentation or developers o JMX client

    programs using the Message Queue JMXAPI.

    Online Help

    Message Queue 4.2 includes command-line utilities or perorming Message Queue message

    service administration tasks.

    Message Queue 4.2 also includes a graphical user interace (GUI) administration tool, the

    Administration Console (imqadmin). Context-sensitive help is included in the Administration

    Console; see Administration Console Online Help in Sun Java System Message Queue 4.2

    Administration Guide.

    Preace

    9

    http://docs.sun.com/doc/820-3701http://docs.sun.com/doc/820-3701http://docs.sun.com/doc/820-5204http://docs.sun.com/doc/820-5204http://docs.sun.com/doc/820-5205http://docs.sun.com/doc/820-5205http://docs.sun.com/doc/820-5205http://docs.sun.com/doc/820-4916http://docs.sun.com/doc/820-4916http://docs.sun.com/doc/820-4916http://docs.sun.com/doc/820-5206http://docs.sun.com/doc/820-5206http://docs.sun.com/doc/820-5206http://docs.sun.com/doc/820-5207http://docs.sun.com/doc/820-5207http://docs.sun.com/doc/820-5207http://docs.sun.com/doc/820-4916/aeoba?a=viewhttp://docs.sun.com/doc/820-4916/aeoba?a=viewhttp://docs.sun.com/doc/820-4916/aeoba?a=viewhttp://docs.sun.com/doc/820-4916/aeoba?a=viewhttp://docs.sun.com/doc/820-4916/aeoba?a=viewhttp://docs.sun.com/doc/820-4916/aeoba?a=viewhttp://docs.sun.com/doc/820-5207http://docs.sun.com/doc/820-5207http://docs.sun.com/doc/820-5207http://docs.sun.com/doc/820-5206http://docs.sun.com/doc/820-5206http://docs.sun.com/doc/820-5206http://docs.sun.com/doc/820-4916http://docs.sun.com/doc/820-4916http://docs.sun.com/doc/820-4916http://docs.sun.com/doc/820-5205http://docs.sun.com/doc/820-5205http://docs.sun.com/doc/820-5205http://docs.sun.com/doc/820-5204http://docs.sun.com/doc/820-5204http://docs.sun.com/doc/820-3701http://docs.sun.com/doc/820-3701
  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    10/230

    JavaDoc

    JMS and Message Queue API documentation in JavaDoc ormat is provided at the ollowing

    location:

    Platorm Location

    Solaris /usr/share/javadoc/imq/index.html

    Linux /opt/sun/mq/javadoc/index.html

    Windows IMQ_HOME/javadoc/index.html

    This documentation can be viewed in any HTML browser. It includes standard JMS API

    documentation, as well as Message Queue-specic APIs or Message Queue administered

    objects, which are o value to developers o messaging applications.

    Example Client ApplicationsMessage Queue provides a number o example client applications to assist developers.

    Example Java Client Applications

    Example Java client applications are located in the ollowing directories, depending on

    platorm. See the README les located in these directories and their subdirectories or descriptiveinormation about the example applications.

    Platorm Location

    Solaris /usr/demo/imq/

    Linux /opt/sun/mq/examples

    Windows IMQ_HOME/demo/

    where IMQ_HOME is the Message Queue home directory

    Example C Client Programs

    Example C client applications are located in the ollowing directories, depending on platorm.

    See the README les located in these directories and their subdirectories or descriptive

    inormation about the example applications.

    Preace

    Sun JavaSystemMessage Queue4.2 Developer's Guide or JavaClients September200810

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    11/230

    Platorm Location

    Solaris /opt/SUNWimq/demo/C/

    Linux /opt/sun/mq/examples/C/

    Windows IMQ_HOME/demo/C/

    where IMQ_HOME is the Message Queue home directory

    Example JMX Client Programs

    Example Java Management Extensions (JMX) client applications are located in the ollowing

    directories, depending on platorm. See the README les located in these directories and theirsubdirectories or descriptive inormation about the example applications.

    Platorm Location

    Solaris /opt/SUNWimq/demo/imq/jmx

    Linux /opt/sun/mq/examples/jmx

    Windows IMQ_HOME\demo\jmx

    where IMQ_HOME is the Message Queue home directory

    The Java Message Service (JMS) SpecifcationThe JMS specication can be ound at the ollowing location:

    (http://java.sun.com/products/jms/docs.html )

    The specication includes sample client code.

    The SOAP with Attachments API or Java (SAAJ)Specifcation

    The SOAP with Attachments API or Java (SAAJ) Specifcation can be ound at the ollowinglocation:

    http://java.sun.com/xml/downloads/saaj.html

    The specication includes sample client code.

    Books on JMS ProgrammingFor background on using the JMS API, you can consult the ollowing publicly-available books:

    Preace

    11

    http://java.sun.com/products/jms/docs.htmlhttp://java.sun.com/products/jms/docs.htmlhttp://java.sun.com/products/jms/docs.htmlhttp://java.sun.com/xml/downloads/saaj.htmlhttp://java.sun.com/xml/downloads/saaj.htmlhttp://java.sun.com/products/jms/docs.html
  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    12/230

    Java Message Service by Richard Monson-Haeel and David A. Chappell, OReilly andAssociates, Inc., Sebastopol, CA

    Proessional JMS by Scott Grant, Michael P. Kovacs, Meeraj Kunnumpurath, Silvano Mafeis,K. Scott Morrison, Gopalan Suresh Raj, Paul Giotta, and James McGovern, Wrox Press Inc.,ISBN: 1861004931

    Practical Java Message Service by Tarak Modi, Manning Publications, ISBN: 1930110138

    Directory Variable ConventionsMessage Queue makes use o three directory variables; how they are set varies rom platorm toplatorm. Table P3 describes these variables and how they are used on the Solaris, Linux, andWindows platorms.

    Note The inormation in Table P3 applies only to the standalone installation o MessageQueue. When Message Queue is installed and run as part o an Application Server installation,the values o the directory variables are set diferently: IMQ_HOME is set to

    appServer_install_dir/imq (where appServer_install_diris the Application Server installationdirectory), and IMQ_VARHOME isset to appServer_domainName_dir/imq (whereappServer_domainName_diris the domain directory or the domain starting the MessageQueue broker).

    TABLE P3 DirectoryVariable Conventions

    Variable Description

    IMQ_HOME Used in Message Queue documentation to reer to the Message Queue base

    directory (root installation directory): On Solaris andLinux, there is no root Message Queue installation directory.

    Thereore IMQ_HOME is not used in Message Queue documentation to reer to

    le locations in Solaris andLinux.

    On Windows, the root Message Queue installation directory is set to the

    directoryin which you unzip the Message Queue bundle.

    IMQ_VARHOME The /var directory in which Message Queue temporary or dynamically-createdconguration anddata les are stored. It can be set as an environment variable to

    point to any directory. On Solaris, IMQ_VARHOME deaults to the /var/imq directory.

    On Solaris, or Sun Java System Application Server, Evaluation Edition,

    IMQ_VARHOME deaults to the IMQ_HOME/var directory.

    On Linux, IMQ_VARHOME deaults to the /var/opt/sun/mq directory.

    On Windows, IMQ_VARHOME deaults to the IMQ_HOME/var directory.

    Preace

    Sun JavaSystemMessage Queue4.2 Developer's Guide or JavaClients September200812

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    13/230

    TABLE P3 DirectoryVariable Conventions (Continued)

    Variable Description

    IMQ_JAVAHOME An environment variable that points to the location o the Java runtime (JRE)

    required by Message Queue executables: On Solaris, IMQ_JAVAHOME looks or the latest JDK, but a user can optionally set

    the value to wherever the preerredJRE resides.

    On Linux, Message Queue looks orthe latest JDK, but a user can optionally set

    the value oIMQ_JAVAHOME to wherever the preerred JRE resides.

    On Windows, IMQ_JAVAHOME will be set topoint to an existing Java runtime i a

    supported version is ound on the system. I a supported version is not ound,

    one will be installed.

    In this guide, IMQ_HOME, IMQ_VARHOME, and IMQ_JAVAHOME are shown withoutplatorm-specic

    environment variable notation or syntax (or example, $IMQ_HOME on UNIX). Path names

    generally use UNIX directory separator notation (/).

    Typographic Conventions

    The ollowing table describes the typographic conventions that are used in this book.

    TABLE P4 TypographicConventions

    Typeace Meaning Example

    AaBbCc123 The names o commands, les, and directories,

    and onscreen computer output

    Edit your .login le.

    Use ls -a to list all les.

    machine_name% you have mail.

    AaBbCc123 What you type, contrasted with onscreen

    computer output

    machine_name% su

    Password:

    aabbcc123 Placeholder: replace with a real name orvalue The command toremove a le is rm

    flename.

    AaBbCc123 Book titles, new terms, and terms tobe

    emphasized

    Read Chapter 6 in the User's Guide.

    A cache is a copythatis storedlocally.

    Do notsave the le.

    Note: Some emphasized items

    appear bold online.

    Preace

    13

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    14/230

    Shell Prompts in Command ExamplesThe ollowing table shows the deault UNIX system prompt and superuser prompt or the Cshell, Bourne shell, Korn shell, and Windows operating system.

    TABLE P5 Shell Prompts

    Shell Prompt

    C shell machine_name%

    C shell orsuperuser machine_name#

    Bourne shell andKorn shell $

    Bourne shell andKorn shell or superuser #

    Windows C:\

    Symbol ConventionsThe ollowing table explains symbols that might be used in this book.

    TABLE P6 SymbolConventions

    Symbol Description Example Meaning

    [ ] Contains optional arguments

    and command options.

    ls [-l] The -l option is not required.

    { | } Contains a set o choices or arequired command option.

    -d {y|n} The -d option requires that you useeither the y argument or the nargument.

    ${ } Indicates a variable

    reerence.${com.sun.javaRoot} Reerences the value o the

    com.sun.javaRootvariable.

    - Joins simultaneous multiple

    keystrokes.

    Control-A Press t he C ontrol key while y ou press

    the A key.

    + Joins consecutive multiple

    keystrokes.

    Ctrl+A+N Press the C ontrol key, release i t, a nd

    then press the subsequent keys.

    Indicates menu item

    selection in a graphical user

    interace.

    FileNewTemplates From the File menu, chooseNew.

    From the New submenu, choose

    Templates.

    Preace

    Sun JavaSystemMessage Queue4.2 Developer's Guide or JavaClients September200814

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    15/230

    Documentation, Support, andTrainingThe Sun web site provides inormation about the ollowing additional resources:

    Documentation (http://www.sun.com/documentation/) Support (http://www.sun.com/support/) Training (http://www.sun.com/training/)

    Searching Sun Product Documentation

    Besides searching Sun product documentation rom the docs.sun.com web site, you can use asearch engine by typing the ollowing syntax in the search eld:

    search-term site:docs.sun.com

    For example, to search or broker, type the ollowing:

    broker site:docs.sun.com

    To include other Sun web sites in your search (or example,java.sun.com, www.sun.com, anddevelopers.sun.com),usesun.cominplaceodocs.sun.com in the search eld.

    Third-Party Web Site ReerencesThird-party URLs are reerenced in this document and provide additional, related inormation.

    Note Sun is not responsible or the availability o third-party web sites mentioned in thisdocument. Sun does not endorse and is not responsible or liable or any content, advertising,products, or other materials that are available on or through such sites or resources. Sun will notbe responsible or liable or any actual or alleged damage or loss caused or alleged to be caused byor in connection with use o or reliance on any such content, goods, or services that are availableon or through such sites or resources.

    Sun Welcomes Your CommentsSun is interested in improving its documentation and welcomes your comments andsuggestions. To share your comments, go to http://docs.sun.com and click Send Comments.In the online orm, provide the ull document title and part number. The part number is a7-digit or 9-digit number that can be ound on the book's title page or in the document's URL.For example, the part number o this book is 819-4469.

    Preace

    15

    http://www.sun.com/documentation/http://www.sun.com/support/http://www.sun.com/support/http://www.sun.com/training/http://docs.sun.com/http://java.sun.com/http://java.sun.com/http://www.sun.com/http://www.sun.com/http://developers.sun.com/http://docs.sun.com/http://docs.sun.com/http://developers.sun.com/http://www.sun.com/http://java.sun.com/http://docs.sun.com/http://www.sun.com/training/http://www.sun.com/support/http://www.sun.com/documentation/
  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    16/230

    16

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    17/230

    Overview

    This chapter provides an overall introduction to Sun JavaTM System Message Queue and aquick-start tutorial. It describes the procedures needed to create, compile, and run a simpleexample application. Beore reading this chapter, you should be amiliar with the conceptspresented in the Sun Java System Message Queue 4.2 Technical Overview

    The chapter covers the ollowing topics:

    Setting Up Your Environment on page 17 Starting and Testing a Message Broker on page 19 Developing a Client Application on page 21 Compiling and Running a Client Application on page 26 Deploying a Client Application on page 30 Example Application Code on page 31

    The minimum Java Development Kit (JDK) level required to compile and run Message Queueclients is 1.2. For the purpose o this tutorial it is sucient to run the Message Queue messagebroker in a deault conguration. For instructions on conguring a message broker, seeChapter 4, Conguring a Broker, in Sun Java System Message Queue 4.2 Administration Guide

    Setting Up Your EnvironmentThe Message Queue les that need to be used in conjunction with Message Queue Java clientscan be ound in the lib directory in the installed location or Message Queue on your platorm.Message Queue Java clients need to be able to use several .jar les ound in the lib directorywhen these clients are compiled and run.

    You need to set the CLASSPATH environment variable when compiling and running a JMS client.(The IMQ_HOMEvariable, where used, reers to the directory where Message Queue is installed onWindows platorms and on some Sun Java System Application Server platorms.)

    The value oCLASSPATH depends on the ollowing actors:

    1C H A P T E R 1

    17

    http://docs.sun.com/doc/820-4917http://docs.sun.com/doc/820-4916/aeocl?a=viewhttp://docs.sun.com/doc/820-4916/aeocl?a=viewhttp://docs.sun.com/doc/820-4916/aeocl?a=viewhttp://docs.sun.com/doc/820-4917
  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    18/230

    The platorm on which you compile or run The JDK version you are using Whether you are compiling or running a JMS application Whether your application uses the Simple Object Access Protocol (SOAP) Whether your application uses the SOAP/JMS transormer utilities

    The ollowing table shows the directories where .jar les are to be ound on the various

    platorms.

    TABLE 11 .jar FileLocations

    Platorm Directory

    SolarisTM /usr/share/lib/

    Solaris, using the standalone version o Sun JavaSystem Application Server

    IMQ_HOME/lib/

    Linux /opt/mq/lib/

    Windows IMQ_HOME\lib\

    The table below lists the .jar les you need to compile and run diferent kinds o code.

    TABLE 12 .jar Files Needed in CLASSPATH

    Type o Code To Compile To Run Remarks

    JMS client jms.jar imq.jar

    jndi.jar

    jms.jar imq.jar

    jndi.jar

    Directory containingcompiled Java

    application or .

    See discussion o JNDI .jar les,

    ollowing this table.

    SOAP Client saaj-api.jaractivation.jar

    saaj-api.jar

    Directory containing

    compiled Java

    application or .

    See Chapter 5, Working with SOAP

    Messages

    SOAP Servlet jaxm-api.jar

    saaj-api.jar

    activation.jar

    Sun Java System Application Server

    already includes these .jar les orSOAP servlet support.

    Code using

    SOAP/JMS

    transormer utilities

    imqxm.jar

    .jar les or JMS and

    SOAP clients

    imqxm.jar Also a dd the appropriate .jar les

    listed in this table or the kind o code

    you are writing.

    Setting UpYourEnvironment

    Sun JavaSystemMessage Queue4.2 Developer's Guide or JavaClients September200818

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    19/230

    A client application must be able to access the le jndi.jar even i the application does not usethe Java Naming and Directory Interace (JNDI) directly to look up Message Queueadministered objects. This is because JNDI is reerenced by the Destination and

    ConnectionFactory classes.

    JNDI .jar les are bundled with JDK 1.4. Thus, i you are using this JDK, you do not have toadd jndi.jar to your CLASSPATH setting. However, i you are using an earlier version o theJDK, you must include jndi.jar in your CLASSPATH.

    I you are using JNDI to look up Message Queue administered objects, you must also includethe ollowing les in your CLASSPATH setting:

    I you are using the le-system service provider or JNDI (with any JDK version), you mustinclude the le fscontext.jar.

    I you are using the Lightweight Directory Access Protocol (LDAP) context

    with JDK 1.2 or 1.3, include the les ldabbp.jar,and fscontext.jar.ldap.jar, with JDK 1.4, all les are already bundled with this JDK.

    Starting and Testing a Message BrokerThis tutorial assumes that you do not have a Message Queue message broker currently running.(I you run the broker as a UNIX startup process or Windows service, then it is already runningand you can skip to Developing a Client Application on page 21.)

    To Start a Broker

    In a terminal window, change to thedirectory containing Message Queue executables (see the

    table below).

    Platorm Location

    Solaris /usr/bin/

    Linux /opt/sun/mq/bin/

    Windows IMQ_HOME\bin\

    Run thebroker startup command(imqbrokerd) as ollows:

    imqbrokerd -tty

    The -tty option causes all logged messages to be displayed to the terminal console (in additionto the log le). The broker will start and display a ew messages beore displaying the message

    imqbroker@host:7676 ready

    1

    2

    Starting andTesting a Message Broker

    Chapter 1 Overview 19

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    20/230

    The broker is now ready and available or clients to use.

    To Test a BrokerOne simple way to check the broker startup is by using the Message Queue command utility(imqcmd) to display inormation about the broker:

    In a separate terminal window, change to the directory containing Message Queue executables

    (see thetableshownat thebeginning o thesection To Starta Brokeron page19).

    Run imqcmd with the ollowing arguments:imqcmd query bkr -u admin

    Supply the deault password oadmin when prompted to do so. The output displayed should besimilar to that shown in the next example.

    Output From Testing a Broker

    % imqcmd query bkr -u admin

    Querying the broker specified by:

    -------------------------

    Host Primary Port

    -------------------------

    localhost 7676

    Version 3.6

    Instance Name imqbroker

    Primary Port 7676

    Current Number of Messages in System 0

    Current Total Message Bytes in System 0

    Max Number of Messages in System unlimited (-1)

    Max Total Message Bytes in System unlimited (-1)

    Max Message Size 70m

    Auto Create Queues true

    Auto Create Topics true

    Auto Created Queue Max Number of Active Consumers 1

    Auto Created Queue Max Number of Backup Consumers 0

    Cluster Broker List (active)

    Cluster Broker List (configured)

    1

    2

    Example 11

    Starting andTesting a Message Broker

    Sun JavaSystemMessage Queue4.2 Developer's Guide or JavaClients September200820

    D l i Cli t A li ti

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    21/230

    Cluster Master Broker

    Cluster URL

    Log Level INFOLog Rollover Interval (seconds) 604800

    Log Rollover Size (bytes) unlimited (-1)

    Successfully queried the broker.

    Current Number of Messages in System 0

    Developing a Client ApplicationThis section introduces the general procedures or interacting with the Message Queue API toproduce and consume messages. The basic steps shown here are elaborated in greater detail inChapter 2, Using the Java API, The procedures or producing and consuming messages have anumber o steps in common, which need not be duplicated i the same client is perorming bothunctions.

    To Produce Messages

    Get a connection actory.

    A Message Queue ConnectionFactory object encapsulates all o the needed congurationproperties or creating connections to the Message Queue message service. You can obtain suchan object either by direct instantiation.

    ConnectionFactory myFctry = new com.sun.messaging.ConnectionFactory();

    or by looking up a predened connection actory using the Java Naming and DirectoryInterace (JNDI). In the latter case, all o the connection actorys properties will have beenprecongured to the appropriate values by your Message Queue administrator. I youinstantiate the actory object yoursel, you may need to congure some o its propertiesexplicitly: or instance,

    myFctry.setProperty(ConnectionConfiguration.imqAddressList,"localhost:7676, broker2:5000, broker3:9999");

    myFctry.setProperty(ConnectionConfiguration.imqReconnectEnabled, "true");

    See Obtaining a Connection Factory on page 35 or urther discussion.

    Create a connection.

    A Connection object is an active connection to the Message Queue message service, created bythe connection actory you obtained in Developing a Client Application on page 21:

    Connection myConnection = myFactory.createConnection();

    1

    2

    Developing a Client Application

    Chapter 1 Overview 21

    Developing a Client Application

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    22/230

    See Using Connections on page 39 or urther discussion.

    Create a session or communicating with the message service.

    A Session object represents a single-threaded context or producing and consuming messages.

    Every session exists within the context o a particular connection and is created by that

    connections createSession method:

    Session mySession = myConnection.createSession(false,

    Session.AUTO_ACKNOWLEDGE);

    The rst (boolean) argument species whether the session is transacted. The second argument

    is the acknowledgment mode, such as AUTO_ACKNOWLEDGE, CLIENT_ACKNOWLEDGE, or

    DUPS_OK_ACKNOWLEDGE; these are dened as static constants in the JMS Session interace. SeeAcknowledgment Modes on page 48 and Transacted Sessions on page 50 or urther

    discussion.

    Geta destination to which to send messages.

    A Destination object encapsulates provider-specic naming syntax and behavior or a

    message destination, which may be either aqueue or a point-to-point publish/subscribe topic

    (see Messaging Domains on page 33). You can obtain such an object by direct instantiationDestination myDest = new com.sun.messaging.Queue("myDest");

    or by looking up a predened destination using the JNDI API. See Working With

    Destinations on page 43 or urther discussion.

    Create a message producer or sending messagesto this destination.

    A MessageProducer object is created by a session and associated with a particular destination:

    MessageProducer myProducer = mySession.createProducer(myDest);

    See Sending Messages on page 62 or urther discussion.

    Create a message.

    A Session object provides methods or creating each o the six types o message dened by

    JMS: text, object, stream, map, bytes, and null messages. For instance, you can create a text

    message with the statement

    TextMessage outMsg = mySession.createTextMessage();

    See Composing Messages on page 56 or urther discussion.

    Set the messages content and properties.

    Each type o message has its own methods or speciying the contents o the message body. For

    instance, you can set the content o a text message with the statement

    outMsg.setText("

    Hello, World!"

    );

    3

    4

    5

    6

    7

    Developing a Client Application

    Sun JavaSystemMessage Queue4.2 Developer's Guide or JavaClients September200822

    Developing a Client Application

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    23/230

    You can also use the property mechanism to dene custom message properties o your own: orinstance,

    outMsg.setStringProperty("

    MagicWord"

    ,"

    Shazam"

    );

    See Working With Messages on page 51 or urther discussion.

    Sendthe message.

    The message producers send method sends a message to the destination with which theproducer is associated:

    myProducer.send(outMsg);

    See Sending Messages on page 62 or urther discussion.

    Close the session.

    When there are no more messages to send, you should close the session

    mySession.close();

    allowing Message Queue to ree any resources it may have associated with the session. SeeWorking With Sessions on page 47 or urther discussion.

    Close the connection.

    When all sessions associated with a connection have been closed, you should close theconnection by calling its close method:

    myConnection.close();

    See Using Connections on page 39 or urther discussion.

    To Consume Messages

    Get a connection actory.

    A Message Queue ConnectionFactory object encapsulates all o the needed congurationproperties or creating connections to the Message Queue message service. You can obtain suchan object either by direct instantiation

    ConnectionFactory myFctry = new com.sun.messaging.ConnectionFactory();

    or by looking up a predened connection actory using the Java Naming and DirectoryInterace (JNDI). In the latter case, all o the connection actorys properties will have beenprecongured to the appropriate values by your Message Queue administrator. I youinstantiate the actory object yoursel, you may need to congure some o its propertiesexplicitly: or instance,

    myFctry.setProperty(ConnectionConfiguration.imqAddressList,

    "localhost:7676, broker2:5000, broker3:9999");

    8

    9

    10

    1

    Developing a Client Application

    Chapter 1 Overview 23

    Developing a Client Application

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    24/230

    myFctry.setProperty(ConnectionConfiguration.imqReconnectEnabled, "true");

    See Obtaining a Connection Factory on page 35 or urther discussion.

    Create a connection.

    A Connection object is an active connection to the Message Queue message service, created bythe connection actory you obtained in Developing a Client Application on page 21:

    Connection myConnection = myFactory.createConnection();

    See Using Connections on page 39 or urther discussion.

    Create a session or communicating with the message service.

    A Session object represents a single-threaded context or producing and consuming messages.Every session exists within the context o a particular connection and is created by thatconnections createSession method:

    Session mySession = myConnection.createSession(false,

    Session.AUTO_ACKNOWLEDGE);

    The rst (boolean) argument species whether the session is transacted. The second argumentis the acknowledgment mode, such as AUTO_ACKNOWLEDGE, CLIENT_ACKNOWLEDGE, orDUPS_OK_ACKNOWLEDGE; these are dened as static constants in the JMS Session interace. SeeAcknowledgment Modes on page 48 and Transacted Sessions on page 50 or urtherdiscussion.

    Geta destination rom which to receive messages.

    A Destination object encapsulates provider-specic naming syntax and behavior or amessage destination, which may be either a point-to-point queue or a publish/subscribe topic

    (see Messaging Domains on page 33). You can obtain such an object by direct instantiationDestination myDest = new com.sun.messaging.Queue("myDest");

    or by looking up a predened destination using the JNDI API. See Working WithDestinations on page 43 or urther discussion.

    Create a message consumer or receiving messages rom this destination.

    A MessageConsumer object is created by a session and associated with a particular destination:

    MessageConsumer myConsumer = mySession.createConsumer(myDest);

    See Receiving Messages on page 64 or urther discussion.

    Start the connection.

    In order or a connections message consumers to begin receiving messages, you must starttheconnection by calling its start method:

    myConnection.start();

    See Using Connections on page 39 or urther discussion.

    2

    3

    4

    5

    6

    p g pp

    Sun JavaSystemMessage Queue4.2 Developer's Guide or JavaClients September200824

    Developing a Client Application

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    25/230

    Receive a message.

    The message consumers receive method requests a message rom the destination with whichthe consumer is associated:

    Message inMsg = myConsumer.receive();

    This method is used or synchronous consumption o messages. You can also congure amessage consumer to consume messages asynchronously, by creating a message listenerandassociating it with the consumer. See Receiving Messages on page 64 or urther discussion.

    Retrieve the messages contentand properties.

    Each type o message has its own methods or extracting the contents o the message body. For

    instance, you can retrieve the content o a text message with the statements

    TextMessage txtMsg = (TextMessage) inMsg;

    String msgText = txtMsg.getText();

    In addition, you may need to retrieve some o the messages header elds: or instance,

    msgPriority = inMsg.getJMSPriority();

    You can also use message methods to retrieve custom message properties o your own: or

    instance,

    magicWord = inMsg.getStringProperty("MagicWord");

    See Processing Messages on page 71 or urther discussion.

    Close the session.

    When there are no more messages to consume, you should close the session

    mySession.close();

    allowing Message Queue to ree any resources it may have associated with the session. SeeWorking With Sessions on page 47 or urther discussion.

    Close the connection.

    When all sessions associated with a connection have been closed, you should close theconnection by calling its close method:

    myConnection.close();

    See Using Connections on page 39 or urther discussion.

    7

    8

    9

    10

    Chapter 1 Overview 25

    Compilingand Running a Client Application

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    26/230

    Compiling and Running a Client ApplicationThis section leads you through the steps needed to compile and run a simple example client

    application, HelloWorldMessage, that sends a message to a destination and then retrieves thesame message rom the destination. The code shown in Example 12 is adapted and simpliedrom an example program provided with the Message Queue installation: error checking andstatus reporting have been removed or the sake o conceptual clarity. You can nd thecomplete original program in the helloworld directory in the ollowing locations.

    Solaris: /usr/demo/imq/ Linux: opt/sun/mq/examples Windows: IMQ_HOME/demo

    EXAMPLE 12 Simple Message QueueClient Application

    // Import the JMS and JNDI API classes

    import javax.jms.*;

    import javax.naming.*;

    import java.util.Hashtable;

    public class HelloWorldMessage

    {

    /**

    * Main method

    *

    * Parameter args not used

    **/

    public static void main (String[] args)

    {

    try

    {

    // Get a connection factory.

    //

    // Create the environment for constructing the initial JNDI

    // naming context.

    Hashtable env = new Hashtable();

    // Store the environment attributes that tell JNDI which

    // initial context

    // factory to use and where to find the provider.

    // (On Unix, use provider URL "file:///imq_admin_objects"

    Sun JavaSystemMessage Queue4.2 Developer's Guide or JavaClients September200826

    Compilingand Running a Client Application

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    27/230

    EXAMPLE 12 Simple Message QueueClientApplication (Continued)

    // instead of"file:///C:/imq_admin_objects".)

    env.put(Context.INITIAL_CONTEXT_FACTORY,

    "com.sun.jndi.fscontext.RefFSContextFactory ");

    env.put(Context.PROVIDER_URL,"file:///C:/imq_admin_objects");

    // Create the initial context.

    Context ctx = new InitialContext(env);

    // Look up connection factory object in the JNDI object store.

    String CF_LOOKUP_NAME = "MyConnectionFactory";

    ConnectionFactory myFactory =

    (ConnectionFactory) ctx.lookup(CF_LOOKUP_NAME);

    // Create a connection.

    Connection myConnection = myFactory.createConnection();

    // Create a session.

    Session mySession = myConnection.createSession(false,

    Session.AUTO_ACKNOWLEDGE);

    // Look up the destination object in the JNDI object store.

    String DEST_LOOKUP_NAME = "MyDest";

    Destination myDest = (Destination) ctx.lookup

    (DEST_LOOKUP_NAME);

    // Create a message producer.

    MessageProducer myProducer = mySession.createProducer(myDest);

    // Create a message consumer.

    MessageConsumer myConsumer = mySession.createConsumer(myDest);

    Chapter 1 Overview 27

    Compilingand Running a Client Application

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    28/230

    EXAMPLE 12 Simple Message QueueClient Application (Continued)

    // Create a message.

    TextMessage outMsg = mySession.createTextMessage

    ("Hello, World!");

    // Send the message to the destination.

    System.out.println("Sending message: " + outMsg.getText());

    myProducer.send(outMsg);

    // Start the connection.

    myConnection.start();

    // Receive a message from the destination.

    Message inMsg = myConsumer.receive();

    // Retrieve the contents of the message.

    if (inMsg instanceof TextMessage)

    { TextMessage txtMsg = (TextMessage) inMsg;

    System.out.println("

    Received message:"

    +txtMsg.getText());

    }

    // Close the session and the connection.

    mySession.close();

    myConnection.close();

    }

    catch (Exception jmse)

    { System.out.println("Exception occurred: " + jmse.toString() );

    jmse.printStackTrace();

    }

    }

    Sun JavaSystemMessage Queue4.2 Developer's Guide or JavaClients September200828

    Compilingand Running a Client Application

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    29/230

    EXAMPLE 12 Simple Message QueueClientApplication (Continued)

    }

    To compile and run Java clients in a Message Queue environment, it is recommended that youuse the Java 2 SDK, Standard Edition, version 1.4 or later. You can download the recommendedSDK rom the ollowing location:

    http://java.sun.com/j2se/1.5

    Be sure to set your CLASSPATH environment variable correctly, as described in Setting Up YourEnvironment on page 17, beore attempting to compile or run a client application.

    Note I you are using JDK 1.5, you will get compiler errors i you use the unqualied JMS Queueclass along with the ollowing import statement.

    import java.util.*

    This is because the packagesjava.util and javax.jms both contain a class named Queue. Toavoid the compilation errors, you must eliminate the ambiguity by either ully qualiyingreerences to the JMS Queue class as javax.jms.Queue or correcting your import statements toreer to specic individual java.util classes.

    The ollowing steps or compiling and running theHelloWorldMessage

    application areurnished strictly as an example. The program is shipped precompiled; you do not actually needto compile it yoursel (unless, o course, you modiy its source code).

    To Compile and Run the HelloWorldMessageApplication

    Make the directory containing the application your current directory.

    The Message Queue example applications directory on Solaris is not writable by users, so copythe HelloWorldMessage application to a writable directory and make that directory yourcurrent directory.

    Compile the HelloWorldMessage application:

    javac HelloWorldMessage.java

    This creates the le HelloWorldMessage.class in your current directory.

    1

    2

    Chapter 1 Overview 29

    Deploying a Client Application

    http://java.sun.com/j2se/1.5http://java.sun.com/j2se/1.5
  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    30/230

    Runthe HelloWorldMessage application:

    java HelloWorldMessage

    The program should display the ollowing output:

    Sending Message: Hello, World!

    Received Message: Hello, World!

    Deploying a Client ApplicationWhen you are ready to deploy your client application, you should make sure your Message

    Queue administrator knows your applications needs. The checklist shown below summarizesthe inormation required; consult with your administrator or specic details. In some cases, itmay be useul to provide a range o values rather than a specic value. See Chapter 9, ManagingAdministered Objects, in Sun Java System Message Queue 4.2 Administration Guide or detailson conguration and on attribute names and deault values or administered objects.

    Administered Objects

    Connection Factories

    Type JNDI lookup name Other attributes

    Destinations

    Type (queue or topic) JNDI lookup name Physical destination name

    Physical Destinations

    Type Name Attributes Maximum number o messages expected Maximum size o messages expected Maximum message bytes expected

    Broker or Broker Cluster

    Name Port Properties

    Dead Message Queue

    Place dead messages on dead message queue? Log placement o messages on dead message queue? Discard body o messages placed on the dead message queue?

    3

    Sun JavaSystemMessage Queue4.2 Developer's Guide or JavaClients September200830

    Example Application Code

    http://docs.sun.com/doc/820-4916/aeogu?a=viewhttp://docs.sun.com/doc/820-4916/aeogu?a=viewhttp://docs.sun.com/doc/820-4916/aeogu?a=viewhttp://docs.sun.com/doc/820-4916/aeogu?a=viewhttp://docs.sun.com/doc/820-4916/aeogu?a=view
  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    31/230

    Example Application CodeThe Message Queue installation includes example programs illustrating both JMS and JAXM

    messaging (see Chapter 5, Working with SOAP Messages). They are located in the ollowingdirectories:

    On Solaris: /usr/demo/imq On Linux: /opt/sun/mq/examples On Windows: IMQ_HOME\demo\

    Each directory (except the JMS directory) contains a README le describing the source lesincluded in that directory. The table below lists the directories o interest to Message Queue Javaclients.

    TABLE 13 Example Programs

    Directory Contents

    helloworld Sample programs showing howto create anddeploy a JMS client in

    Message Queue, including the steps required to create administered objects

    and tolookup such objects with JNDIromwithin client code

    jms Sample programs demonstrating the use o the JMS API with MessageQueue

    jaxm Sample programs demonstrating the use o SOAP messages in conjunctionwith JMS in Message Queue

    applications Four subdirectories containing source code or the ollowing: A GUI application using the JMS API to implement a simple chat

    application

    A GUI application using the Message Queue JMS monitoring API to

    obtain a list o queues rom a Message Queue brokerand browse their

    contents with a JMS queue browser

    The Message Queue Ping demo program

    The Message Queue Applet demo program

    monitoring Sample programs demonstrating the use o the JMS API to monitor a

    message broker

    jdbc Examples orplugging in a PointBase and an Oracle database

    imqobjmgr Examples oimqobjmgr command les

    Chapter 1 Overview 31

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    32/230

    32

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    33/230

    Using the Java API

    This chapter describes how to use the classes and methods o the Message Queue Java

    application programming interace (API) to accomplish specic tasks, and provides brie code

    samples to illustrate some o these tasks. (For clarity, the code samples shown in the chapter

    omit an exception check.) The topics covered include the ollowing:

    Messaging Domains on page 33 Working With Connections on page 34 Working With Destinations on page 43 Working With Sessions on page 47 Working With Messages on page 51

    This chapter does not provide exhaustive inormation about each class and method. For

    detailed reerence inormation, see the JavaDoc documentation or each individual class. For

    inormation on the practical design o Message Queue Java programs, see Chapter 3, MessageQueue Clients: Design and Features

    Messaging Domains

    The Java Message Service (JMS) specication, which Message Queue implements, supports two

    commonly used models o interaction between message clients and message brokers,sometimes known as messaging domains:

    In thepoint-to-point(or PTP) messaging model, each message is delivered rom a message

    producer to a single message consumer. The producer delivers the message to a queue, rom

    which it is later delivered to one o the consumers registered or the queue. Any number o

    producers and consumers can interact with the same queue, but each message is guaranteed

    to be delivered to (and be successully consumed by) exactly one consumer and no more. I

    no consumers are registered or a queue, it holds the messages it receives and eventuallydelivers them when a consumer registers.

    2C H A P T E R 2

    33

    WorkingWith Connections

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    34/230

    In thepublish/subscribe (orpub/sub) model, a single message can be delivered rom a

    producer to any number o consumers. The producerpublishes the message to a topic, rom

    which it is then delivered to all active consumers that have subscribedto the topic. Any

    number o producers can publish messages to a given topic, and each message can bedelivered to any number o subscribed consumers. The model also supports the notion o

    durable subscriptions, in which a consumer registered with a topic need not be active at the

    time a message is published; when the consumer subsequently becomes active, it will receive

    the message. I no active consumers are registered or a topic, the topic does not hold the

    messages it receives unless it has inactive consumers with durable subscriptions.

    JMS applications are ree to use either o these messaging models, or even to mix them both

    within the same application. Historically, the JMS API provided a separate set odomain-specic object classes or each model. While these domain-specic interaces continue

    to be supported or legacy purposes, client programmers are now encouraged to use the newer

    unifed domain interace, which supports both models indiscriminately. For this reason, the

    discussions and code examples in this manual ocus exclusively on the unied interaces

    wherever possible. Table 21 shows the API classes or all three domains.

    TABLE 21 Interace Classes or MessagingDomains

    Unifed Domain Point-to-Point Domain Publish/Subscribe Domain

    Destination Queue Topic

    C onnecti onFact ory Qu eueCon nection Factor y Topi cConne ctionFa ctory

    Connection QueueConnection TopicConnection

    Session QueueSession TopicSession

    MessageProducer QueueSender TopicPublisher

    MessageConsumer QueueReceiver TopicSubscriber

    Working With Connections

    All messaging occurs within the context o a connection. Connections are created using aconnection actory encapsulating all o the needed conguration properties or connecting to a

    particular JMS provider. A connections conguration properties are completely determined by

    the connection actory, and cannot be changed once the connection has been created. Thus the

    only way to control the properties o a connection is by setting those o the connection actory

    you use to create it.

    Sun JavaSystemMessage Queue4.2 Developer's Guide or JavaClients September200834

    WorkingWith Connections

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    35/230

    Obtaining a Connection Factory

    Typically, a connection actory is created or you by a Message Queue administrator and

    precongured, using the administration tools described in the Chapter 1, AdministrativeTasks and Tools, in Sun Java System Message Queue 4.2 Administration Guidewith whateverproperty settings are appropriate or connecting to particular JMS provider. The actory is thenplaced in a publicly available administered object store, where you can access it by name usingthe Java Naming and Directory Interace (JNDI) API. This arrangement has several benets:

    It allows the administrator to control the properties o client connections to the provider,ensuring that they are properly congured.

    It enables the administrator to tune perormance and improve throughput by adjustingconguration settings even ater an application has been deployed.

    By relying on the predened connection actory to handle the conguration details, it helpskeep client code provider-independent and thus more easily portable rom one JMSprovider to another.

    Sometimes, however, it may be more convenient to dispense with JNDI lookup and simplycreate your own connection actory by direct instantiation. Although hard-coding

    conguration values or a particular JMS provider directly into your application code sacricesexibility and provider-independence, this approach might make sense in some circumstances:or example, in the early stages o application development and debugging, or in applicationswhere recongurability and portability to other providers are not important concerns.

    The ollowing sections describe these two approaches to obtaining a connection actory: byJNDI lookup or direct instantiation.

    Looking Up a Connection FactoryWith JNDIExample 21 shows how to look up a connection actory object in the JNDI object store. Thecode example is explained in the procedure that ollows.

    Note I a Message Queue client is a J2EE component, JNDI resources are provided by the J2EEcontainer. In such cases, JNDI lookup code may difer rom that shown here; see your J2EEprovider documentation or details.

    EXAMPLE 21 Looking Up a Connection Factory

    // Create the environment for constructing the initial JNDI

    // naming context.

    Hashtable env = new Hashtable();

    Chapter 2 Using the Java API 35

    WorkingWith Connections

    http://docs.sun.com/doc/820-4916/aeoap?a=viewhttp://docs.sun.com/doc/820-4916/aeoap?a=viewhttp://docs.sun.com/doc/820-4916/aeoap?a=viewhttp://docs.sun.com/doc/820-4916/aeoap?a=viewhttp://docs.sun.com/doc/820-4916/aeoap?a=view
  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    36/230

    EXAMPLE 21 Looking Up a Connection Factory (Continued)

    // Store the environment attributes that tell JNDI which initial context

    // factory to use and where to find the provider.//

    env.put(Context.INITIAL_CONTEXT_FACTORY,

    "com.sun.jndi.fscontext.RefFSContextFactory");

    env.put(Context.PROVIDER_URL, "file:///C:/imq_admin_objects");

    // Create the initial context.

    Context ctx = new InitialContext(env);

    // Look up the connection factory object in the JNDI object store.

    String CF_LOOKUP_NAME = "MyConnectionFactory";

    ConnectionFactory myFactory = (ConnectionFactory) ctx.lookup

    (CF_LOOKUP_NAME);

    To Look Up a Connection FactoryWith JNDI

    Create the environment or constructing the initial JNDI naming context.

    How you create the initial context depends on whether you are using a le-system object storeor a Lightweight Directory Access Protocol (LDAP) server or your Message Queue

    administered objects. The code shown here assumes a le-system store; or inormation aboutthe corresponding LDAP object store attributes, see Using an LDAP User Repository in SunJava System Message Queue 4.2 Administration Guide

    The constructor or the initial context accepts an environment parameter, a hash table whoseentries speciy the attributes or creating the context:

    Hashtable env = new Hashtable();

    You can also set an environment by speciying system properties on the command line, rather

    than programmatically. For instructions, see the README le in the JMS example applicationsdirectory.

    Store theenvironment attributes that tell JNDI which initial contextactory to useand where to

    fnd the JMS provider.

    The names o these attributes are dened as static constants in class Context:

    env.put(Context.INITIAL_CONTEXT_FACTORY,

    "com.sun.jndi.fscontext.RefFSContextFactory");

    env.put(Context.PROVIDER_URL, "file:///C:/imq_admin_objects");

    1

    2

    Sun JavaSystemMessage Queue4.2 Developer's Guide or JavaClients September200836

    WorkingWith Connections

    http://docs.sun.com/doc/820-4916/aeofr?a=viewhttp://docs.sun.com/doc/820-4916/aeofr?a=viewhttp://docs.sun.com/doc/820-4916/aeofr?a=viewhttp://docs.sun.com/doc/820-4916/aeofr?a=viewhttp://docs.sun.com/doc/820-4916/aeofr?a=view
  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    37/230

    Note The directory represented byC:/imq_admin_objects must already exist; i necessary, youmust create the directory beore reerencing it in your code.

    Create the initial context.

    Context ctx = new InitialContext(env);

    I you use system properties to set the environment, omit the environment parameter whencreating the context:

    Context ctx = new InitialContext();

    Look up theconnection actory object in theadministered object store andtypecast it to the

    appropriateclass:

    String CF_LOOKUP_NAME = "MyConnectionFactory";

    ConnectionFactory

    myFactory = (ConnectionFactory) ctx.lookup(CF_LOOKUP_NAME);

    The lookup name you use, CF_LOOKUP_NAME, must match the name used when the object wasstored.

    You can now proceed to use the connection actory to create connections to the messagebroker, as described under Using Connections on page 39.

    Overriding Confguration Settings

    It is recommended that you use a connection actory just as you receive it rom a JNDI lookup,with the property settings originally congured by your Message Queue administrator.However, there may be times when you need to override the precongured properties with

    diferent values o your own. You can do this rom within your application code by calling theconnection actorys setProperty method. This method (inherited rom the superclassAdministeredObject) takes two string arguments giving the name and value o the property tobe set. The property names or the rst argument are dened as static constants in the MessageQueue class ConnectionConfiguration: or instance, the statement

    myFactory.setProperty(ConnectionConfiguration.imqDefaultPassword,

    "mellon");

    sets the deault password or establishing broker connections. See Connection FactoryAttributes in Sun Java System Message Queue 4.2 Administration Guideor completeinormation on the available connection actory conguration attributes.

    It is also possible to override connection actory properties rom the command line, by using the-D option to set their values when starting your client application. For example, the commandline

    java -DimqDefaultPassword=mellon MyMQClient

    3

    4

    Chapter 2 Using the Java API 37

    WorkingWith Connections

    http://docs.sun.com/doc/820-4916/aeogz?a=viewhttp://docs.sun.com/doc/820-4916/aeogz?a=viewhttp://docs.sun.com/doc/820-4916/aeogz?a=viewhttp://docs.sun.com/doc/820-4916/aeogz?a=viewhttp://docs.sun.com/doc/820-4916/aeogz?a=viewhttp://docs.sun.com/doc/820-4916/aeogz?a=view
  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    38/230

    starts an application named MyMQClient with the same deault password as in the preceding

    example. Setting a property value this way overrides any other value specied or it, whether

    precongured in the JNDI object store or set programmatically with the setProperty method.

    Note A Message Queue administrator can prevent a connection actorys properties rom being

    overridden by speciying that the object be read-only when placing it in the object store. The

    properties o such a actory cannot be changed in any way, whether with the -D option rom the

    command line or using the setProperty method rom within your client applications code.

    Any attempt to override the actorys property values will simply be ignored.

    Instantiating a Connection Factory

    Example 22 shows how to create a connection actory object by direct instantiation and

    congure its properties.

    EXAMPLE 22 Instantiating a Connection Factory

    // Instantiate the connection factory object.

    com.sun.messaging.ConnectionFactory

    myFactory = new com.sun.messaging.ConnectionFactory();

    // Set the connection factorys configuration properties.

    myFactory.setProperty(ConnectionConfiguration.imqAddressList,

    "localhost:7676,broker2:5000,broker3:9999");

    The ollowing procedure explains each program satement in the previous code sample.

    To Instantiate and Confgure a Connection Factory

    Instantiate the connection actory object.

    The name ConnectionFactory is dened both as a JMS interace (in package javax.jms)andas

    a Message Queue class (in com.sun.messaging) that implements that interace. Since only a

    class can be instantiated, you must use the constructor dened in com.sun.messaging to create

    your connection actory object. Note, however, that you cannot import the name rom both

    1

    Sun JavaSystemMessage Queue4.2 Developer's Guide or JavaClients September200838

    k i h i il i H i h i d h i k

    WorkingWith Connections

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    39/230

    packages without causing a compilation error. Hence, i you have imported the entire packagejavax.jms.*, you must qualiy the constructor with the ull package name when instantiatingthe object:

    com.sun.messaging.ConnectionFactorymyFactory = new com.sun.messaging.ConnectionFactory();

    Notice that the type declaration or the variable myFactory, to which the instantiatedconnection actory is assigned, is also qualied with the ull package name. This is because thesetProperty method, used in Instantiating a Connection Factory on page 38, belongs to theConnectionFactory class dened in the package com.sun.messaging, rather than to theConnectionFactory interace dened in javax.jms . Thus in order or the compiler torecognize this method, myFactory must be typed explicitly as

    com.sun.messaging.ConnectionFactory rather than simplyConnectionFactory (whichwould resolve to javax.jms.ConnectionFactory ater importing javax.jms.* ).

    Set the connection actorys confguration properties.

    The most important conguration property is imqAddressList, which species the host namesand port numbers o the message brokers to which the actory creates connections. By deault,the actory returned by the ConnectionFactory constructor in Instantiating a ConnectionFactory on page 38 is congured to create connections to a broker on host localhost at portnumber 7676. I necessary, you can use the setProperty method, described in the precedingsection, to change that setting:

    myFactory.setProperty(ConnectionConfiguration.imqAddressList,

    "localhost:7676,broker2:5000,broker3:9999");

    O course, you can also set any other conguration properties your application may require. SeeConnection Factory Attributes in Sun Java System Message Queue 4.2 Administration Guideor a list o the available connection actory attributes.

    You can now proceed to use the connection actory to create connections to the messageservice, as described in the next section.

    Using Connections

    Once you have obtained a connection actory, you can use it to create a connection to the

    message service. The actoryscreateConnection

    method takes a user name and password asarguments:

    Connection

    myConnection = myFactory.createConnection("mithrandir", "mellon");

    Beore granting the connection, Message Queue authenticates the user name and password bylooking them up in its user repository. As a convenience or developers who do not wish to go tothe trouble o populating a user repository during application development and testing, there is

    also a parameterless orm o the createConnection method:

    2

    Chapter 2 Using the Java API 39

    Connection myConnection myFactory createConnection()

    WorkingWith Connections

    http://docs.sun.com/doc/820-4916/aeogz?a=viewhttp://docs.sun.com/doc/820-4916/aeogz?a=viewhttp://docs.sun.com/doc/820-4916/aeogz?a=view
  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    40/230

    Connection myConnection = myFactory.createConnection();

    This creates a connection congured or the deault user identity, with both user name and

    password set to guest.

    This unied-domain createConnection method is part o the generic JMS

    ConnectionFactory interace, dened in package javax.jms; the Message Queue version in

    com.sun.messaging adds corresponding methods createQueueConnection and

    createTopicConnection or use specically with the point-to-point and publish/subscribe

    domains.

    The ollowing table shows the methods dened in the Connection interace.

    TABLE 22 Connection Methods

    Name Description

    createSession Create session

    setClientID Set client identier

    getClientID Get client identier

    setEeventListener Set event listener orconnection events

    setExceptionListener Set exception listener

    getExceptionListener Get exception listener

    getMetaData Get metadata or connection

    createConnectionConsumer Create connectionconsumer

    createDurableConnectionConsumer Create durable connection consumer

    start Start incoming message delivery

    stop Stop incoming message delivery

    close Close connection

    The main purpose o a connection is to create sessions or exchanging messages with themessage service:

    myConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    The rst argument to createSession is a boolean indicating whether the session is transacted;

    the second species its acknowledgment mode. Possible values or this second argument are

    AUTO_ACKNOWLEDGE, CLIENT_ACKNOWLEDGE,and DUPS_OK_ACKNOWLEDGE, all dened as static

    constants in the standard JMS Session interace, javax.jms.Session ; the extended Message

    Sun JavaSystemMessage Queue4.2 Developer's Guide or JavaClients September200840

    Queue version o the interace com sun messaging jms Session adds another such

    WorkingWith Connections

  • 8/8/2019 Sun Java SystemMessageQueue820-5205

    41/230

    Queue version o the interace, com.sun.messaging.jms.Session , adds another suchconstant, NO_ACKNOWLEDGE.See Acknowledgment Modes on page 48 and TransactedSessions on page 50 or urther discussion.

    I your client application will be using the publish/subscribe domain to create durable topicsubscriptions, it must have a client identiferto identiy itsel to the message service. In general,the most convenient arrangement is to congure the client runtime to provide a unique clientidentier automatically or each client. However, the Connection interace also provides amethod, setClientID, or setting a client identier explicitly, and a correspondinggetClientID method or retrieving its value. See Assigning Client Identiers on page 82 andClient Identier in Sun Java System Message Queue 4.2 Administration Guide or moreinormation.

    You should also use the setExceptionListener method to register an exception listeneror theconnection. This is an object implementing the JMS ExceptionListener interace, whichconsists o the single method onException:

    void onException (JMSException exception)

    In the event o a problem with the connection, the message broker will call this method, passing

    an exception object identiying the nature o the problem.

    A connections getMetaData method returns a ConnectionMetaData object, which in turnprovides methods or obtaining various items o inormation about the connection, such as itsJMS version and the name and version o the JMS provider.

    The createConnectionConsumer and createDurableConnectionConsumer methods (as wellas the session methods setMessageListener and getMessageListener, listed in Table 23)areused or concurrent message consumption; see theJava Message Service Specifcation or more