Welcome!

Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

Related Topics: Weblogic

Weblogic: Article

JMS and WebLogic 7.0

JMS and WebLogic 7.0

This article demonstrates how to create a gateway class for sending JMS messages generically with WebLogic. This is beneficial for any asynchronous messaging effort, and provides a basis for future JMS development. A generic access path for sending JMS messages is provided. We will also cover setting up a JMS topic within WebLogic 7.0. A sample message-driven bean is provided as well.

Program communication is generally "synchronous," meaning that the client sends a request and waits for a response (e.g., client/server or distributed object RMI call). Asynchronous messaging provides an alternative means of program communication in which the initiating program writes a message to the JMS session, and the WebLogic container ensures delivery. The initiating program does not get anything back. This allows the program to continue other processing or return control to the user.

Asynchronous messaging can vastly increase response times to the user because it does not require additional business logic processing time. However, because asynchronous processes cannot return an immediate response, separate asynchronous notification methods must also be employed. Potential notification solutions include e-mail, a status or work queue view, or a scrolling update bar within the application.

Many software projects are affected by poor performance. While asynchronous messaging can improve performance, JMS solutions are uncommon in today's business environment. Few success stories have been observed beyond simple asynchronous data transfer, which may not even be JMS's best usage.

Part of the problem is that many designers and business requirements teams think only within the request-response box. The concept of "I push a button, and then the process starts, and it is done when I get a confirmation screen" is easily understood by all. While this process may be necessary for some applications, the asynchronous alternative should always be considered as well. It's not as foreign a concept as it seems. Consider how e-mail works...your system is not locked between the time that an e-mail message is sent and received, and yet there is the confidence that it will arrive at its destination.

