SlideShare a Scribd company logo
Java Message Service – Quick learn (hopefully)
                                                                                             Veeramani S
                                                                                       vee.sam@live.com

Messaging ?

Messaging is one of the well known methods to integrate (communicate) two software components
(applications).

Major Benefits?

Asynchronous : Either of the parties (sender or receiver) need not be available at the same time. I.e.
sender can send a message as if the receiver is ready and waiting for the message even though actual
receiver is not active at the time of message sending. (Please note synchronous also possible)

Reliable : Possible to make sure that one message is delivered once and only once. (E.g. A refund
request to the customer should not processed more than one time)

How ?

Every message sent using JMS will be first received by the JMS Queue or Topic and will be available till
the appropriate client consumes the message.

JMS -API?

JMS is JAVA API helps JAVA developers quickly build application with a capable of create, send or
receive message from/to any other application.

Let us have some closer look:

Terminologies :

JMS Provider : Any vendor who is implementing the JMS API specification

JMS Client : Any Java application that creates, sends or receives messages using JMS implementation.

Message : is object from JMS family used to communicate between JMS clients.

Administered objects: Before stating our actual game there should be some infrastructure and
commonly agreed terms for the involved parties. (Destinations and connection factories)




                                                                                                           1
A small story now:




Figure 1 fictional scenario to depict asynchronous messaging and application integration using messaging

Some discussion and clarification from hamazzzon.com story

    1. Should the message server need not to be a standalone always?
          a. No it can be a part of hamazzzon.com application server or Fulfillment vendor
               application server also.
    2. How long a message can wait in the message server?
          a. Administrator of the server can configure, default is 0 which means never expires till the
               message is consumed by a client
    3. Can the same message be available after delivery to the Fulfillment vendor application?
          a. No, Strictly no dupes. Once and only once message will be delivered to the client.
    4. How long a message can wait in the message server?
          a. Queues retain all messages sent to them until the messages are consumed or until the
               messages expire
          b. Administrator of the server can configure the expiry time, default is 0 which means
               never expires till the message is consumed by a client.
    5. What happens if there is an exception?
          a. When an exception occurs while the message consumption
               message it will be marked as unread in the message server
               and will be ready to send for the next message lookup
               request.
          b. Also please note that it is possible to configure after certain
               number of attempts delivery failed message can be moved

                                                                                                           2
to another message (so that hamazzzon can take a look on to it to fix and resend) or
                deleted permanently (in our story it is not wise)
    6. How the message server determines that the message is consumed successfully by the client?
             a. Using the message acknowledge status. We will more about with sample code some
                time later.
    7. Is it possible to include other operation in the same consume call and make it as a single
       transaction (For example vendor wants to update a database)?
             a. YES it is possible transaction support can be extended for this scenario
    8. Is it possible to make the message sender to wait until a message consuming client pick up the
       message?
             a. YES it is possible through ACKNOWLWDGE_MODE setting (then it would turn as
                synchronous* call)

LITTLE more concepts before we start our ROCKING code!

In ancient days most of the MOM(Message Oriented Middleware) or messaging providers support one
of the following category but after the period JMS birth, most(all !) of the messaging providers started
supporting both in single product

Point-to-Point

In this approach single message can be consumed by a single client. Consider our fulfillment story which
is really a point-to-point example, even if our hamazzzon.com has more than one fulfillment vendor only
one of the vendor can/should do the fulfillment.

In JMS call this approached message destination as Queue




                                       Figure 2 Point-to-Point (Queue)

Publisher Subscriber

In this approach single message can be consumed by more than one client. Consider RBI (central bank)
wants to send new rate of interest tariff to all the participant banks the same message has to be
processed by all the banks subscribed.

In JMS call this approached message destination as Topic



                                                                                                           3
Figure 3 Publisher Subscriber (Topic)

Some discussion from these concepts:

   1. If there is more than one message consumption clients in what order message delivered to
      client?
            a. Whoever first calls the receive message method will the chance to consume
            b. However ordering can be defined in the message level so that server can decide which
                message should be delivered first.
   2. Will all the consumer clients in the topic always get the message published in the Topic?
            a. NO. Only the clients online at the time of message publish will the chance to consume
                it.
            b. YES. By marking as durable consumer we can provide the capability to receive messages
                published while the consumer was not active. However this messages are limited from
                the time since durable consumer of a topic created
   3. Is it guarantee that message every will be consumed at least once by its
      client in topic?
            a. No, for example if a topic has all non durable consumers and none
                of them active at the time of message publish then the message
                will not be processed by any client
   4. Now it might sound little late question nevertheless, what actually I can
      send using JMS?
            a. TextMessage, MapMessage, BytesMessage, StreamMessage and
                ObjectMessage




                        If you are not familiar with Administered objects configuration steps, you
                            can get familiar using Weblogic server sample explained in this link.




                                                                                                     4
