home / infca / mq / mq_java (navigation links) That Christmas spirit is not what you drink

Java code samples | jmsAdmin | jBoss Pend | Links | End

Accés a MQ des Java


MQ tmt MQ rcv MQ both JMS tmt JMS rcv JMS both JMS UserID JMS Test

Concept

JMS is an API for asynchronous, transacted message production, distribution, and delivery.

The Java Message Service (JMS) API is a Java Message Oriented Middleware (MOM) API for sending messages between two or more clients.

The JMS API is an API for accessing enterprise messaging systems from Java programs.

URL, wiki, "JMS 1.1 FR spec.pdf"

The Java EE programming environment provides a standard API called JMS (Java Message Service), which is implemented by most MOM vendors and aims to hide the particular MOM API implementations; however, JMS does not define the format of the messages that are exchanged, so JMS systems are not interoperable.

MOM wiki

Unlike JMS, which merely defines an API, AMQP is a wire-level protocol. A wire-level protocol is a description of the format of the data that is sent across the network as a stream of octets. Consequently any tool that can create and interpret messages that conform to this data format can interoperate with any other compliant tool irrespective of implementation language. Note that, like HTTP and XMPP, AMQP does not have a standard API.

AMQP

Q & A

Q: What is the Java Message Service?
A: The Java Message Service (JMS) API is an API for accessing enterprise messaging systems. It is part of the Java 2 Platform, Enterprise Edition (J2EE).

Q: Where can I find the Java Message Service specification?
A: The Java Message Service specification is available at http://java.sun.com/products/jms/docs.html. A link to the online JMS API documentation is at the same location.

JMS FAQ, EE 1.3.1 Overview.

Messaging Systems and the Java Message Service (JMS), by Sun


Modes d'accés a MQ des Java

Les classes de IBM son directes i senzilles.

Les classes de JMS (complicades i enfarragoses de manegar) se suposa que son transportables i interoperables, però en realitat no ho son pas.

WebSphere MQ classes for Java ('Base Java' - package com.ibm.mq) or WebSphere MQ classes for JMS (package com.ibm.mq.jms)

Definició classes MQ : import com.ibm.mq.* ;
Conexió al gestor : objetoMQ = new MQQueueManager( "Nombre_Qmgr" ) ;
Obrir una cua : MQQueue Cola_MQ = qMgr.accessQueue ( "Nombre_cola_MQ", openOptions ) ;

Definició classes JMS : import javax.jms.* ;

Operació Java JMS
Declaració import com.ibm.mq.* ; import javax.jms.* ;
MQCONN(qmgr) qMgr = new MQQueueManager ( qManagerName ) ; qcf = (QueueConnectionFactory) ctx.lookup ( "jndiQCF" ) ;
MQOPEN(queue) MQQueue Cola_MQ = qMgr.accessQueue ( "Nom_cua_MQ", openOptions ) ;

El JMS és una especificació de l'interface i sempre necessita un "provider" de l'implementació (en aquest cas el MQ). Els programes java inclouen crides a funcions JMS i el provider les tradueix al MOM. Cada "provider" proporciona les seves "llibreries" de JMS. Sun proporciona la especificació que és un estàndar (en java es diu el "interface", en aquest cas javax.jms). Per proporcionar un JMS Provider has de tenir un producte capaç d'enviar missatges asíncronament. Si no el tens, no pots implementar l'interface. WebSphere MQ Classes for Java™ Message Service (WebSphere MQ Classes for JMS) es el proveedor JMS que se suministra con WebSphere MQ. Además de implementar las interfaces que están definidas en el paquete javax.jms,...
Per altre banda, el que tu dius : pots cridar directament al MQ des de java amb una API que no deixa de ser la versió Java del MQI. Aquesta és a la que es refereixen com "MQ Classes for Java". WebSphere MQ classes for Java encapsulate the Message Queue Interface (MQI), the native WebSphere MQ API.

JMS

El JNDI es el contenedor de objetos abstractos. Es el interface para acceder al servicio de nombres, que proporciona

  1. almacena nombre y propiedades
  2. busqueda de nombre y devuelve sus propiedades

El JNDI almacena

El destino de un mensaje puede ser una cola o un tópico (publicación).

Defining which connection to use : Bindings/Client

The type of connection to use is determined by the setting of variables in the MQEnvironment class. Two variables are used:

url, v7

Client connections

When WebSphere® MQ classes for Java™ is used as a client, it is similar to the WebSphere MQ C client, but has a number of differences. If you are programming for WebSphere MQ classes for Java for use as a client, be aware of the following differences:

When used in client mode, WebSphere MQ classes for Java does not support the MQBEGIN call.

url

Using a client channel definition table (MQ v7)

