SlideShare ist ein Scribd-Unternehmen logo
1 von 9
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

Weitere ähnliche Inhalte

Was ist angesagt? (11)

Solace Integration with Mulesoft
Solace Integration with MulesoftSolace Integration with Mulesoft
Solace Integration with Mulesoft
 
Jms
JmsJms
Jms
 
Jms
JmsJms
Jms
 
Understanding JMS Integration Patterns
Understanding JMS Integration Patterns Understanding JMS Integration Patterns
Understanding JMS Integration Patterns
 
Java Messaging Services
Java Messaging ServicesJava Messaging Services
Java Messaging Services
 
Jms intro
Jms introJms intro
Jms intro
 
Jms
JmsJms
Jms
 
SMS API InforUMobile
SMS API InforUMobileSMS API InforUMobile
SMS API InforUMobile
 
SMS API InforUMobile
SMS API InforUMobileSMS API InforUMobile
SMS API InforUMobile
 
test
testtest
test
 
test
testtest
test
 

Andere mochten auch (7)

Clasificación de las redes por cobertura
Clasificación de las redes por coberturaClasificación de las redes por cobertura
Clasificación de las redes por cobertura
 
Internet
InternetInternet
Internet
 
60 lecie Koła Łowieckiego Knieja
60 lecie Koła Łowieckiego Knieja60 lecie Koła Łowieckiego Knieja
60 lecie Koła Łowieckiego Knieja
 
Y si les parecio
Y si les parecioY si les parecio
Y si les parecio
 
Ap3d seo young deok
Ap3d seo young deokAp3d seo young deok
Ap3d seo young deok
 
Apah abet 8 presentation
Apah abet 8 presentationApah abet 8 presentation
Apah abet 8 presentation
 
Administered object config
Administered object configAdministered object config
Administered object config
 

Ähnlich wie Java message service

Test DB user
Test DB userTest DB user
Test DB user
techweb08
 
test validation
test validationtest validation
test validation
techweb08
 
Apache ActiveMQ and Apache Camel
Apache ActiveMQ and Apache CamelApache ActiveMQ and Apache Camel
Apache ActiveMQ and Apache Camel
Omi Om
 
Indianapolis mule soft_meetup_12_june_2021
Indianapolis mule soft_meetup_12_june_2021Indianapolis mule soft_meetup_12_june_2021
Indianapolis mule soft_meetup_12_june_2021
ikram_ahamed
 

Ähnlich wie Java message service (20)

Test DB user
Test DB userTest DB user
Test DB user
 
test validation
test validationtest validation
test validation
 
Apache ActiveMQ and Apache Camel
Apache ActiveMQ and Apache CamelApache ActiveMQ and Apache Camel
Apache ActiveMQ and Apache Camel
 
Jms
JmsJms
Jms
 
#7 (Java Message Service)
#7 (Java Message Service)#7 (Java Message Service)
#7 (Java Message Service)
 
Jms topics
Jms topicsJms topics
Jms topics
 
Indianapolis mule soft_meetup_12_june_2021
Indianapolis mule soft_meetup_12_june_2021Indianapolis mule soft_meetup_12_june_2021
Indianapolis mule soft_meetup_12_june_2021
 
Mule jms-topics
Mule jms-topicsMule jms-topics
Mule jms-topics
 
Jms session (1)
Jms session (1)Jms session (1)
Jms session (1)
 
JMS - Java Messaging Service
JMS - Java Messaging ServiceJMS - Java Messaging Service
JMS - Java Messaging Service
 
test
testtest
test
 
test
testtest
test
 
test
testtest
test
 
test
testtest
test
 
test
testtest
test
 
test
testtest
test
 
test
testtest
test
 
M messaging 1
M messaging 1M messaging 1
M messaging 1
 
Java Message Service
Java Message ServiceJava Message Service
Java Message Service
 
Jms topics
Jms   topicsJms   topics
Jms topics
 

Kürzlich hochgeladen

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Java message service

  • 1. 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
  • 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