Where is my code!




                    Figure 4 JMS programming model




                                                     5
Message producer/sender client

import   javax.jms.Connection;
import   javax.jms.ConnectionFactory;
import   javax.jms.Destination;
import   javax.jms.JMSException;
import   javax.jms.MessageProducer;
import   javax.jms.Session;
import   javax.jms.TextMessage;
import   javax.naming.Context;
import   javax.naming.InitialContext;
import   javax.naming.NamingException;

/**
 * @author sv
 *
 */
public class TestJmsMessageSender {

         public static void main(String[] args) {
               Context jndiContext = null;
               ConnectionFactory connectionFactory = null;
               Connection connection = null;
               Session session = null;
               Destination dest = null;

              /*
               * Setting environment property, this should be ideally come form
               * properties files and should be set through HashMap, But it is
               * OK for our test run
               */

            System.setProperty("java.naming.factory.initial",
                        "weblogic.jndi.WLInitialContextFactory");
            System.setProperty("java.naming.provider.url",
"t3://localhost:7001");


              try {
                      jndiContext = new InitialContext();

                  connectionFactory = (ConnectionFactory)
jndiContext.lookup("jms/TestJmsConnectionFactory");
                  dest = (Destination)
jndiContext.lookup("jms/TestJmsQueue");

                      /*
                       * Create connection. Create session from connection; false
means
                       * session is not transacted.
                       */

                      connection = connectionFactory.createConnection();




                                                                                    6
session =
connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);

                        MessageProducer msgProducer = session.createProducer(dest);
                        TextMessage message = session.createTextMessage();

                        message.setText("JMS TextMessage test......");

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

                  } catch (NamingException e) {
                        e.printStackTrace();
                  }

                  catch (JMSException e) {
                        System.out.println("Exception occurred: " + e.toString());
                  } finally {
                        if (connection != null) {
                              try {
                                    connection.close();
                              } catch (JMSException e) {
                              }
                        }
                  }
         }
}


Message Consumer/receiver client

import       javax.jms.Connection;
import       javax.jms.ConnectionFactory;
import       javax.jms.Destination;
import       javax.jms.JMSException;
import       javax.jms.MessageConsumer;
import       javax.jms.Queue;
import       javax.jms.QueueConnectionFactory;
import       javax.jms.Session;
import       javax.jms.TextMessage;
import       javax.naming.Context;
import       javax.naming.InitialContext;
import       javax.naming.NamingException;

/**
 * @author sv
 *
 *
 */
public class TestJmsMessageReceiver {



                                                                                      7
public static void main(String[] args) {
              Context jndiContext = null;
              ConnectionFactory connectionFactory = null;
              Connection connection = null;
              Session session = null;
              Destination dest = null;

            /*
             * Setting environment property
             */
            System.setProperty("java.naming.factory.initial",
                        "weblogic.jndi.WLInitialContextFactory");
            System.setProperty("java.naming.provider.url",
"t3://localhost:7001");


              try {
                      jndiContext = new InitialContext();

                  connectionFactory = (QueueConnectionFactory)
jndiContext.lookup("jms/TestJmsConnectionFactory");
                  dest = (Queue) jndiContext.lookup("jms/TestJmsQueue");

                      /*
                       * Create connection. Create session from connection; false
means
                       * session is not transacted. Create sender and text
message. Send
                       * messages, varying text slightly. Finally, close
connection.
                       */

                      connection = connectionFactory.createConnection();

                  session =
connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);
                  connection.start();

                      MessageConsumer consumer = session.createConsumer(dest);


                  TextMessage message =    (TextMessage)
consumer.receive(1000);
                  System.out.println(message.getText());

                      message =    (TextMessage) consumer.receive(1000);
                      System.out.println(message.getText());
                      message.acknowledge();

                      //queueSession.commit();

              } catch (NamingException e) {
                    e.printStackTrace();
                                      System.exit(1);
              }

              catch (JMSException e) {

                                                                                    8
System.out.println("Exception occurred: " + e.toString());
                }
                catch(Exception e){
                      e.printStackTrace();
                }
                finally {
                      if (connection != null) {
                            try {
                                  connection.close();
                            } catch (JMSException e) {
                            }
                      }
                }
        }
}