As an alternative to creating a client connection channel definition by setting certain properties of a ConnectionFactory object, a WebSphere® MQ classes for JMS application can use client connection channel definitions that are stored in a client channel definition table. These definitions are created by WebSphere MQ Script (MQSC) commands or WebSphere MQ Programmable Command Format (PCF) commands.

When the application creates a Connection object, WebSphere MQ classes for JMS searches the client channel definition table for a suitable client connection channel definition, and uses the channel definition to start an MQI channel.

To use a client channel definition table, the CCDTURL property of a ConnectionFactory object must be set to a URL object. The URL object encapsulates a uniform resource locator (URL) that identifies the name and location of the file containing the client channel definition table and specifies how the file can be accessed. You can set the CCDTURL property by using the WebSphere MQ JMS administration tool, or an application can set the property by creating a URL object and calling the setCCDTURL() method of the ConnectionFactory object.

url


Amunt! Top Amunt!
JMS code samples
Objectiu

Fer un Java MQCONNX amb

or JMS code with

code sample {improve it with 2 more lines @ T42:\\Java\MQ\JMSDEMO.zip }

Connection factories are objects that enable JMS clients to create JMS connections. A connection factory supports concurrent use, enabling multiple threads to access the object simultaneously. After defining a JMS server, you can configure one or more connection factories to create connections with predefined attributes.


// // =========================================================================== // sample application // WebSphere MQ classes for Java // // To compile this sample : javac MQSample.java // // To run this sample : java MQSample // import com.ibm.mq.* ; // Include the WebSphere MQ classes for Java package public class MQSample { private String qManager = "INDI" ; // define name of queue manager to connect to. private String szQueueName = "QD1" ; // "SYSTEM.DEFAULT.LOCAL.QUEUE" private MQQueueManager qMgr ; // define a queue manager object public static void main ( String args[] ) { new MQSample(); } public MQSample() { try { MQEnvironment.hostname = "192.168.187.136" ; // host MQEnvironment.port = 1466 ; // port MQEnvironment.channel = "CON.NET" ; // SVRCONN channel name MQEnvironment.userID = "sebastia" ; MQEnvironment.password = "any" ; // Create a connection to the queue manager System.out.println ( "The Qmgr Name is : " + qManager ) ; qMgr = new MQQueueManager ( qManager ) ; // MQCONN() // Set up the options on the queue we wish to open... // Note. All WebSphere MQ Options are prefixed with MQC in Java. int openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT ; // Now specify the queue that we wish to open, and the open options... System.out.println ( "The Queue Name is: " + szQueueName ) ; MQQueue system_default_local_queue = qMgr.accessQueue ( szQueueName, openOptions ) ; // MQOPEN() // Define a simple WebSphere MQ message, and write some text in UTF format.. MQMessage hello_world = new MQMessage(); hello_world.writeUTF ( "Hello World !" ) ; // specify the message options... MQPutMessageOptions pmo = new MQPutMessageOptions() ; // accept the defaults, same as MQPMO_DEFAULT // put the message(s) on the queue int iCnt = 0 ; while ( iCnt < 1000 ) { System.out.println ( iCnt + " - put() message." ) ; system_default_local_queue.put ( hello_world, pmo ) ; iCnt ++ ; int j = 0 ; while ( j < 10000000 ) { j ++ ; } ; } ; // get the message back again... // First define a WebSphere MQ message buffer to receive the message into.. MQMessage retrievedMessage = new MQMessage() ; retrievedMessage.messageId = hello_world.messageId ; // Set the get message options... MQGetMessageOptions gmo = new MQGetMessageOptions() ; // accept the defaults same as MQGMO_DEFAULT // get the message off the queue... System.out.println ( "Get() message." ) ; system_default_local_queue.get ( retrievedMessage, gmo ) ; // And prove we have the message by displaying the UTF message text String msgText = retrievedMessage.readUTF() ; System.out.println ( "The message I have just got is : " + msgText ) ; // Close the queue... System.out.println ( "Close() queue." ) ; system_default_local_queue.close() ; // Disconnect from the queue manager System.out.println ( "Disconnect() queue manager." ) ; qMgr.disconnect() ; } // If an error has occurred in the above, try to identify what went wrong // Was it a WebSphere MQ error? catch (MQException ex) { System.out.println ( "--- A MQ 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

This code runs ok @ VM !


MQ base Java versus MQ JMS

 import com.ibm.mq.* ;     ===>>> IMB MQ classes for Java
 import com.ibm.mq.jms.* ; ===>>> IBM clases for JMS
 import javax.jms.* ;      ===>>> Sun clases para JMS

 Stuff in the com.ibm.mq.jms packages are the IBM supplied implementation of the JMS Provider.
 Stuff in javax.jms are the Sun supplied implementation of the "client" side of the JMS API.
 Stuff in the com.ibm.mq package are the IBM supplied WebSphere MQ API for Java - which is not JMS at all.

Parts

  1. llegir dades de entrada des HTML
  2. cridar a la API de MQ
  3. escriure dades de sortida a HTML

