Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Implement and access stateful Web services using WebSphere Studio, Part 5

Notify changes in properties of WS-Resource

Hidayatullah Shaikh (hshaikh@us.ibm.com), Senior Software Engineer, IBM
Hidayatullah H. Shaikh is a Senior Software Engineer on the IBM Software Group's On Demand Architecture and Development Team. His areas of interest and expertise include business process modeling and integration, Service-Oriented Architecture, grid computing, e-commerce, enterprise Java, and database management systems. You can contact Hidayatullah at hshaikh@us.ibm.com.
Lalitha Kamesam (lpk@us.ibm.com), Advisory Software Engineer, IBM
Lalitha P. Kamesam is an Advisory Software Engineer on the IBM Software Group’s On Demand Architecture and Development Team. Her areas of interest and expertise include e-commerce applications, database management systems, and Web services. You can contact Lalitha at lpk@us.ibm.com.
Mark Hunsinger (hunsinge@us.ibm.com), Manager, On Demand Development and Incubation, IBM
Mark Hunsinger is the manager of the IBM On Demand Architecture and Development team. Mark has many years of experience in programming and in managing complex Web-based development projects. In his role as the lead of the On Demand Architecture and Development, Mark is responsible for evaluating, prioritizing, and ultimately developing incubators and proofs of concept to fill voids in IBM's On Demand portfolio. You can contact Mark at hunsinge@us.ibm.com.

Summary:  The Web Services Resource Framework (see Resources) proposes a model for accessing state using Web services. The WS-Resource Properties specification (see Resources) defines how you can query and change the data associated with a stateful resource using Web services technologies. This article shows how changes in the values of resource properties of a WS-Resource can be sent to a client that has subscribed to it in an IBM® WebSphere® Application Server environment using WebSphere Studio Application Developer V5.1.1.

Date:  08 Sep 2004
Level:  Advanced

Activity:  4513 views
Comments:  

Introduction

The Web Services Resource Framework (WS-Resource) defines a family of specifications for accessing stateful resources using Web services. Web services, by their nature, typically do not maintain state information during their interactions. However, their interfaces must frequently allow for the manipulation of state, that is, data values that persist across, and evolve as a result of, multiple Web service interactions. In WS-Resource, state is modeled as stateful resources and the relationship between Web services is codified in terms of an implied resource pattern.

The WS-Resource Properties specification defines how you can query and change the data associated with a stateful resource using Web services technologies. This allows a standard means by which clients can access data associated with a WS-Resource. The declaration of the WS-Resource’s properties represents a projection of, or a view on, the WS-Resource’s state. Any change in the value of the property of a WS-Resource can trigger notification messages. This is typically done using WS-Notification. The WS-Notification family of documents includes a white paper, "Publish-Subscribe Notification for Web Services" as well as three normative specifications: WS-BaseNotification, WS-BrokeredNotification, and WS-Topics (see Resources) .

This part of the series modifies the Calculator sample to illustrate the following:

  1. In lieu of support for WS-Notification in WebSphere, you can use JMS instead.
  2. A topic can be created with the JMS broker for the resource property of a WS-Resource.
  3. A client can subscribe to changes in the resource properties of a WS-Resource.
  4. A change in the state of the WS-Resource results in a notification message being produced by the Web service which is then sent to the broker and subsequently to all clients that have subscribed to the state changes.

Intended audience

You should have a basic understanding of J2EE technology, Web services, JMS, and WebSphere Application Server V5.1. To familiarize yourself with these technologies, please consult the Resources section of this paper for links to good introductory material. You can also consult additional resources available at IBM developerWorks, and read the first four articles in this series to become familiar with the WS-Resource Framework concepts (see Resources) .

Contents and requirements for the sample code

The samples referenced in this article were created with WebSphere Studio Application Developer V5.1.1 GM Version (build ID 20031120-1915, hereafter, Application Developer). They were unit tested using the WebSphere Application Server V5.1 (5.1.0.3 cumulative fixpack applied) Built-in Test Environment and WebSphere Embedded Messaging (included with Application Developer V5.1.1). For more information on downloading these prerequisites, refer to the Resources section of this article. The WSDLs in the samples have been configured to use the tcpmon utility that comes with Apache Axis for monitoring the exchanged SOAP messages. Configure the tcpmon utility to listen on port 81 (listenPort) and forward the requests to a target port of 9080 (targetPort) on localhost. For more information on tcpmon refer to the Resources section of this article.