/! Trap zone :

    1. Any acknowledge mode will be ignored if the transaction is enable in a session

             For example in the following code transaction flag is set as “true” hence whatever
             acknowledgement mode provided here will be ignored and set as “AUTO_ACKNOWLEDGE”,
             if the transaction succeeds then message will get automatically acknowledge ( using which
             means server will determine whether to remove the message or to redeliver).

             QueueSession queueSession createQueueSession(true,Session.
             CLIENT_ACKNOWLEDGE);

    2. UserTransaction handling is allowed only for the MDBs configured as Bean-managed
       transactions
           a. For example messageDrivenContext.getUserTransaction().begin() will throw an
               exception if it called from a MDB which is configured as Container transitioned
    3. MessageDrivenContext’s setRollbackOnly() would cause the server to re-deliver the message
       again. However this is legal only if the provider(connection factory) is XA transaction enabled

    4. MDB acknowledge mode can either “Auto-Acknowledge” or “DUPS_OK_ACKNOWLEDGE” any
       other mode is not allowed
    5. Throwing an exception in the onMessage() method of MDB make the server to re-deliver the
       message again
    6. Security is depends on the provider and it’s a architectural decision.


Exercise :

Set a Topic in your application server and try a similar program
Try to set up MDB and consume message send from a producer.
In case of any clarification please contact me though my email, I will try to resolve.


                                                                                                         9

More Related Content

What's hot (11)

DOCX
Solace Integration with Mulesoft
Integration Assistance
 
PDF
Understanding JMS Integration Patterns
WSO2
 
PPT
Java Messaging Services
kumar gaurav
 
PPT
Jms intro
Manav Prasad
 
PPT
Jms
Manav Prasad
 
PDF
SMS API InforUMobile
inforumobile
 
PDF
SMS API InforUMobile
inforumobile
 
PDF
test
marenostrumad
 
PPT
test
techweb08
 
Solace Integration with Mulesoft
Integration Assistance
 
Understanding JMS Integration Patterns
WSO2
 
Java Messaging Services
kumar gaurav
 
Jms intro
Manav Prasad
 
SMS API InforUMobile
inforumobile
 
SMS API InforUMobile
inforumobile
 
test
techweb08
 

Viewers also liked (7)

PPTX
Clasificación de las redes por cobertura
Luisa Bedoya Valencia
 
PPTX
Internet
Rere Vezhiama
 
PPT
60 lecie Koła Łowieckiego Knieja
kacpersky21
 
PPT
Y si les parecio
Pepe030597
 
PPTX
Ap3d seo young deok
Florence
 
PPTX
Apah abet 8 presentation
Florence
 
PPTX
Administered object config
Veeramani S
 
Clasificación de las redes por cobertura
Luisa Bedoya Valencia
 
Internet
Rere Vezhiama
 
60 lecie Koła Łowieckiego Knieja
kacpersky21
 
Y si les parecio
Pepe030597
 
Ap3d seo young deok
Florence
 
Apah abet 8 presentation
Florence
 
Administered object config
Veeramani S
 
Ad

Similar to Java message service (20)

PPT
test validation
techweb08
 
PPT
Test DB user
techweb08
 
ODP
Apache ActiveMQ and Apache Camel
Omi Om
 
PPTX
#7 (Java Message Service)
Ghadeer AlHasan
 
PPT
Jms topics
Ravinder Singh
 
PPTX
Indianapolis mule soft_meetup_12_june_2021
ikram_ahamed
 
PPTX
Mule jms-topics
Gandham38
 
PPT
How to apply Messaging In Java in Enterprise
HieuHuy9
 
PPTX
Jms session (1)
Marwa Dosoky
 
PDF
JMS - Java Messaging Service
Peter R. Egli
 
PPT
test
techweb08
 
PPT
test
techweb08
 
PPT
test
techweb08
 
PPT
test
techweb08
 
PPT
test
techweb08
 
PPT
test
techweb08
 
PPT
test
techweb08
 
PPTX
M messaging 1
Vasanthii Chowdary
 
PPTX
Java Message Service
AMIT YADAV
 
test validation
techweb08
 
Test DB user
techweb08
 
Apache ActiveMQ and Apache Camel
Omi Om
 
#7 (Java Message Service)
Ghadeer AlHasan
 
Jms topics
Ravinder Singh
 
Indianapolis mule soft_meetup_12_june_2021
ikram_ahamed
 
