Oracle TopLink with Message Driven Beans

How-To Document

January 2006

After reading this How-To document, you should be able to:

Software Requirements

Conventions

The following conventions are used in this document:

Introduction

This How-To demonstrates a Message-Driven Bean using OracleAS TopLink to persist regular Java objects, with examples of

This How To illustrates storing messages received from JMS (Java Message Service) into a database, then reading these stored messages. A simple JSP front-end with servlets to log and read messages from the database provide interaction.

Sessions

You must create the required server and client sessions for TopLink. For example, Example: Database Session shows a typical database session with the applicable getServerSession(), getSession(), getUnitOfWork(), and getNonTxUnitOfWork() methods.

Database Session

public class SessionHelperSingleton {
  private static String SESSION_NAME = "messagedrivenbean"; // project name as it exists in the MW project file
  private static SessionHelperSingleton m_instance = null; // single instance of this class
 
  static {
  ConversionManager.getDefaultManager().setShouldUseClassLoaderFromCurrentThread(true);
  }
 
  // The default constructor for the class.
  private SessionHelperSingleton() {}
 
  // Return the (only) instance of this class.
  static SessionHelperSingleton getInstance() {
    if (m_instance == null) {
      m_instance = new SessionHelperSingleton();
    }
    return m_instance;
  }
 
  // Return a single session that supports multiple user/clients connection at the same time.
  private static Server getServerSession() {
    return (Server)SessionManager.getManager().getSession(SESSION_NAME, SessionHelperSingleton.class.getClassLoader());
  }
 
// Return a client session for this server session.
  static Session getSession() {
    return getServerSession().acquireClientSession();
  }
 
// Return the active unit of work for the current active external (JTS) transaction.
  static UnitOfWork getUnitOfWork() {
    return getServerSession().getActiveUnitOfWork();
  }

// Return a external transaction independant unit of work for this session.
  static UnitOfWork getNonTxUnitOfWork() {
    return getSession().acquireUnitOfWork();
  }}

Example: sesssions.xml shows a sample sessions.xml file for use with the previous database session.

sesssions.xml

<toplink-configuration>
   <session>
      <name>messagedrivenbean</name>
      <project-xml>MessageDrivenProject.xml</project-xml>
      <session-type>
         <server-session/>
      </session-type>
      <login>
         <type>oracle.toplink.sessions.DatabaseLogin</type>
         <datasource>java:comp/env/jdbc/JTSTopLinkDS</datasource>
         <platform-class>oracle.toplink.internal.databaseaccess.OraclePlatform</platform-class>
         <uses-external-connection-pool>true</uses-external-connection-pool>
         <uses-external-transaction-controller>true</uses-external-transaction-controller>
         <non-jts-datasource>java:comp/env/jdbc/JTSTopLinkDS</non-jts-datasource>
      </login>
      <external-transaction-controller-class>oracle.toplink.jts.oracle9i.Oracle9iJTSExternalTransactionController</external-transaction-controller-class>
      <enable-logging>true</enable-logging>
      <logging-options/>
   </session>
</toplink-configuration>

Logging Messages

To log a message to the database, TopLink executes the following in a unit of work:

UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + 50 WHERE SEQ_NAME = 'Msg_SEQ'
SELECT SEQ_COUNT FROM SEQUENCE WHERE SEQ_NAME = 'Msg_SEQ'
INSERT INTO MESSAGES (M_MESSAGE, M_DATE, M_ID, M_SUBJECT) VALUES ('<message>', {d '<date>'}, <SEQUENCE NUMBER>, '<subject>')

In this example, TopLink provides a unique sequence number counter. TopLink executes the unit of work based on the following Java code:

public class LogMessageServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
      request.setCharacterEncoding("UTF-8");
      response.setContentType("text/html; charset=UTF-8");
      getServletContext().log("LogMessages servlet - doGet");

      // redirect to post method
      doPost(request, response);
    }

    // Handle 'Post' request.
    public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        try {
          TopicConnectionFactory connectionFactory = (TopicConnectionFactory) new InitialContext().lookup("java:comp/env/jms/theTopicConnectionFactory");
          TopicConnection connection = connectionFactory.createTopicConnection();connection.start();
          TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
          Topic topic = (Topic) new InitialContext().lookup("java:comp/env/jms/theTopic");
          TopicPublisher publisher = topicSession.createPublisher(topic);
          // create a message using user input
          Message message = topicSession.createMessage();
          message.setJMSType("messageLogger");
          message.setLongProperty("time", System.currentTimeMillis());
          message.setStringProperty("subject", request.getParameter("subject"));
          message.setStringProperty("message", request.getParameter("message"));
          // publish the message
          publisher.publish(message);
          publisher.close();
          topicSession.close();
          connection.close();
        }
        catch (NamingException ne) {
          request.setAttribute("source", "LogMessageServlet doPost");
          request.setAttribute("header", "An Error Occurred");
          request.setAttribute("errorMessage", ne.getMessage());
          request.getRequestDispatcher("./errorPage.jsp").forward(request, response);
          return;
        }
       catch (JMSException jmse) {
          request.setAttribute("source", "LogMessageServlet doPost");
          request.setAttribute("header", "An Error Occurred");
          request.setAttribute("errorMessage", jmse.getMessage());
          request.getRequestDispatcher("./errorPage.jsp").forward(request, response);
          return;
       }
  }
}