Estructura

El codi java inclou un import com.ibm.mq.* ;

Ha de existir un com.ibm.mq.jar

De on es demana el jms.jar ? javax.jms.* ??


Lectura de les dades des HTML


Crida a la API de MQ des Java


Escriptura de les dades a HTML


Codi (MQCONNX ?)

import com.ibm.mq.*; // Include the WebSphere MQ classes for Java package import java.io.*; public class MQPruebaConexion { private String nombreMQ = "QMNAME" ; // Define e inicializa variable nombre MQ private MQQueueManager objetoMQ ; // Define un objeto MQ public static void main(String args[]) { new MQPruebaConexion() ; } public MQPruebaConexion() { try { // Crea una conexión con el gestor de colas estableciendo antes // la direccion IP, el puerto y el canal tipo servidor MQEnvironment.hostname = "10.11.12.13" ; MQEnvironment.port = 1420 ; MQEnvironment.channel = "CH_2_HOST.M42F" ; MQEnvironment.userID = "@USER1"; // pongo trace en mi fichero FileOutputStream trace = new FileOutputStream("MyTrace.txt") ; MQEnvironment.enableTracing(2,trace) ; objetoMQ = new MQQueueManager(nombreMQ) ; // MQCONN() // Configurar las opciones en la cola que se va a abrir... // Todas las opciones de WebSphere MQ tienen el prefijo MQC en Java int openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT ; // Especificar la cola que se va a abrir MQQueue system_default_local_queue = objetoMQ.accessQueue ( "QTP.PRUEBAS", openOptions ) ; // MQOPEN() // Definir un mensaje WebSphere MQ simple y escribir texto en formato UTF... MQMessage mensaje = new MQMessage() ; mensaje.writeUTF ( "Mensaje grabado desde Java en mi PC al MQ en zOS - M42F - " ) ; // especificar las opciones de mensaje para escribir... MQPutMessageOptions opcionesPut = new MQPutMessageOptions() ; // aceptar los valores por omisión iguales que MQPMO_DEFAULT // escribir el mensaje a la cola system_default_local_queue.put ( mensaje, opcionesPut ) ; // obtener de nuevo el mensaje... MQMessage retrievedMessage = new MQMessage() ; retrievedMessage.messageId = mensaje.messageId ; // Establecer las opciones de obtención de mensajes... MQGetMessageOptions opcionesGet = new MQGetMessageOptions() ; // aceptar los valores por omisión iguales que MQGMO_DEFAULT // extraer el mensaje de la cola... system_default_local_queue.get(retrievedMessage, opcionesGet) ; // Y probar que tenemos el mensaje visualizando el texto de mensaje UTF String msgText = retrievedMessage.readUTF() ; System.out.println("El mensaje es: " + msgText) ; // Cerrar la cola... system_default_local_queue.close() ; // Desconectar del gestor de colas objetoMQ.disconnect() ; } // Control de errores // ¿ Era un error de WebSphere MQ ? catch (MQException ex) { System.out.println ( "Se ha producido un error de WebSphere MQ : "+ "Código de terminación " +ex.completionCode + " Código de razón " + ex.reasonCode ) ; } // ¿ Era un error de espacio de almacenamiento intermedio de Java ? catch (java.io.IOException ex) { System.out.println ( "Se ha producido un error al grabar mensaje en "+ "almacenamiento intermedio de mensajes: " + ex ) ; } } // conexion } // class

Object Model - MQclases para Java