The file ws-statefulws5code.zip contains the code samples that accompany this article. You can download the file by clicking on the Code icon at the top or bottom of this article. The zip file contains the following files:

  • WASv5WSAExtensions.jar: A JAR file containing the utility classes that WebSphere Application Server V5.1 needs in order to create and access WS-Addressing message information headers in SOAP messages. Helper classes for manipulating WS-Addressing endpoint references (EPRs) are also included. These classes may be configured for use with WebSphere Studio applications.
  • WASvsWSAExtensions-javadoc.zip:The javadoc for the utility classes.
  • CalculatorService.ear: A sample stateful operating system service.
  • WASv5WSNTExtensions.jar: A JAR file containing the utility classes for subscribers and publishers.
  • CalculatorServiceClientJava.jar: A JAR file containing the client to invoke the Calculator Web service.

JMS publish-subscribe

JMS defines two modes of messaging: point-to-point (P2P) and publish-subscribe (pub-sub). In P2P mode, a message producer sends a message to a specific message consumer through a queue, whereas pub-sub is intended for the one-to-many or many-to-many broadcast of messages. This article uses the pub-sub model. In the pub-sub model, a messaging client (producer) sends a message through a virtual channel called topic to messaging clients (consumers) that subscribe to this topic. Every consumer receives a copy of every message automatically without having to request or poll the topic for new messages.

Notification messages are asynchronous in nature. To receive messages asynchronously as they are delivered to the message consumer, the client program needs to create a message listener that implements the MessageListener interface and then register it with the MessageConsumer object. The example in this article uses this approach to register listeners dynamically.

For more information refer to the JMS specification (see Resources).


The Calculator sample

The Calculator sample, introduced in Part 1 of this series, provided a simple Calculator service to client programs through a standard WSDL V1.1 interface. The service interface allowed clients to create instances of a calculator and subsequently add and subtract from the calculator total. Calculator instances are treated as WS-Resources in the sample. Also note that the Calculator Web service implementation used existing J2EE best practices with the service interface implemented as a stateless session bean and the state maintained in a CMP entity bean.

This article takes you through the steps to enable the Calculator service to be subscribed to for any changes in its state (value of total) and for it to send notification messages upon the changes. Specifically, you will:

  • Be introduced to a couple of helper classes, SubscriberHelper and PublisherHelper.
  • Add a JMS message listener, CalculatorListenerBean, which receives the notification messages.
  • Add a J2EE client application that can be used to change the value of total. This code simulates a component that changes the state of the Calculator WS-Resource.
  • Add an additional method, setTotalWithJMSPub, to the CalculatorStateBean. This J2EE client application calls this method to change the value of total and send a notification message.

The instructions in this article help you modify the sample code in the first part of this series. When you are done with these modifications, your code should look like the code in ws-statefulws5code.zip (Click the Code icon at the top or bottom of this article).

Look at the modified flow of the Calculator sample Figure 1 shows.


Figure 1. Calculator service flow
Figure 1. Calculator service flow

Step 1 uses the CalculatorServiceClient Java application instead of the CalculatorTestClient.jsp (we will discuss the reason for this in a later section).

Steps 2–3 are the same as before. The CalculatorServiceClient invokes the Calculator Web service which in turn creates the CalculatorState EJB and the primary key is returned in the EPR.

In Step 4 the CalculatorServiceClient invokes the SubscriberHelper class to subscribe to the topic for any change in the Calculator State.

In Steps 5-6, the SubscriberHelper class instantiates the CalculatorMessageListener to listen to any changes to the value of total for the Calculator resource instance, created in Step 3.

In Step 7, a back-end application changes the value of total for the Calculator resource instance, created in Step 3.

In Steps 8-9, the CalculatorStateBean updates the value of total and then invokes the PublisherHelper class to notify the subscribers that a change was made to the total. PublisherHelper class publishes a notification message on the JMS topic queue.

In Step 10, the CalculatorMessageListener receives the notification message.

In Step 11, the CalculatorMessageListener calls the Calculator service to get the current value of total.


SubscriberHelper

The SubscriberHelper provides a subscribe method that the WS-Resource client uses to register its interest in the change in the values of the resource properties of a particular WS-Resource instance. The subscribe method takes the following parameters as input:

  • ctx – a java naming context object
  • topic – a topic name
  • instanceID - instance identifier of the WS-Resource
  • messageListener – A message listener registered by the client


