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.

    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.

    @ThingsExpo Stories
    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...
    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.
    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.
    The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
    Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.
    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.
    As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
    Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
    The IoT Will Grow: In what might be the most obvious prediction of the decade, the IoT will continue to expand next year, with more and more devices coming online every single day. What isn’t so obvious about this prediction: where that growth will occur. The retail, healthcare, and industrial/supply chain industries will likely see the greatest growth. Forrester Research has predicted the IoT will become “the backbone” of customer value as it continues to grow. It is no surprise that retail is ...
    Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
    The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
    DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of bus...
    With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
    DXWorldEXPO LLC announced today that "Miami Blockchain Event by FinTechEXPO" has announced that its Call for Papers is now open. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Financial enterprises in New York City, London, Singapore, and other world financial capitals are embracing a new generation of smart, automated FinTech that eliminates many cumbersome, slow, and expe...
    Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
    DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
    DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by FinTechEXPO. ICOHOLDER give you detailed information and help the community to invest in the trusty projects. Miami Blockchain Event by FinTechEXPO has opened its Call for Papers. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Miami Blockchain Event by FinTechEXPO also offers s...
    DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
    Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
    Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.