Send Amunt! Top Amunt!
import com.ibm.mq.* ; // Include the WebSphere MQ classes for Java package public class MQSample extends java.applet.Applet { private String hostname = Direccion IP o nombre host gestor MQ ; private String channel = Puerto TCP/IP listener gestor MQ ; private String qManager = Nombre gestor MQ ; private MQQueueManager qMgr ; public void init() { MQEnvironment.hostname = hostname ; MQEnvironment.channel = channel ; MQEnvironment.properties.put ( MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES ) ; // MQEnvironment.properties.put ( MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT ) ; } public void start() { try { qMgr = new MQQueueManager ( qManager ) ; // MQCONN() int openOptions = MQC.MQOO_OUTPUT ; MQQueue Cola_MQ = qMgr.accessQueue ( "Nom_cua_MQ", openOptions ) ; // MQOPEN() MQMessage MsgMQ = new MQMessage() ; MsgMQ.writeByte ( "Datos_mensaje_MQ" ) ; MQPutMessageOptions pmo = new MQPutMessageOptions() ; Cola_MQ.put(MsgMQ,pmo) ; MsgMQ.close() ; Cola_MQ.close() ; qMgr.disconnect() ; } catch (MQException ex) { System.out.println ( "Error MQ : CompCode " + ex.completionCode + " ReasonCode " + ex.reasonCode ) ; } catch (java.io.IOException ex) { System.out.println ( "Error en escritura buffer: " + ex ) ; } } }
Receive Amunt! Top Amunt!
import com.ibm.mq.* ; // Include the WebSphere MQ classes for Java package public class MQSample extends java.applet.Applet { private String hostname = Direccion IP o nombre host gestor MQ ; private String channel = Puerto TCP/IP listener gestor MQ ; private String qManager = Nombre gestor MQ ; private MQQueueManager qMgr ; public void init() { MQEnvironment.hostname = hostname ; MQEnvironment.channel = channel ; MQEnvironment.properties.put ( MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES ) ; } public void start() { try { qMgr = new MQQueueManager(qManager) ; int openOptions = MQC.MQOO_INPUT_SHARED ; MQQueue Cola_MQ = qMgr.accessQueue("Nombre_cola_MQ", openOptions) ; MQMessage MsgMQ = new MQMessage() ; MQGetMessageOptions gmo = new MQGetMessageOptions() ; Cola_MQ.get(MsgMQ, gmo) ; String msgText = MsgMQ.readUTF() ; MsgMQ.close() ; Cola_MQ.close() ; qMgr.disconnect() ; } catch (MQException ex) { System.out.println("Error MQ : CompCode " + ex.completionCode + " ReasonCode " + ex.reasonCode) ; } catch (java.io.IOException ex) { System.out.println("Error en lectura buffer: " + ex) ; } } }
Send + Receive Amunt! Top Amunt!
import com.ibm.mq.* ; // Include the WebSphere MQ classes for Java package public class MQSample extends java.applet.Applet { private String hostname = Direccion IP o nombre host gestor MQ ; private String channel = Puerto TCP/IP listener gestor MQ ; private String qManager = Nombre gestor MQ ; private MQQueueManager qMgr ; public void init() { MQEnvironment.hostname = hostname ; MQEnvironment.channel = channel ; MQEnvironment.properties.put ( MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES ) ; } public void start() { try { qMgr = new MQQueueManager(qManager) ; int openOptions = MQC.MQOO_OUTPUT ; MQQueue Cola_MQ_Req = qMgr.accessQueue ( "Nombre_cola_MQ_Request", openOptions ) ; MQMessage MsgMQ_Req = new MQMessage() ; MQMessage MsgMQ_Rep = new MQMessage() ; MsgMQ_Req.writeUTF("Datos_mensaje_MQ") ; MQPutMessageOptions pmo = new MQPutMessageOptions() ; Cola_MQ_Req.put(MsgMQ_Req,pmo) ; MsgMQ_Rep.correlationId = MsgMQ_Req.messageId ; MsgMQ_Req.close() ; Cola_MQ_Req.close() ; openOptions = MQC.MQOO_INPUT_SHARED ; MQQueue Cola_MQ_Rep = qMgr.accessQueue("Nombre_cola_MQ_Reply", openOptions) ; MQGetMessageOptions gmo = new MQGetMessageOptions() ; Cola_MQ_Rep.get ( MsgMQ_Rep, gmo ) ; String msgText = MsgMQ_Rep.readUTF() ; MsgMQ_Rep.close() ; Cola_MQ_Rep.close() ; qMgr.disconnect() ; } catch (MQException ex) { System.out.println("Error MQ : CompCode " + ex.completionCode + " ReasonCode " + ex.reasonCode) ; } catch (java.io.IOException ex) { System.out.println("Error de escritura buffer: " + ex) ; } } }

Object Model - JMS