Listing 1. SubscriberHelper subscribe method implementation
001     public static void subscribe(Context ctx, String topic, String 
002     instanceID, MessageListener messageListener) {
003         ...
004     String connectionFactoryName = "jms/" + topic + "tcf";
005     String topicName = "jms/" + topic;
006     
007     try 
008     {
009     
010          ...
011     topicConnectionFactory = (TopicConnectionFactory) 
012                                   ctx.lookup(connectionFactoryName);
013          ...
014     topicConnection = topicConnectionFactory.createTopicConnection();
015          ...
016     topicConnection.start();
017     
018     boolean transacted = false;
019     topicSession = topicConnection.createTopicSession(
020     				transacted,
021     				Session.AUTO_ACKNOWLEDGE);
022          ...
023          _topic = (Topic) ctx.lookup(topicName);
024          ...
025          selector = new String("(instanceID = '" + instanceID + "')");
026     topicSubscriber = topicSession.createDurableSubscriber(_topic, 
027                                                               selector);
028          ...
029     topicSubscriber.setMessageListener(messageListener);
030     
031          ...
032     Thread.sleep(120000);
033          ...
034     	}
			

Look at the above code snippet in detail:

  1. In lines 11-16 you create a connection to the topic using the topic factory.
  2. In line 19 you start a session with the topic connection.
  3. In line 23 you do a JNDI lookup of the topic name.
  4. In line 25 you use the instance identifier of the WS-Resource to construct a JMS selector. A JMS message selector allows a client to specify, by message header, the messages it’s interested in. Only messages whose headers and properties match the selector are delivered.
  5. You then create a durable subscriber, in line 26, using the topic looked up in Step 4 and the selector.
  6. In line 29 you set the message listener in the subscriber created in Step 5.
  7. In line 32, you wait for the message listener to receive any updates to the topic total, with a wait time set for two minutes. This wait time has been introduced for running the sample, as it doesn't have a long running client.

PublisherHelper

The PublisherHelper provides a publish method that the WS-Resource uses to publish any change in the values of its resource properties. The publish method takes the following parameters as input:

  • ctx – a java naming context object
  • topic – a topic name
  • instanceID - instance identifier of the WS-Resource

Listing 2 shows the implementation of the publish method.


Listing 2. PublisherHelper publish method implementation
001     public static void publish(Context ctx, String topic, String 
002     instanceID) 
003     {
004       ...
005     String connectionFactoryName = "jms/" + topic + "tcf";
006     String topicName = "jms/" + topic;
007     
008     try
009     {
010          ...
011          topicConnectionFactory = (TopicConnectionFactory)              
012                                   ctx.lookup(connectionFactoryName);
013          ...
014     topicConnection =                      
015             topicConnectionFactory.createTopicConnection();
016          ...
017     topicSession =
018       topicConnection.createTopicSession(
019     	transacted,
020     	Session.AUTO_ACKNOWLEDGE);
021          ...
022     
023          _topic = (Topic) ctx.lookup(topicName);
024          ...
025     topicPublisher = topicSession.createPublisher(_topic);
026          ...
027     String outString = "Value of " + topic + " has been Changed";
028          ...
029     TextMessage outMessage=topicSession.createTextMessage(outString);
030          ...
031     outMessage.setStringProperty("instanceID", instanceID);
032     topicPublisher.publish(outMessage);
033          ...
034   }
			

Look at the above code snippet in detail:

  1. In lines 11-15 you create a connection to the topic using the topic factory.
  2. In line 17 you start a session with the topic connection.
  3. In lines 23-25 you do a JNDI lookup of the topic and then you create a topic publisher using this topic.
  4. In line 27 you construct the message to be published using the topic name. The topic name is the same as the WS-Resource property name.
  5. In line 29 you use the message to create a JMS TextMessage.
  6. In line 31 it set a JMS property called instanceID with the instance id received when the publish method gets called. This enables the selector logic defined in the SubscriberHelper to work and allows clients to selectively receive the notification messages.
  7. In line 32 you use the topic publisher to publish the message to the topic queue.

Modifying the CalculatorStateBean

The CalculatorStateBean is modified to add a new method, setTotalWithJMSPub, which updates the value of total. It also publishes a message stating that the value of total has changed by calling the publish method of the PublisherHelper class and passing the following parameters:

  1. A new Java naming context object
  2. The topic queue name, which is the same as the resource property name (which is total in this sample)
  3. The primary key of the CalculatorState entity bean (This is the instanceID of the Calculator resource.)

Listing 3 shows the relevant portion of the code. For details refer to the CalculatorStateBean.java included in CalculatorService.ear.


Listing 3. CalculatorStateBean’s setTotalWithJMSPub method implementation
			...
import com.ibm.samples.wsnt.utils.PublisherHelper;

public abstract class CalculatorStateBean implements javax.ejb.EntityBean {
private javax.ejb.EntityContext myEntityCtx;

..

public  void setTotalWithJMSPub(float total) {
   ...
   this.setTotal(total);
   ...
   try 
   {
      PublisherHelper.publish(new InitialContext(),                            
                    "com/ibm/samples/calculator/CalculatorState/total",
                    this.getName());
   
    } catch (NamingException e) {
	e.printStackTrace();
...
			


J2EE client application

A new J2EE client application, CalculatorBackendApplicationClient, is created to change the value of the total. This application takes the primary key of the CalculatorStateBean and a new value of total as input and invokes setTotalWithJMSPub method on the CalculatorStateBean. For details refer to the CalculatorServiceBackend.java file included in the CalculatorService.ear.


CalculatorListenerBean

As mentioned before, one of the input parameters of the subscribe method of the SubscriberHelper is a MessageListener. For this example, you have defined a CalculatorListenerBean class that implements the JMS MessageListener class. As messages arrive for the JMS consumer, the JMS provider delivers them by calling the listener’s onMessage method. Listing 4 shows the constructor and onMessage method implementation of the CalculatorListenerBean. In the example, the onMethod is called whenever the value of total changes. In the onMessage method, the Calculator service proxy gets the current value of the total.


Listing 4. CalculatorListenerBean onMethod implementation.
			public class CalculatorListenerBean implements MessageListener {
...
public CalculatorListenerBean(CalculatorService calculatorService)
{
	this.calculatorService = calculatorService;
}

public void onMessage(Message msg) {
	try 
      {
		String instanceId = msg.getStringProperty("instanceID");
		String message = ((TextMessage) msg).getText();
            ...

	     if (message.equals("Value of total has been Changed")) 
	     {
			float total = calculatorService.getTotalEPR();
                  ...
	     }

	} catch (JMSException e) {
        ...

	}

			


Modifying the client to subscribe to the topic queue

In this section you see how you must modify the client code to support subscribing to notification messages using the SubscriberHelper. The SubscriberHelper uses the setMessageListener method to dynamically register message listeners. However, because of context, Application Server does not permit setMessageListener to be called from within the Web or an EJB container. When EJB and servlet methods are invoked, the container keeps context, such as the current transaction and security principal, associated with the thread. When a JMS provider invokes a MessageListener, the application server can't intercept the call and add the appropriate context. The sample in this article circumvents this problem by converting the CalculatorTestExecute JSP to a stand-alone Java application, CalculatorServiceClient. The logic for creating the Calculator WS-Resource remains the same as before. Listing 5 shows the additions made to the logic to subscribe for notification.


Listing 5. Logic to subscribe to the topic queue
001     public class CalculatorServiceClient
002     {
003         ...
004      
005     public static void main(String[] args) 
006     {
007             String acctName = args[0];
008             float add = (new Float(args[1])).floatValue();
009             float sub = (new Float(args[2])).floatValue();
010     
011     	try
012             {
013     		...
014     
015     		CalculatorListenerBean myListener
016                         = new CalculatorListenerBean(calculatorService);
017                     Properties env = new Properties()
018                 env.setProperty(Context.INITIAL_CONTEXT_FACTORY,
019     			"com.ibm.websphere.naming.WsnInitialContextFactory");
020                 env.setProperty(Context.PROVIDER_URL,
021                       "iiop://localhost:2809");
022                 ...
023                 Context ctx = new InitialContext(env);
024                 ...
025                 SubscriberHelper.subscribe(ctx,
026                         "com/ibm/samples/calculator/CalculatorState/total", 
027                         instanceID, 
028                         myListener);
029                 ...
030     	}
031     
032     }
			

Look at the above code snippet in detail:

  1. In lines 15-16 you instantiate the CalculatorListenerBean and pass it proxy to the Calculator service.
  2. In lines 17-23 you create a java naming context object.
  3. In lines 25-28 you call the subscribe method of the SubscriberHelper, passing it the following:
    1. Context object created in Step 2
    2. The name of the resource property which is the same as the topic name
    3. Instance identifier of the calculator WS-Resource
    4. The message listener instantiated in Step 1

Server configuration changes to enable JMS

In this section you learn the steps needed to enable and configure JMS in your WebSphere Application Server 5.1 Test Environment to run the Calculator sample:

  1. Create a new server WebSphere Version 5.1 Test Environment. In the J2EE perspective, switch to the J2EE Hierarchy view. Right-click on Servers and select New > Server and Server Configuration to open the server creation wizard, as shown in Step 4 below. Specify the Server Name as WebSphere Version 5.1 Test Environment and select a Server type of WebSphere version 5.1 > Test Environment. Click Finish to complete the creation of the test server.
  2. Edit the JMS provider settings. Double-click WebSphere Version 5.1 Test Environment in the J2EE Hierarchy to open its editor and switch to the JMS tab to display the WebSphere JMS Provider Options panel. Verify that the Server Settings are being altered. At the top of the panel, verify that Server Settings is expanded and that both Cell Settings and Node Settings are not. Change JMS Provider setting to use Embedded Messaging.
  3. Add a WAS Topic Connection Factory. In the Server Settings section of the WebSphere JMS Provider Options panel, move down into the JMS Connection Factories section to the WASTopicConnectionFactories entries table and click Add. In the resulting wizard, specify the following information:
    1. Name: com.ibm.samples.calculator.CalculatorState.totaltcf
    2. JNDI Name: jms/com/ibm/samples/calculator/CalculatorState/totaltcf
    3. Port: QUEUED
    4. Node: localhost
    5. Server Name: server1
    6. Purge Policy: EntirePool
  4. Add a WAS Topic. Move down to the WebSphere Application Server Topic entries table and click Add. In the resulting wizard, specify the following information:
    1. Name: com.ibm.samples.calculator.CalculatorState.total
    2. JNDI Name: jms/com/ibm/samples/calculator/CalculatorState/total
    3. Topic: com.ibm.samples.calculator.CalculatorState.total
  5. Save the updated server configuration and start the server.

Set up the Calculator Web service

This section describes how to create a workspace in Application Developer that contains the CalculatorService sample and how to deploy it in the built-in WebSphere Application Server Test Environment.

  1. Create a new workspace called CalculatorService in Application Developer.
  2. Enable the Server Targeting function in Application Developer. Do this by selecting Window>Preferences>J2EE>Enable server targeting support.
  3. Import the CalculatorService.ear file into your workspace. Make sure you select the WASv5WSNTExtensions.jar to get the project created instead of the jar file. Make sure that WebSphere Version 5.1 Test Environment (that you configured earlier) is selected as the target server. This creates the following projects:
    1. An Enterprise Application Project (J2EE 1.3) called CalculatorService.
    2. An Enterprise JavaBeans project called CalculatorServiceEJB, which contains the implementation of the CalculatorServiceEJB components
    3. A Dynamic Web Project called CalculatorServiceWeb, which contains the Web Services router project.
    4. A WebSphere Application Client project called CalculatorBackendApplicationClient, which contains the logic to change the total value of the WS instanceID.
    5. A Java project called WASv5WSNTExtensions, which contains the implementation of Publisher and SubscriberHelper classes.
  4. Change to Java Perspective and create a new java project with the name CalculatorServiceClientJava and import the CalculatorServiceClientJava.jar file into your workspace by selecting import > zip file. Select the CalculatorServiceClientJava.jar file from your zip file and select CalculatorServiceClientJava project for into folder.
  5. Add the CalculatorService Project to the WebSphere Test Environment. Right-click WebSphere Version 5.1 Test Environment in the J2EE Hierarchy and select the Add and Remove projects. Add the CalculatorService project and click Finish.
  6. Add the JDBC Resources. Double-click WebSphere Version 5.1 Test Environment in the J2EE Hierarchy to open its editor and switch to the Security. Create the JAAS Authentication Entries.
  7. Modify the JDBC Provider for the DB2 JDBC Provider to use COM.ibm.db2.jdbc.DB2XADataSource for the Implementation Class name.
  8. Assign the JNDI name jdbc/calculator to the data source.

This completes the deployment of the EAR and the JAR files included with this article.


Running the CalculatorServiceJavaClient

This section describes the steps to configure and run the CalculatorServiceJavaClient application.

  1. Create and configure a new launch configuration. In the J2EE perspective, open the Launch Configuration wizard by selecting Run>Run. In the Launch Configurations list, select Java Application and click New. Name this new configuration CalculatorServiceClient, use the project CalculatorServiceClientJava and the main class com.ibm.samples.calculator.CalculatorServiceClient and click Apply. The wizard should now look like Figure 2:

Figure 2. Launch configuration for CalculatorServiceClient application
Figure 2: Launch configuration for CalculatorServiceClient application
  1. Update the Classpath. Switch to the Classpath tab and add the WebSphere Test Environment Runtime Files properties directory. In this setup this is C:\IBM\WebSphere Studio\runtimes\base_51\properties.
  2. Ensure that the JRE tab selection is Default (WebSphere V5.1 JRE).
  3. In the Arguments tab, enter the three arguments: Hello 10 5. Effectively you are trying to create a Calculator WS-Resource with account name Hello, and then adding 10 to the total and then subtracting 5 from it.
  4. Select Apply.
  5. Make sure that the WebSphere Application Server Test Environment is running.
  6. Click Run at the foot of the Launch Configuration wizard.
  7. Listing 6 shows the relevant section of the output console. The CalculatorServiceClient application is now running and waiting for two minutes for a message to be published to the topic to which it is subscribed. You can publish such a message by running the CalculatorBackendApplicationClient. Remember the instanceID, 1092325353206, for this run, shown in line 9 of listing 6. You need this later when you run the CalculatorBackendApplicationClient application.


Listing 6. CalculatorServiceClient console messages
001     
002     CalculatorServiceClient: Creating calculator for Account = Hello
003     CalculatorServiceClient: Getting an Initial Context..
004     CalcualatorServiceClient: Giving Control to SubscriberHelper
005     ...
006     
007     SubscriberHelper - Subscribe the message : 
008     topic://com.ibm.samples.calculator.CalculatorState.total?brokerVersion=1
009     SubscriberHelper -– Sleeping for 2 minutes. InstanceId = 1092325353206
			


Running the CalculatorBackendApplicationClient

This section describes the steps to configure and run the CalculatorBackendApplicationClient application.

  1. Create and configure a new launch configuration. In the J2EE perspective, open the Launch Configuration wizard by selecting Run>Run. In the Launch Configurations list, select WebSphere V5 Application Client and click New. Name this new configuration CalculatorBackendApplicationClient, and using drop-down list, specify an Enterprise Application of CalculatorService and the Application Client CalculatorBackendApplicationClient and click Apply. The wizard should now look like Figure 3.

Figure 3. Launch configuration for CalculatorBackendApplicationClient
Figure 3: Launch configuration for CalculatorBackendApplicationClient
  1. In the Arguments tab, enter the Calculator WS Instance identifier of the calculator that you created in Step 8 of running CalculatorServiceClient with the total value to be changed. For this run it is, 1092325353206 350. Effectively you are trying to set the value of the total for the Calculator resource with instance identifier equal to 1092325353206 with a new value of 350.
  2. Select Apply.
  3. Make sure that the WebSphere Application Server Test Environment is running.
  4. Click Run at the foot of the Launch Configuration wizard.
  5. Listing 7 shows the relevant section of the output console. Line 10 shows application parameters. It calls setTotalWithJMSPub method in the CalculatorState EJB to update the total for the instanceID as in Line 20.


Listing 7. Console output from the client application
						
001     IBM WebSphere Application Server, Release 5.1 
002     J2EE Application Client Tool 
003     Copyright IBM Corp., 1997-2003
004     ..
005     WSCL0001I: Command line, property file, and system property 
006     resolved to:         File to launch          = 
007     C:/CalculatorService/CalculatorService
008     ..
009             Soap Connector Port     = null
010             Application Parameters  = 1092325353206 350 
011     ..
012     WSCL0013I: Initializing the J2EE Application Client Environment.
013     ..
014     WSCL0035I: Initialization of the J2EE Application Client Environment 
015     has completed.
016     WSCL0014I: Invoking the Application Client class 
017     com.ibm.samples.calculator.CalculatorServiceBackend
018     CalculatorServiceBackend: Changing Total Information for instance id 
019     1092325353206 from 10.0 to 350.0
020     CalculatorServiceBackend: Call setTotalWithJMSPub
021     CalculatorServiceBackend: Successfully Updated the total
							


  1. Now look at the WebSphere Test Environment Console. Listing 8 shows the relevant portion, specifically the CalculatorStateBean invocation and PublisherHelper publishing the message to the queue.
    • Lines 4-5 show that the PublisherHelper has created a Text message.
    • Lines 6-7 show the topic name to which this message will be published.


Listing 8. PublisherHelper publishing the message to the topic
001     CalculatorStateBean : setTotalWithJMSPub got control now
002     PublisherHelper: Getting an TopicConnectionFactory...
003     ..
004     PublisherHelper - Creating a TextMessage: Value of 
005     com/ibm/samples/calculator/CalculatorState/total has been Changed
006     PublisherHelper - Publish the message : 
007     topic://com.ibm.samples.calculator.CalculatorState.total?brokerVersion=1 
						


  1. If the message was successfully published, the CalculatorListenerBean that CalculatorServiceClient was waiting for should have received it. To verify, switch to CalculatorServiceClient Console View. Its output will display in the console view. Listing 9 shows the relevant portion of the output. The CalculatorListenerBean receives the message, and it prints the message along with the instanceID and the new value of total.


Listing 9. CalculatorServiceClient receives the message after the total changed
001     ..
002     CalculatorListenerBean: onMessage() called with message =  Value of 
003     com/ibm/samples/calculator/CalculatorState/total has been Changed
004     CalculatorListenerBean: Instance Id = 1092325353206
005     CalculatorListenerBean: New Total Value = 350.0
006     ...
007     SubscriberHelper: Closing the TopicSession and TopicConnection now.
008     CalculatorServiceClient:  Exiting
009     ...
						

This illustrates how Calculator resource can be subscribed to, for any changes in its state, and for it to send notification messages upon the changes.


Conclusion

This article discussed how to modify our Calculator service sample to establish it as a subscription service for notification of any changes in its state (the value of total). It showed how to modify the Calculator service sample for it to send notification messages when changes in the state occur. It discussed how to:

  • establish a JMS message listener
  • set up a topic to be published upon creation of a new WS-Resource instance
  • receive changes in the resource properties of a WS-Resource from a client
  • initiate a change in state of the WS-Resource that results in the Web service producing a notification message which it then sends to the broker

While the example of a Calculator service itself is somewhat trivial, the hope through this series of articles is that you have increased your understanding of some of the WS-* specifications and are enabled to more quickly get your applications up and running utilizing this support. For further information on these specifications refer to the Resources section of this article and the other articles in this series.



Download

NameSizeDownload method
ws-statefulws5code.zip HTTP

Information about download methods


Resources

About the authors

Hidayatullah H. Shaikh is a Senior Software Engineer on the IBM Software Group's On Demand Architecture and Development Team. His areas of interest and expertise include business process modeling and integration, Service-Oriented Architecture, grid computing, e-commerce, enterprise Java, and database management systems. You can contact Hidayatullah at hshaikh@us.ibm.com.

Lalitha P. Kamesam is an Advisory Software Engineer on the IBM Software Group’s On Demand Architecture and Development Team. Her areas of interest and expertise include e-commerce applications, database management systems, and Web services. You can contact Lalitha at lpk@us.ibm.com.

Mark Hunsinger is the manager of the IBM On Demand Architecture and Development team. Mark has many years of experience in programming and in managing complex Web-based development projects. In his role as the lead of the On Demand Architecture and Development, Mark is responsible for evaluating, prioritizing, and ultimately developing incubators and proofs of concept to fill voids in IBM's On Demand portfolio. You can contact Mark at hunsinge@us.ibm.com.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=SOA and Web services
ArticleID=15094
ArticleTitle=Implement and access stateful Web services using WebSphere Studio, Part 5
publish-date=09082004
author1-email=hshaikh@us.ibm.com
author1-email-cc=
author2-email=lpk@us.ibm.com
author2-email-cc=
author3-email=hunsinge@us.ibm.com
author3-email-cc=Copy email address

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

For articles in technology zones (such as Java technology, Linux, Open source, XML), Popular tags shows the top tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), Popular tags shows the top tags for just that product zone.

For articles in technology zones (such as Java technology, Linux, Open source, XML), My tags shows your tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), My tags shows your tags for just that product zone.

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Try IBM PureSystems. No charge.

Special offers