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
    In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
    Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
    When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
    Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
    Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
    If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
    Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
    Chris Matthieu is the President & CEO of Computes, inc. He brings 30 years of experience in development and launches of disruptive technologies to create new market opportunities as well as enhance enterprise product portfolios with emerging technologies. His most recent venture was Octoblu, a cross-protocol Internet of Things (IoT) mesh network platform, acquired by Citrix. Prior to co-founding Octoblu, Chris was founder of Nodester, an open-source Node.JS PaaS which was acquired by AppFog and ...
    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...
    Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...