Send Amunt! Top Amunt!
import javax.jms.* ; import javax.naming.Context ; import javax.naming.InitialContext ; import javax.naming.NamingException ; import com.ibm.mq.jms.* ; import com.ibm.mq.MQC.* ; public class PutMsg { static public void main(String[] args) { Context ctx ; QueueConnectionFactory qcf ; QueueConnection con = null ; Queue sendqueue ; QueueSession session ; QueueSender sender ; TextMessage messagemq ; try { ctx = new InitialContext() ; qcf = (QueueConnectionFactory) ctx.lookup ( "jndiQCF" ) ; con = qcf.createQueueConnection() ; session = con.createQueueSession ( false, Session.AUTO_ACKNOWLEDGE ) ; sendqueue = (Queue) ctx.lookup ( "jndiQSend" ) ; sender = session.createSender ( sendqueue ) ; messagemq = session.createTextMessage ( "Datos mensaje" ) ; sender.send ( sendqueue, messagemq ) ; sender.close() ; } catch (JMSException je) { System.out.println ( "error " + je ) ; Exception le = je.getLinkedException() ; if (le != null) System.out.println ( "linked exception " + le ) ; } catch (NamingException ne) { System.out.println ( "error " + ne ) ; } finally { if (con != null) { try { con.close() ; } catch (JMSException je) { System.out.println ( "error " + je ) ; Exception le = je.getLinkedException() ; if (le != null) System.out.println ( "linked exception " + le ) ; } } } } }
Receive Amunt! Top Amunt!
import javax.jms.* ; import javax.naming.Context ; import javax.naming.InitialContext ; import javax.naming.NamingException ; import com.ibm.mq.jms.* ; import com.ibm.mq.MQC.* ; public class ReceiverMsg { static public void main(String[] args) { Context ctx ; QueueConnectionFactory qcf ; QueueConnection con = null ; Queue receiverqueue ; QueueSession session ; QueueReceiver receiver ; Message messagemq ; try { ctx = new InitialContext() ; qcf = (QueueConnectionFactory) ctx.lookup ( "jndiQCF" ) ; con = qcf.createQueueConnection() ; con.start() ; session = con.createQueueSession ( false, Session.AUTO_ACKNOWLEDGE ) ; receiverqueue = (Queue) ctx.lookup ( "jndiQReceiver" ) ; receiver = session.createReceiver ( receiverqueue ) ; messagemq = receiver.receive() ; if (messagemq == null) { System.out.println ( "ERROR: mensaje invalido" ) ; } receiver.close() ; } catch (JMSException je) { System.out.println ( "error " + je ) ; Exception le = je.getLinkedException() ; if (le != null) System.out.println ( "linked exception " + le ) ; } catch (NamingException ne) { System.out.println ( "error " + ne ) ; } finally { if (con != null) { try { con.close() ; } catch (JMSException je) { } } } } }
Send + Receive Amunt! Top Amunt!
import javax.jms.* ; import javax.naming.Context ; import javax.naming.InitialContext ; import javax.naming.NamingException ; import com.ibm.mq.jms.* ; import com.ibm.mq.MQC.* ; public class PetResp { static public void main() { Context ctx ; QueueConnectionFactory qcf ; QueueConnection con = null ; Queue sendqueue ; Queue receivequeue ; QueueSession session ; QueueSender sender ; QueueReceiver receiver ; TextMessage messagemq ; String messageID ; Message messagercv ; String filter ; try { ctx = new InitialContext() ; qcf = (QueueConnectionFactory) ctx.lookup ( "jndiQCF" ) ; con = qcf.createQueueConnection() ; con.start() ; session = con.createQueueSession ( false, Session.AUTO_ACKNOWLEDGE ) ; sendqueue = (Queue) ctx.lookup ( "jndiQSend" ) ; sender = session.createSender ( sendqueue ) ; messagemq = session.createTextMessage ( "Datos mensaje" ) ; sender.send ( sendqueue, messagemq ) ; messageID = messagemq.getJMSMessageID() ; sender.close() ; filter = "JMSCorrelationID = '"+messageID+"'" ; receivequeue = (Queue) ctx.lookup ( "jndiQRcv" ) ; receiver = session.createReceiver ( receivequeue, filter ) ; messagercv = receiver.receive ( 1000 ) ; if (messagercv == null) { System.out.println ( "ERROR: no message received" ) ; } else { System.out.println ( "Datos mensaje respuesta: " + messagercv ) ; } receiver.close() ; } catch (JMSException je) { System.out.println ( "error " + je ) ; Exception le = je.getLinkedException() ; if (le != null) System.out.println ( "linked exception " + le ) ; } catch (NamingException ne) { System.out.println ( "error " + ne ) ; } finally { if (con != null) { try { con.close() ; } catch (JMSException je) { } } } } }

How to set UserID Amunt! Top Amunt!

One way around it was to set the user ID and password when I created the queue connection. When I subsequently created a message, the JMSXUserID property was properly set by MQ.

// Create a queue connection. QueueConnection conn = qcf.createQueueConnection ( userID, password ) ;

Pointers

Volem fer un Connect, Open, Put, Get, Close, Disconnect.

Samples

Have a look at <MQ>\tools\Java\base and <MQ>\tools\Java\jms { MQ v7 : <MQ>\Tools\jms\samples\ }


JMS

========================================================== WHY JMS ? http://archive.devx.com/java/free/articles/MasoJMS02/Maso02-1.asp ========================================================== MQ versus JMS : http://forum.java.sun.com/thread.jspa?threadID=629810&messageID=3895874 http://forums.java.sun.com/thread.jspa?threadID=664240&tstart=120 ========================================================== JMS forum http://forums.java.sun.com/forum.jspa?forumID=29&start=135 ========================================================== WAS MQ versus WS JMS versus MQ http://www.rtpwug.org/download/2003.10/RTPWUG-JMS-V2.1-10282003.ppt {gone} ========================================================== JMS performance http://www.javaperformancetuning.com/tips/j2ee_jms.shtml RMI performance http://www.javaperformancetuning.com/tips/j2ee_rmi.shtml ========================================================== JAVA programming http://www.codeguru.com/forum/archive/index.php/f-5-p-51.html ========================================================== http://www.inferdata.com/training/j2ee/jmsmqseries.html Java Message Service (JMS) is a standard Java Application Programming Interface (API) from Sun Microsystems that provides a common interface for Java programmers to invoke any messaging services such as WebLogic's JMS Service, IBM's WebSphere MQ, Progress Software's SonicMQ, etc. JMS is part of Java 2 Enterprise Edition (J2EE). ========================================================== simple JMS example http://www.onjava.com/pub/a/onjava/excerpt/jms_ch2/ same again ?!?!? http://www.oreilly.com/catalog/javmesser/chapter/ch02.html ========================================================== IBM MQ sample code & JMS also !!!! *** GET ALL *** http://www.developer.ibm.com/isv/tech/sampmq.html 2007 : ok @ "T42:\\MQ\Codi\Samples IBM" ==========================================================