Mule jms-topics
Gandham38
 
How to apply Messaging In Java in Enterprise
HieuHuy9
 
Jms session (1)
Marwa Dosoky
 
JMS - Java Messaging Service
Peter R. Egli
 
test
techweb08
 
test
techweb08
 
test
techweb08
 
test
techweb08
 
test
techweb08
 
test
techweb08
 
test
techweb08
 
M messaging 1
Vasanthii Chowdary
 
Java Message Service
AMIT YADAV
 
Ad

Recently uploaded (20)

PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 

Java message service

  • 1. Java Message Service – Quick learn (hopefully) Veeramani S [email protected] Messaging ? Messaging is one of the well known methods to integrate (communicate) two software components (applications). Major Benefits? Asynchronous : Either of the parties (sender or receiver) need not be available at the same time. I.e. sender can send a message as if the receiver is ready and waiting for the message even though actual receiver is not active at the time of message sending. (Please note synchronous also possible) Reliable : Possible to make sure that one message is delivered once and only once. (E.g. A refund request to the customer should not processed more than one time) How ? Every message sent using JMS will be first received by the JMS Queue or Topic and will be available till the appropriate client consumes the message. JMS -API? JMS is JAVA API helps JAVA developers quickly build application with a capable of create, send or receive message from/to any other application. Let us have some closer look: Terminologies : JMS Provider : Any vendor who is implementing the JMS API specification JMS Client : Any Java application that creates, sends or receives messages using JMS implementation. Message : is object from JMS family used to communicate between JMS clients. Administered objects: Before stating our actual game there should be some infrastructure and commonly agreed terms for the involved parties. (Destinations and connection factories) 1
  • 2. A small story now: Figure 1 fictional scenario to depict asynchronous messaging and application integration using messaging Some discussion and clarification from hamazzzon.com story 1. Should the message server need not to be a standalone always? a. No it can be a part of hamazzzon.com application server or Fulfillment vendor application server also. 2. How long a message can wait in the message server? a. Administrator of the server can configure, default is 0 which means never expires till the message is consumed by a client 3. Can the same message be available after delivery to the Fulfillment vendor application? a. No, Strictly no dupes. Once and only once message will be delivered to the client. 4. How long a message can wait in the message server? a. Queues retain all messages sent to them until the messages are consumed or until the messages expire b. Administrator of the server can configure the expiry time, default is 0 which means never expires till the message is consumed by a client. 5. What happens if there is an exception? a. When an exception occurs while the message consumption message it will be marked as unread in the message server and will be ready to send for the next message lookup request. b. Also please note that it is possible to configure after certain number of attempts delivery failed message can be moved 2
  • 3. to another message (so that hamazzzon can take a look on to it to fix and resend) or deleted permanently (in our story it is not wise) 6. How the message server determines that the message is consumed successfully by the client? a. Using the message acknowledge status. We will more about with sample code some time later. 7. Is it possible to include other operation in the same consume call and make it as a single transaction (For example vendor wants to update a database)? a. YES it is possible transaction support can be extended for this scenario 8. Is it possible to make the message sender to wait until a message consuming client pick up the message? a. YES it is possible through ACKNOWLWDGE_MODE setting (then it would turn as synchronous* call) LITTLE more concepts before we start our ROCKING code! In ancient days most of the MOM(Message Oriented Middleware) or messaging providers support one of the following category but after the period JMS birth, most(all !) of the messaging providers started supporting both in single product Point-to-Point In this approach single message can be consumed by a single client. Consider our fulfillment story which is really a point-to-point example, even if our hamazzzon.com has more than one fulfillment vendor only one of the vendor can/should do the fulfillment. In JMS call this approached message destination as Queue Figure 2 Point-to-Point (Queue) Publisher Subscriber In this approach single message can be consumed by more than one client. Consider RBI (central bank) wants to send new rate of interest tariff to all the participant banks the same message has to be processed by all the banks subscribed. In JMS call this approached message destination as Topic 3
  • 4. Figure 3 Publisher Subscriber (Topic) Some discussion from these concepts: 1. If there is more than one message consumption clients in what order message delivered to client? a. Whoever first calls the receive message method will the chance to consume b. However ordering can be defined in the message level so that server can decide which message should be delivered first. 2. Will all the consumer clients in the topic always get the message published in the Topic? a. NO. Only the clients online at the time of message publish will the chance to consume it. b. YES. By marking as durable consumer we can provide the capability to receive messages published while the consumer was not active. However this messages are limited from the time since durable consumer of a topic created 3. Is it guarantee that message every will be consumed at least once by its client in topic? a. No, for example if a topic has all non durable consumers and none of them active at the time of message publish then the message will not be processed by any client 4. Now it might sound little late question nevertheless, what actually I can send using JMS? a. TextMessage, MapMessage, BytesMessage, StreamMessage and ObjectMessage If you are not familiar with Administered objects configuration steps, you can get familiar using Weblogic server sample explained in this link. 4
  • 5. Where is my code! Figure 4 JMS programming model 5
  • 6. Message producer/sender client import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; /** * @author sv * */ public class TestJmsMessageSender { public static void main(String[] args) { Context jndiContext = null; ConnectionFactory connectionFactory = null; Connection connection = null; Session session = null; Destination dest = null; /* * Setting environment property, this should be ideally come form * properties files and should be set through HashMap, But it is * OK for our test run */ System.setProperty("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory"); System.setProperty("java.naming.provider.url", "t3://localhost:7001"); try { jndiContext = new InitialContext(); connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/TestJmsConnectionFactory"); dest = (Destination) jndiContext.lookup("jms/TestJmsQueue"); /* * Create connection. Create session from connection; false means * session is not transacted. */ connection = connectionFactory.createConnection(); 6
  • 7. session = connection.createSession(false,Session.CLIENT_ACKNOWLEDGE); MessageProducer msgProducer = session.createProducer(dest); TextMessage message = session.createTextMessage(); message.setText("JMS TextMessage test......"); System.out.println("Sending message: " + message.getText()); msgProducer.send(message); System.out.println("Sending message: " + message.getText()); msgProducer.send(message); } catch (NamingException e) { e.printStackTrace(); } catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { } } } } } Message Consumer/receiver client import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.Queue; import javax.jms.QueueConnectionFactory; import javax.jms.Session; import javax.jms.TextMessage; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; /** * @author sv * * */ public class TestJmsMessageReceiver { 7
  • 8. public static void main(String[] args) { Context jndiContext = null; ConnectionFactory connectionFactory = null; Connection connection = null; Session session = null; Destination dest = null; /* * Setting environment property */ System.setProperty("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory"); System.setProperty("java.naming.provider.url", "t3://localhost:7001"); try { jndiContext = new InitialContext(); connectionFactory = (QueueConnectionFactory) jndiContext.lookup("jms/TestJmsConnectionFactory"); dest = (Queue) jndiContext.lookup("jms/TestJmsQueue"); /* * Create connection. Create session from connection; false means * session is not transacted. Create sender and text message. Send * messages, varying text slightly. Finally, close connection. */ connection = connectionFactory.createConnection(); session = connection.createSession(false,Session.CLIENT_ACKNOWLEDGE); connection.start(); MessageConsumer consumer = session.createConsumer(dest); TextMessage message = (TextMessage) consumer.receive(1000); System.out.println(message.getText()); message = (TextMessage) consumer.receive(1000); System.out.println(message.getText()); message.acknowledge(); //queueSession.commit(); } catch (NamingException e) { e.printStackTrace(); System.exit(1); } catch (JMSException e) { 8
  • 9. System.out.println("Exception occurred: " + e.toString()); } catch(Exception e){ e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { } } } } } /! Trap zone : 1. Any acknowledge mode will be ignored if the transaction is enable in a session For example in the following code transaction flag is set as “true” hence whatever acknowledgement mode provided here will be ignored and set as “AUTO_ACKNOWLEDGE”, if the transaction succeeds then message will get automatically acknowledge ( using which means server will determine whether to remove the message or to redeliver). QueueSession queueSession createQueueSession(true,Session. CLIENT_ACKNOWLEDGE); 2. UserTransaction handling is allowed only for the MDBs configured as Bean-managed transactions a. For example messageDrivenContext.getUserTransaction().begin() will throw an exception if it called from a MDB which is configured as Container transitioned 3. MessageDrivenContext’s setRollbackOnly() would cause the server to re-deliver the message again. However this is legal only if the provider(connection factory) is XA transaction enabled 4. MDB acknowledge mode can either “Auto-Acknowledge” or “DUPS_OK_ACKNOWLEDGE” any other mode is not allowed 5. Throwing an exception in the onMessage() method of MDB make the server to re-deliver the message again 6. Security is depends on the provider and it’s a architectural decision. Exercise : Set a Topic in your application server and try a similar program Try to set up MDB and consume message send from a producer. In case of any clarification please contact me though my email, I will try to resolve. 9