Using JMS
When can asynchronous processing be used? Almost anything that is currently processed synchronously can be developed asynchronously, especially processes that do not return anything to the user. Some appropriate applications include:

  • Business processes requiring complex calculations and/or many synchronous reads and formulations: Developers know that these processes are very prone to causing performance problems. However, if these activities are run asynchronously, the user can continue processing while the complex business process is being resolved. The asynchronous solution to this business process also lends itself to being run on a dedicated server.
  • Several separate, unrelated processes are kicked off by one main task: In the synchronous world, this must be managed carefully, and many times these tasks are simply kicked off in sequential order, although they needn't be. Asynchronously, each process can be kicked off without waiting for the others to finish.
  • Logging: Some logging solutions become fairly complex, involving writing to databases and separate files and sending e-mail. Asynchronously processing a logging solution allows it to be as complex as needed, without each enhancement impacting performance.
  • Necessary communication to down servers: The JMS specification provides durable subscribers that allow the WebLogic container to hold the message until its destination becomes active.
  • Large-scale processing of voluminous information: JMS automatically provides priority processing; thus, the lower priority items don't threaten the ability of the system to begin processing more critical tasks.

    Many more applications for asynchronous messaging exist, but I hope that at this point you are more interested in learning how it works. If not, it's time to move on, as this article is about to get slightly more technical.

    Quick JMS Overview
    The JMS specification includes a series of Java interface definitions that provide a means for asynchronous messaging. WebLogic provides an implemention that allows the application server to send or receive JMS messages through the container. Message delivery is guaranteed.

    There are two types of asynchronous messaging: point to point (P2P or PTP), and publish and subscribe (Pub-Sub). P2P involves a direct connection to one other listening party. It uses a queue as its primary sending mechanism. Pub-Sub allows the sender to post to a topic to which multiple listeners may have access. There is no direct connection between sender and receiver in the Pub-Sub model. JMS provides alternative implementations for each type. WebLogic allows P2P messages to be browsed prior to receipt and Pub-Sub messages to be sent even if the receiving client is not active at the time of attempted delivery.

    The initial interface in the JMS API hierarchy is the ConnectionFactory. The QueueConnectionFactory or TopicConnectionFactory enables the client to open a connection to the JMS message broker. The JMS message broker serves as the messaging hub, through which all routing occurs. Coding the message broker is not necessary, since it is included with WebLogic. For a Pub-Sub message, a TopicConnection is opened. Similarly, P2P uses a QueueConnection.

    Within the connection, a TopicSession (Pub-Sub) or QueueSession (P2P) is established. The session allows the client to provide transactional characteristics and acknowledgement ability. If the session falls within the transaction, then rolling back the client application will automatically roll back the JMS message. Committing it will allow the container to begin processing that message. On the receiving side, enabling a transaction will result in an acknowledgement being sent only after the message processing has been committed.

    The acknowledgment mode determines the degree to which the message broker informs the client that its message has been successfully sent and received. Its options are:

  • DUPS_OK_ACKNOWLEDGE: Acknowledges when processor is free, minimizes work, can result in a duplicate message.
  • AUTO_ACKNOWLEDGE: Automatically acknowledges receipt after the MessageListener has completed processing.
  • CLIENT_ACKNOWLEDGE: Acknowledges receipt when the acknowledge() method on Message object is called.

    For a Pub-Sub application, the session then provides access to one or more TopicPublishers or TopicSubscribers, depending on sending or receiving intent. Each topic represents some logical grouping of messages that can be received. The TopicPublisher provides the ability to write to a topic and assign priority and message persistence. Message persistence refers to the ability of the message to survive system failure. Similarly, a P2P application provides access to QueueSender or QueueReceiver, which creates a queue.

    Once the topic or queue is accessed, the actual creation of the message is the only remaining step. Messages may be a variety of different types, including TextMessage, MapMessage (for HashMap sending), XMLMessage (WebLogic specific), or ObjectMessage.

    JMS messages have three distinct sections: header, properties, and the body. The header is used to determine routing and delivery information. Properties are optional and provide a degree of personalization to the message, as these properties can be reviewed by the message received and then acted upon prior to opening the message. The body is the message itself, which falls within a message-type structure.

    Sample JMS Sender
    A simple JMS program is presented in Listing 1. This program will allow another program to instantiate the JMSGateway class with an existing topic, and then call a sender method on the JMSGateway. A similar program for sending queue messages could also be created. The listing shows methods for sending simple text, but additional methods for sending other types like a HashMap or serializable Object could easily be added. It should be noted that this class is meant for the developer to become familiar with sending JMS messages, and not for direct production release.

    On line 15, a topic name is passed into the constructor to allow the calling class to define the topic. The topic must be set up within the WebLogic domain. Within the constructor (line 23), a JNDI lookup for ConnectionFactory generates the connection to a JMS server, in this case my local WebLogic server. The connection factory is used to generate the connection between the client and server (line 25) using createTopicConnection. The connection is created in "stopped" mode - while stopped, the connection can transmit messages but cannot send them. After the session and topic have been successfully created, the connection is started (line 32).

    From the gatewayConnection, the gatewaySession (line 27) that sends messages through the connection is created. Each session remains a single threaded context and retains messages until acknowledged (or conditions are met). The first parameter identifies the transaction level of the session. If transacted, the session will buffer messages until the client issues a commit or rollback. The second parameter represents the acknowledgeMode (if not transacted), which was detailed earlier.

    After the session has been created, the topic JNDI name is looked up (line 29) and that topic is passed to a method on the session to create a TopicPublisher (line 31). The connection is started (line 32), and the session is now ready to process a message.

    The client accessing this class should then call the sendTextMessage method (line 35) with the text message to be sent as the parameter. The other message types supported by WebLogic 7.0 are the StreamMessage, MapMessage, TextMessage, ObjectMessage, BytesMessage, and XMLMessage. This method could also be expanded to allow for the setting of priority or other header type information.

    When the message processing has been completed, the close method (line 41) should be called. This releases local resources from the connection.

    WebLogic 7.0 JMS Setup
    The next step is to set up JMS within WebLogic. Luckily, WebLogic's admin console is fairly straightforward.
    1.   After bringing up the console, choose the JMS Service configuration from the menu on the left.
    2.   Choose Connection Factories to create the required ConnectionFactory for the JMSGateway class. Select the "Configure a new JMS Connection Factory..." option.
    3.   You will see a page with three tabs (see Figure 1). On the first tab, "Configuration," fill out the JNDI name with "weblogic.jms.testJMSFactory". The other values can be set as desired. Press the "Apply" button when you are finished. On the second tab, "Targets," select your test server. Select "Apply" and you should be able to view your ConnectionFactory on the selection menu.
    4.   You must next create a JMS server. Select the Servers folder from the JMS list. Select "Configure a new JMSServer...". Update the Configuration and Targets with the name of your JMS server and target server.
    5.   Select the "Configure Destinations" link from the bottom of the Configuration tab. Select "Configure a new JMSTopic..." and name the topic. Provide the JNDI name with whatever your test program passes to the JMSGateway. Leave the other values with defaults or update as you experiment.
    6.   That's it. Other options can be created as needed or as your JMS learning dictates.

    A Sample Message-Driven Bean
    Finally, a reader is needed for the text message being sent. The newest EJB, a message-driven bean, will be used (see Listing 2). A message-driven bean (MDB) defines a specific destination (topic or queue) in the deployment descriptor it is associated with. When that destination is written to, the container directs that message to an instance of the MDB. MDBs do not have home or remote interfaces, and exist as stateless services. They cannot be called directly, and do not return values or pass exceptions.

    Because MDBs were designed for the purpose of accessing JMS Destinations, creating them is a snap. The SampleReceiverBean is a complete MDB that will take a TextMessage and print it out. In reality, you would want the MDB to kick off a real business process. The only method that involved any coding is the onMessage method (line 8). The onMessage method is where you would add your processing logic, keeping in mind that any reuse dictates that that logic occurs outside of the MDB.

    Deployment descriptors must be set up. A sample ejb-jar (see Listing 3)and weblogic-ejb-jar (see Listing 4) are provided as reference, but setup should be as your deployment descriptors process dictates. Key values to keep in mind are acknowledge mode, and destination-type (topic or queue) in the ejb-jar and destination-jndi-name (topic or queue jndi name) in the weblogic-ejb-jar. Remember to match the key values that you set up in the JMS server.

    Summary
    This brief synopsis is only an introduction, and does not provide all of the JMS information needed to perform detailed processing. I recommend you try the example and then perform some additional research to learn more. The following sites should be helpful:

  • Programming WebLogic JMS: http://e-docs.bea.com/wls/ docs70/jms/index.html
  • Designing Message Beans from BEA for 7.0: http://e-docs.bea.com/wls/docs70/ ejb/message_beans.html#1050867
  • Implementing JMS-based Web Services: http://edocs.bea.com/wls/docs70/ webserv/jms.html
  • O'Reilly summary article: www.onjava.com/pub/a/onjava/2001/ 05/22/ejb_msg.html?page=1
  • More Stories By Jason Snyder

    Jason Snyder is an architectural expert for CSC Consulting in Boston, and has served as the lead architect for several J2EE development projects. He has over 10 years of experience in software development, OO design, and application architecture.

    Comments (0)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    IoT & Smart Cities Stories
    DXWorldEXPO LLC announced today that Telecom Reseller has been named "Media Sponsor" of CloudEXPO | DXWorldEXPO 2018 New York, which will take place on November 11-13, 2018 in New York City, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
    To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...
    The deluge of IoT sensor data collected from connected devices and the powerful AI required to make that data actionable are giving rise to a hybrid ecosystem in which cloud, on-prem and edge processes become interweaved. Attendees will learn how emerging composable infrastructure solutions deliver the adaptive architecture needed to manage this new data reality. Machine learning algorithms can better anticipate data storms and automate resources to support surges, including fully scalable GPU-c...
    A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to great conferences, helping you discover new conferences and increase your return on investment.
    Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
    We are seeing a major migration of enterprises applications to the cloud. As cloud and business use of real time applications accelerate, legacy networks are no longer able to architecturally support cloud adoption and deliver the performance and security required by highly distributed enterprises. These outdated solutions have become more costly and complicated to implement, install, manage, and maintain.SD-WAN offers unlimited capabilities for accessing the benefits of the cloud and Internet. ...
    Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
    SYS-CON Events announced today that Silicon India has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Published in Silicon Valley, Silicon India magazine is the premiere platform for CIOs to discuss their innovative enterprise solutions and allows IT vendors to learn about new solutions that can help grow their business.
    DXWorldEXPO LLC announced today that "IoT Now" was named media sponsor of CloudEXPO | DXWorldEXPO 2018 New York, which will take place on November 11-13, 2018 in New York City, NY. IoT Now explores the evolving opportunities and challenges facing CSPs, and it passes on some lessons learned from those who have taken the first steps in next-gen IoT services.
    SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...