Arquitectura de JMS

Una aplicación JMS consta de los siguientes elementos:

Objetos administrados

Los objetos administrados son el punto al que se comunican los clientes JMS para enviar o recibir mensajes. Se denominan objetos administrados por que los crea el administrador (en la implementación de referencia mediante j2eeadmin). Implementan las interfaces JMS y se sitúan en el espacio de nombres de JNDI (Java Naming and Directory Interface) para que los clientes puedan solicitarlos.

Hay dos tipos de objetos administrados en JMS:

Mensajes

Es el corazón del sistema de mensajes. Estan formados por tres elementos:

Clientes JMS

Son clientes de JMS tanto el que suministra mensajes como el que los recibe. Todos tienen una serie de pasos en común antes de lograr enviar o recibir un mensaje:

From here


JNDI

The Java Naming and Directory Interface (JNDI) API implementation provides directory and naming functionality to programs developed in Java. This allows Java programs to discover and retrieve objects of any type from the JNDI name space.

JMS has two types of administered objects:

An administrator can place objects of these types in the JNDI name space to be accessed by messaging applications. So, how does an administrator put these objects in the JNDI name space? This step is vendor specific. If you are using WebSphere MQ V5.3 with WebSphere Application Server V5.0 you can administer these objects right from the WebSphere Administrative Console. If you are using another application server, WebSphere MQ V5.3 provides a tool called JMSAdmin for this purpose.

http://www.redbooks.ibm.com/redpieces/pdfs/sg246875.pdf

The Java Naming and Directory Interface (JNDI) is an API for directory services. It allows clients to discover and lookup data and objects via a name and, like all Java APIs that interface with host systems, is independent of the underlying implementation. Additionally, it specifies a service provider interface (SPI) that allows directory service implementations to be plugged into the framework.

Wikipedia, wiki.


JMSAdmin

The administration tool enables administrators to define the properties of eight types of WebSphere MQ JMS object and to store them within a JNDI namespace. Then, JMS clients can use JNDI to retrieve these administered objects from the namespace and use them.

The JMS objects that you can administer by using the tool are:

URL

Remember as well if you try to run some of the JMS samples that you will need to run JMSAdmin first and create the relevant file Context before the sample will work.
Hint: create the context with type *FileContext first (its the easiest to master) and if that works well for you, you may graduate to other contexts.
Try with -nojndi option first and then start using JMSAdmin. Look at the source code for the samples on how to use -nojndi ...

Iniciando Administración del Servicio de mensajes de WebSphere MQ Classes for Java(tm) Inicializando el contexto JNDI... INITIAL_CONTEXT_FACTORY: com.sun.jndi.fscontext.RefFSContextFactory PROVIDER_URL: file:/C:/JNDI-Directory La inicialización de JNDI ha fallado; por favor compruebe los valores de JNDI y el servicio. Para obtener información adicional sobre la razón de este problema, ejecútelo con el argumento -v Error: javax.naming.NameNotFoundException; remaining name 'C:\JNDI-Directory' Error: javax.naming.NameNotFoundException; remaining name 'C:\Program Files\IBM\WebSphere MQ\Java\bin\sebasMQJNDI'

How to configure the JMSAdmin tool to work properly with the WebSphere 4.0 namespace

We run command

C:\Program Files\IBM\WebSphere MQ\Java\bin> jmsadmin < c:\sebas\MQ\JNDI\createJNDI.defs

File "C:\Program Files\IBM\WebSphere MQ\Java\bin\JMSAdmin.config" has :

INITIAL_CONTEXT_FACTORY=com.sun.jndi.fscontext.RefFSContextFactory PROVIDER_URL=file:/C:/sebas/MQ/JNDI

File c:\sebas\MQ\JNDI\createJNDI.defs has :