Each time a message is published (illustrated in the LogMessageServlet code snippet) the onMessage() method is called and the message is then logged to the database using the following code:

/**
* Called upon receipt of message associated with the queue/topic this bean is * registered with.
*  * @see javax.jms.MessageListener#onMessage(Message)
*/
public void onMessage(Message message) {
  try {
  // print the received message
  System.out.println("Received message: '" + message.getStringProperty("message") + "'"); 
  // since there is no associated external transaction, get a non-transactional unit of work
  UnitOfWork uow = SessionHelperSingleton.getInstance().getNonTxUnitOfWork();
  Messages msgObject = (Messages) uow.registerObject(new Messages());

  msgObject.setSubject(message.getStringProperty("subject"));
  msgObject.setMessage(message.getStringProperty("message"));
  msgObject.setM_date(new Date(message.getLongProperty("time")));
  uow.commit();
  } catch (JMSException jmse) {
    System.out.println("JMS Exception: " + jmse.getMessage());
  }
}

Receiving Messages

To receive a specific message from the database, TopLink executes the following in a unit of work:

SELECT M_ID, M_MESSAGE, M_DATE, M_SUBJECT FROM MESSAGES

TopLink executes the unit of work based on the following Java code:

public Messages getMessage(String id) {
  Messages msg;
  try {
    ExpressionBuilder builder = new ExpressionBuilder();
    Expression exp = builder.get("m_id").equal(id);
    Session session = SessionHelperSingleton.getInstance().getSession();
    msg = (Messages) (session.readObject(Messages.class, exp));
  }
  catch (Exception e) {
    System.out.println("Exception: " + e.getMessage());
    return null;
  }
  return msg;
}

Summary

This How-To has shown examples of using TopLink with message driven beans.


Oracle TopLink, 10g Release 3 (10.1.3)

The Programs (which include both the software and documentation) contain proprietary information; they are provided under a license agreement containing restrictions on use and disclosure and are also protected by copyright, patent, and other intellectual and industrial property laws. Reverse engineering, disassembly, or decompilation of the Programs, except to the extent required to obtain interoperability with other independently created software or as specified by law, is prohibited.

The information contained in this document is subject to change without notice. If you find any problems in the documentation, please report them to us in writing. This document is not warranted to be error-free. Except as may be expressly permitted in your license agreement for these Programs, no part of these Programs may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose.

If the Programs are delivered to the United States Government or anyone licensing or using the Programs on behalf of the United States Government, the following notice is applicable:

U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers are "commercial computer software" or "commercial technical data" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, use, duplication, disclosure, modification, and adaptation of the Programs, including documentation and technical data, shall be subject to the licensing restrictions set forth in the applicable Oracle license agreement, and, to the extent applicable, the additional rights set forth in FAR 52.227-19, Commercial Computer Software—Restricted Rights (June 1987). Oracle Corporation, 500 Oracle Parkway, Redwood City, CA 94065

The Programs are not intended for use in any nuclear, aviation, mass transit, medical, or other inherently dangerous applications. It shall be the licensee's responsibility to take all appropriate fail-safe, backup, redundancy and other measures to ensure the safe use of such applications if the Programs are used for such purposes, and we disclaim liability for any damages caused by such use of the Programs.

Oracle, JD Edwards and PeopleSoft are registered trademarks of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

The Programs may provide links to Web sites and access to content, products, and services from third parties. Oracle is not responsible for the availability of, or any content provided on, third-party Web sites. You bear all risks associated with the use of such content. If you choose to purchase any products or services from a third party, the relationship is directly between you and the third party. Oracle is not responsible for: (a) the quality of third-party products or services; or (b) fulfilling any of the terms of the agreement with the third party, including delivery of products or services and warranty obligations related to purchased products or services. Oracle is not responsible for any loss or damage of any sort that you may incur from dealing with any third party.

Alpha and Beta Draft documentation are considered to be in prerelease status. This documentation is intended for demonstration and preliminary use only. We expect that you may encounter some errors, ranging from typographical errors to data inaccuracies. This documentation is subject to change without notice, and it may not be specific to the hardware on which you are using the software. Please be advised that prerelease documentation in not warranted in any manner, for any purpose, and we will not be responsible for any loss, costs, or damages incurred due to the use of this documentation.