Show TOC

Using TransactionsLocate this document in the navigation structure

Use

In a JMS client, you can use local transactions to group messages being sent or received. All messages sent during a transaction come into existence at the point where the transaction is committed (and thus become visible to consumers). If the transaction is rolled back, the messages sent will disappear as if they had never been produced. All messages received during a transaction are acknowledged at the point the transaction is committed. If the transaction is rolled back, the messages will be redelivered.

Procedure

To use transactions, you have to create a session specifying that it is transacted. The first argument of the createQueueSession and the createTopicSession methods is a boolean value. It is true for transacted session, otherwise it is false . The second value of these methods is the acknowledgement mode, which is relevant only for nontransacted sessions. If the session is transacted, the second argument is ignored.

            topicSession = topicConnection.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);

         

To commit the transaction, use the commit method. After committing the transaction, the messages appear.

            topicSession.commit();

         

To roll back the transaction, use the rollback method.

            topicSession.rollback();

         

If you close a transacted session, you roll back its transaction in progress, including any messages pending to be produced or consumed.

Example
            package com.sap.test.jms;

 

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Enumeration;

import java.util.Properties;

 

import javax.annotation.Resource;

import javax.jms.JMSException;

import javax.jms.Queue;

import javax.jms.QueueBrowser;

import javax.jms.QueueConnection;

import javax.jms.QueueConnectionFactory;

import javax.jms.QueueSender;

import javax.jms.QueueSession;

import javax.jms.Session;

import javax.jms.TextMessage;

import javax.naming.Context;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.transaction.UserTransaction;

 

/**

 * Servlet implementation class for Servlet: SendingServlet

 * 

 */

 

public class UsingTransactionsServlet extends javax.servlet.http.HttpServlet

      implements javax.servlet.Servlet {

 

   private static final long serialVersionUID = 1L;

 

   private static final String USER = "user";

 

   private static final String PASSWORD = "password";

 

   private static final String SAP_NAMING_PROVIDER_URL = "localhost:56004";

 

   private static final String SAP_INITIAL_CONTEXT_FACTORY_IMPL = "com.sap.engine.services.jndi.InitialContextFactoryImpl";

 

   private PrintWriter printWriter;

 

   @Resource

   UserTransaction ut;

 

   // inject QueueConnectionFactory to the field queueConnectionFactoryAnnot

   @Resource(mappedName = "MyServletQueueConnectionFactory")

   private QueueConnectionFactory queueConnectionFactoryAnnot;

 

   // inject Queue to the field queueAnnot

   @Resource(mappedName = "MyServletQueue")

   private Queue queueAnnot;

 

   public UsingTransactionsServlet() {

      super();

   }

 

   protected void doGet(HttpServletRequest request,

         HttpServletResponse response) throws ServletException, IOException {

      doTest(request, response);

   }

 

   protected void doPost(HttpServletRequest request,

         HttpServletResponse response) throws ServletException, IOException {

      doTest(request, response);

   }

 

   private void doTest(HttpServletRequest request, HttpServletResponse response)

         throws ServletException {

      QueueConnection queueConnection = null;

      QueueSession queueSession = null;

      QueueSender queueSender = null;

      TextMessage message = null;

 

      try {

         printWriter = response.getWriter();

      } catch (IOException ioe) {

         ioe.printStackTrace();

         throw new ServletException("Exception during response.getWriter()");

      }

 

      printWriter.println("Start sending.<br>");

 

      // set the properties of the connection

      Properties properties = System.getProperties();

      properties.put(Context.INITIAL_CONTEXT_FACTORY,

            SAP_INITIAL_CONTEXT_FACTORY_IMPL);

      properties.put(Context.PROVIDER_URL, SAP_NAMING_PROVIDER_URL);

      properties.put(Context.SECURITY_PRINCIPAL, USER);

      properties.put(Context.SECURITY_CREDENTIALS, PASSWORD);

 

      try {

         // queueConnectionFactoryAnnot is injected via annotation

         queueConnection = queueConnectionFactoryAnnot

               .createQueueConnection();

         queueSession = queueConnection.createQueueSession(true,

               Session.AUTO_ACKNOWLEDGE);

         // queueAnnot is injected via annotation

         queueSender = queueSession.createSender(queueAnnot);

         message = queueSession.createTextMessage();

         queueConnection.start();

 

         // starting a transaction

         ut.begin();

         printWriter

               .println("<br>Starting a transaction with transaction.begin().");

         for (int i = 1; i < 3; i++) {

            message.setText("This is message " + i);

            printWriter.println("<br>" + "Sending message " + i);

            queueSender.send(message);

         }

         // committing the transaction

         ut.commit();

         printWriter

               .println("<br>Committing a transaction with transaction.commit().<br>");

 

         // starting another transaction

         ut.begin();

         printWriter

               .println("<br>Starting another transaction with transaction.begin().");

         for (int i = 3; i < 5; i++) {

            message.setText("This is message " + i);

            printWriter.println("<br>" + "Sending message " + i);

            queueSender.send(message);

         }

         // rolling back the transaction

         ut.rollback();

         printWriter

               .println("<br>Rollbacking a transaction with transaction.rollback().<br>");

 

         printWriter.println("<br>End sending.<br>");

 

         printWriter.println("<br>MyServletQueue contains:");

         // monitoring the content of the queue after transaction's

         // operations

         QueueBrowser browser = queueSession.createBrowser(queueAnnot);

         Enumeration en = browser.getEnumeration();

 

         while (en.hasMoreElements()) {

            TextMessage queueBrMessage = (TextMessage) en.nextElement();

            printWriter.println("<br>" + queueBrMessage.getText());

         }

 

      } catch (JMSException e) {

         throw new ServletException("JMSException occurred: " + e.toString());

 

      } catch (Exception ex) {

         throw new ServletException("Exception occurred: " + ex.toString());

 

      } finally {

         if (queueConnection != null) {

 

            try {

               queueConnection.close();

            } catch (JMSException e) {

               throw new ServletException(

                     "Exception during queueConnection.close()");

            }

         }

      }

   }

}