# Define a QueueConnectionFactory # Only parameters being overridden from their default values are specified. # This sets up a MQ client binding. DEF QCF(QCF) + TRANSPORT(CLIENT) + QMANAGER(JMSQM) + HOSTNAME(localhost) + PORT(1414) # Define a Queue Destination DEF Q(INPUTQ) + QUEUE(INPUTQ) + QMANAGER(JMSQM)+ # DEF Q(OUTPUTQ) + QUEUE(OUTPUTQ) + QMANAGER(JMSQM) # END

Ara JMSADMIN dona

Iniciando Administración del Servicio de mensajes de WebSphere MQ Classes for Java(tm) InitCtx>

MDB

JMS en EJB's: Message Driven Bean

La especificación 2.0 de EJB introdujo un nuevo tipo de Enterprise Java Bean, el Message Driven Bean. Hasta ahora, para integrar una aplicación J2EE con JMS habia que programar un consumidor de mensajes que hiciese llegar los mensajes que recibiese a un Session Bean, y que fuese este el que los tratase. Esta solución, aparte de añadir una capa mas, no era la mas correcta. Con la inclusión del nuevo tipo de EJB, se consigue que la aplicacion J2EE sea capaz de recibir mensajes JMS y de tratarlos por si misma (con los beneficios que esto conlleva: seguridad, transacciones dentro del servidor de aplicaciones, etc..). Este nuevo tipo de beans se comporta como un bean de sesión sin estado.

Los MDB's (Message Driven Beans), al contrario que los otros tipos de EJB, no tienen implementar ninguna interfaz remota, pues no van a ser utilizados desde fuera del servidor de aplicaciones, por lo que solo hace falta programar el Bean propiamente dicho. Todos los MDB's implementan dos interfaces:

El enterprise bean se comporta de la misma manera que un cliente normal que recoja mensajes en el servicio JMS. La diferencia es que no tendremos que preocuparnos de conseguir las interfaces de la JNDI, pues de eso ya se encarga el servidor de aplicaciones (nosostros le indicamos cual sera la factory y el asunto o la cola de la que debe recibir mensajes). El archivo MensajeBeanCola.java contiene un MDB que consulta la cola que hemos estado usando hasta ahora y si tiene mensajes, imprime su contenido en pantalla. Puede observar que solo se ha escrito codigo para el metodo onMessage().

From here

MDB by Sun


MQ access from Java

Point a web-browser containing a Java 1.3 runtime Plugin (as Netscape 6) to this page :

<MQ base directory>\Tools\Java\jms\applet\en_US\test.html

[T42] VM-BI:file://localhost/C:/TEMP/JavaJDK/test.html

T42:\MQ\Java\Test_Instalacio\test.html
It is an installation verification applet.
The applet connects to a given queue manager, exercises all the WebSphere MQ calls, and produces diagnostic messages if there are any failures
.

Using Java, csqzasw12.pdf, page 29 (47 of 539)

Problem [VM MB] : JMSTestApplet.class not found.
We have JMSTestApplet.java, but no javac
On another machine [P4], we do have javac but not com.ibm.mq.jar (at <mq>\Java\lib), so we install Java JDK 1.5 at VM-MB.


Puedo ejecutarlo sin browser :

javac JMSTestApplet.java
java  JMSTestApplet

Desde Opera tengo este error :
Exception in thread "AWT-EventQueue-1" java.lang.NoClassDefFoundError: javax/jms/JMSException
Solució : url : The connector cannot find jms.jar Solution: make sure that jms.jar is in the connector classpath.


How to Connect to mq using Channel tab file in java

url

See also "Using Java" PDF.


MQ, Java i Francisco
MessageApplication.java
package com.ibm.iic; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; import javax.naming.InitialContext; import javax.naming.NamingException; public class MessageApplication { public static final String CONNECTION_FACTORY_JNDI_NAME = "jms/testConnFactory"; public static final String QUEUE_DESTINATION_JNDI_NAME = "jms/testQueue"; public static final String MESSAGE_TEXT = "Hola!"; protected ConnectionFactory cFactory = null; protected Destination destination = null; protected Destination dQueue = null; public MessageApplication() { super(); } protected void findJNDIObjects ( String connectionFactory, String destination ) throws NamingException { InitialContext jndiContext = new InitialContext(); cFactory = (ConnectionFactory) jndiContext.lookup ( connectionFactory==null ? CONNECTION_FACTORY_JNDI_NAME: connectionFactory ); dQueue = (Destination) jndiContext.lookup ( destination==null ? QUEUE_DESTINATION_JNDI_NAME : destination); System.out.println(jndiContext); System.out.println(dQueue); } public String sendMessage ( String connectionFactory, String destination, String message ) throws NamingException, JMSException { findJNDIObjects(connectionFactory, destination); Connection cnn = cFactory.createConnection(); cnn.start(); Session session = cnn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(/*dTopic*/dQueue); TextMessage msg = session.createTextMessage(); msg.setText(message!=null ? message : MESSAGE_TEXT); producer.send(msg); System.out.println("Message sent: "+msg.toString()); cnn.close(); return msg.toString(); } public String receiveMessage ( String connectionFactory, String destination, long millisWaiting ) throws NamingException, JMSException { findJNDIObjects(connectionFactory, destination); String result = null; Connection cnn = cFactory.createConnection(); cnn.start(); Session session = cnn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(dQueue); TextMessage msg = (TextMessage)consumer.receive(millisWaiting); if (msg!=null) result = msg.getText(); cnn.close(); return result; } }
ConnectionFactory
Channel The name of the channel used for connection to the WebSphere MQ queue manager, for client connection only (=> SVRCONN) Transport type Specifies whether the WebSphere MQ client connection or JNDI bindings are used for connection to the WebSphere MQ queue manager. The external JMS provider controls the communication protocols between JMS clients and JMS servers. Default BINDINGS BINDINGS JNDI bindings are used to connect to the queue manager. BINDINGS is a shared memory protocol and can only be used when the queue manager is on the same node as the JMS client and poses security risks that should be addressed through the use of EJB roles. CLIENT WebSphere MQ client connection is used to connect to the queue manager (=> SVRCONN)

url


Initial values for dynamic structures

When a variable number of instances of a structure is required, the instances are usually created in main storage obtained dynamically using the calloc or malloc functions. To initialize the fields in such structures, the following technique is recommended:

  1. Declare an instance of the structure using the appropriate MQxxx_DEFAULT macro variable to initialize the structure. This instance becomes the "model" for other instances:
    MQMD Model = {MQMD_DEFAULT}; /* declare model instance */

    The static or auto keywords can be coded on the declaration in order to give the model instance static or dynamic lifetime, as required.

  2. Use the calloc or malloc functions to obtain storage for a dynamic instance of the structure:
    PMQMD Instance; Instance = malloc(sizeof(MQMD)); /* get storage for dynamic instance */
  3. Use the memcpy function to copy the model instance to the dynamic instance:
    memcpy(Instance,&Model,sizeof(MQMD)); /* initialize dynamic instance */

MQJMS1017: non-local MQ queue not valid for receiving or browsing.

There are different type of queues -- all defined locally -- on a qmgr :

  1. queue local -- this one you can browse and receive from
  2. queue remote -- used as a pointer to a queue local on a different qmgr
  3. queue alias -- used as a pointer to queue on the same qmgr
  4. queue model -- used as a template for dynamic creation of a queue
  5. queue cluster -- when defined locally it can be accessed on a remote qmgr, within the cluster, as you would access a queue remote there.
  6. queue local usage xmitq -- a local queue serving to move messages from one qmgr to the other via a channel. It should never be directly posted to by the application

url

Verify Listener is running !

Another chance :

<bean id="jmsMQConnectionFactory" class="com.ibm.mq.jms.MQQueueConnectionFactory"> <!--property name="queueManager" value="QM.CBX2GSS2"/--> <property name="hostName" value="192.168.219.80"/> <property name="port" value="1442"/> <property name="channel" value="CH.CBX2GSS.SRVC"/> <property name="transportType" value="1"/> </bean>

MQseries.net


mqjbnd05.dll

Si en ejecutar java JMS_Sender QD1 INDI rebem un error

Exception in thread "main" java.lang.UnsatisfiedLinkError: no mqjbnd05 in java.library.path

simplement vol dir que NO TENIM EL MQ INSTALAT !

FAQ for EasyJMS


JMS Test

Setting up a JMS queue in WebSphere MQ with LDAP

url.


Amunt! Top Amunt!
jBoss

jBoss homepage

JBoss Application Server documentation

MQ Resource Adapter : the J2EE Connector Architecture (JCA) provides a standard way of connecting applications running in a J2EE environment to an Enterprise Information System (EIS) as MQ or DB2.

Using JCA with JBoss

Installing and configuring WebSphere MQ resource adapter on JBoss Application Server : This article shows you how to install, configure, and troubleshoot the IBM© WebSphere© MQ resource adapter Install Verification Test (IVT) on JBoss Application Server.

MQ J2EE Connector Architecture IVT :

Using Connection Factory:java:comp/env/jms/IVTCF Using Destination:java:comp/env/jms/IVTQueue Altered JNDI name to java:java:comp/env/jms/IVTQueue

See "Using Java", SC34-6591-02, url


JMS providers
\\T400\C:\Documents and Settings\All Users\Application Data\IBM\MQSI\registry\MB7BROKER\CurrentVersion\ExternalResources\JMSProviders\ ActiveMQ BEA_Weblogic FioranoMQ Generic_File Generic_LDAP JBoss JOnAS Joram OpenJMS Oracle_AQ Oracle_OEMS SeeBeyond SonicMQ SwiftMQ Tibco_EMS WebSphere_MQ WebSphere_WAS_Client

Pendent


Links


Valid HTML 4.01!   Valid CSS!
Modificat el 7/3/2012.