Working with subscriptions in WebSphere Service Registry and Repository V8

This article shows you how to use subscription objects and the notification service in WebSphere Service Registry and Repository. A sample application shows you how to cycle a subscription object through its Create, Read, Update, and Delete (CRUD) life cycle.

Share:

Stephen Rea (stephen_rea@uk.ibm.com), Software Engineer, WebSphere Service Registry and Repository Development team, IBM

Photo of Stephen ReaStephen Rea is a Software Engineer on the WebSphere Service Registry and Repository team at the IBM Software Lab in Hursley, United Kingdom. His development expertise includes modeling, messaging, parsing, and consumability. Since joining the Lab as an experienced hire in 1999, Stephen has worked on numerous Websphere products, including WebSphere MQ, WebSphere Message Broker and WebSphere Service Registry and Repository. You can contact Stephen at stephen_rea@uk.ibm.com.



06 February 2013

Also available in Chinese

Introduction

This article shows you how to use subscription objects and the notification service in IBM® WebSphere® Service Registry and Repository (hereafter called Service Registry). You will interact with a sample application in order to cycle a subscription object through its Create, Read, Update, and Delete (CRUD) life cycle. You can also use the application to cycle a generic object, which is used as the subscription's target entity, through its life cycle. The article demonstrates the following capabilities:

  • How you can use the public Representational State Transfer (REST) based API in Service Registry to create and manipulate content in its repository. You can affect the content of Service Registry using the REST distributed application architecture, which uses lightweight clients that do not support EJBs and web services, to perform these tasks by using HTTP requests.
  • How to cycle objects through their standard life cycle phases within Service Registry via the REST API.
  • How, by targeting a subscription object at a generic object, you can trigger notification events within Service Registry when a target object is transitioned through its life cycle states.

Subscription object CRUD life cycle

Service Registry enables clients to subscribe to events related to changes applied to entities within the repository resulting from direct interaction with it. If the content of an object or its metadata is altered, these changes can be monitored by clients by creating one or more subscription objects. This section explores the life cycle of subscription objects, demonstrating how they may be:

  • Created (registered) within Service Registry to subscribe to specific content activity.
  • Read (retrieved) from Service Registry to confirm the existence and correctness of property settings.
  • Updated (modified) within Service Registry to alter how events are packaged (aggregated) to subscribers.
  • Deleted (removed) from Service Registry in order to de-register interest in specific events tied to the target entity set.

A sample subscription object with associated properties and subscribed operations (no target classifications or subscribed transitions), will be transitioned through its life cycle using a sample Java® application called CRUDApp and interfacing with the Service Registry REST API. The application reads a pre-supplied file containing well-defined XML that describes the subscription object's properties and subscribed operations. This information forms the body of an HTTP POST request, one of several methods (verbs) available on the REST API, and used by the application to manipulate the subscription object within Service Registry. The sample application in this article uses the same HTTP URLs that can be used by any web browser.

In addition to cycling a subscription object through its CRUD life cycle, the sample application uses the same techniques to alternately cycle a GenericObject through its life cycle. Again a predefined XML formatted file is provided that describes the generic object to be created. The generic object is used as the target entity in the demonstration and forms the only entity in the target set, and is described by the subscription object.

The subscription object registers an interest in the subscribed operations create, update and delete when applied to the generic object. Hence by using the sample application to cycle the generic object through its CRUD life cycle stages, the registered subscription object should provide three notifications (one for each event matching a subscribed operation) via the subscription notification service.

Sample application requirements

  • Disable Service Registry security . The sample application demonstrates the simplicity of using the Service Registry REST API, but not the intricacies of encrypted HTTP communication. To connect to Service Registry with security enabled, you can use the sample application and apply common programming practices.
  • Ensure that Service Registry JMS notification is enabled. If you want to use the subscription notification service, you must ensure that JMS notification is enabled, because the event notification messages that are processed by the service are sent to a JMS queue. For more information, see Ensuring that JMS notification is enabled in the Service Registry information center.
  • Ensure that the Service Registry subscription notifier scheduler is enabled. To activate the subscription notification service, you must also enable a Service Registry scheduled task. When enabled, the task runs periodically to check for changes to subscribed target objects. Matching subscriptions notify the subscription's end points by using a subscription notifier of the specified type, such as an HTTP POST subscription notifier.

The default profile contains a subscription notifier plug-in scheduler entry called SubscriptionNotifierPluginScheduler. It defines a subscription notifier plug-in scheduled task that is turned off by default. To use the subscription notification service, you must enable the scheduled task. For more information, see Enabling the subscription notifier scheduler in the Service Registry information center. For this sample demonstration, set the value of the <intervalGranularity> element, which controls the frequency at which the scheduled task runs, to seconds, ensuring that new events are processed every five seconds, rather than the default, which is every five minutes.

How the sample application works

The CRUDApp sample application works by calling the command line and supplying the following parameters:

>>-java CRUDApp- -action -+- create -bodyFile file name 
    -type [subscription | generic] +-->
    +- [read | delete] -bsrURI bsrURI ---------------------------+  
    '- update -bodyFile file name -bsrURI bsrURI-----------------'  
>--hostname host name -port port number ---><

Where:

action
Life cycle stage to perform, either create, read, update, or delete.
bodyFile
Full path to XML-formatted file that forms the body of a HTTP POST (create) or PUT (update) request from this sample client application.
type
Type of object to create -- either a subscription object or a generic object can be created through the create action.
bsrURI
Unique Service Registry provided URI of an object in the content model. When a subscription or generic object is created, its bsrURI is reported as part of a response in standard output.
hostname
Hostname or IP address to the Service Registry service
port
Service Registry WC_defaulthost port, which is the port that the Service Registry web UI is hosted on -- typically 9080 in a standalone environment.

The sample application verifies that all parameters are supplied before instantiating an instance of the CRUDApp class and calling the appropriate action method.

Listing 1. Instantiating CRUDApp and calling action method
    // Initialize a new subscription management class with command line parameters
CRUDApp loader = new CRUDApp(action, type, bodyFile, bsrURI, hostName, port);
if(action.equals(CREATE))
    // create specified subscription object 
    // any thrown exceptions will be returned to the console
    loader.create();  
else if(action.equals(READ))
    loader.read();
else if(action.equals(UPDATE))
    loader.update();
else // DELETE
    loader.delete();

The CRUDApp action methods are responsible for constructing the appropriate Service Registry HTTP URL for the action specified. This URL is used to create an HttpURLConnection object that represents a connection to the remote object referred to by the URL. The methods are also responsible for setting the appropriate HTTP request method or verb, matching the action specified through the command-line call.

Listing 2. Action methods
// createSubURL: http://<hostName>:<port>/WSRR/8.0/Content/Subscription
// createGenURL: http://<hostName>:<port>/WSRR/8.0/Content/GenericObject
// deleteURL: http://<hostName>:<port>/WSRR/8.0/Content/<bsrURI>
// workURL: http://<hostName>:<port>/WSRR/8.0/Metadata/XML/<bsrURI>

/**
  * POSTs a subscription/generic body document in to Service Registry 
  * in order to create a new object
  * @throws Exception
  */
private void create() throws Exception
{
    // Open a connection to Service Registry
    URL url = new URL(type.equals(SUB) ? createSubURL : createGenURL);
    HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
    urlConnection.setRequestMethod("POST");
    workWithContent(urlConnection, true);
}

/**
  * PUTs a subscription/generic body document in to Service Registry
  * in order to update an existing object
  * @throws Exception
  */
private void update() throws Exception
{
    // Open a connection to Service Registry
    URL url = new URL(workURL);
    HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
    urlConnection.setRequestMethod("PUT");
    workWithContent(urlConnection, true);
}

/**
  * GETs the content of a subscription/generic object in Service Registry
  * @throws Exception
  */
private void read() throws Exception
{
    // Open a connection to Service Registry
    URL url = new URL(workURL);
    HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
    urlConnection.setRequestMethod("GET");
    workWithContent(urlConnection, false);
}

/**
 * DELETEs a subscription/generic object in Service Registry
 * @throws Exception
 */
private void delete() throws Exception
{
    // Open a connection to Service Registry
    URL url = new URL(deleteURL);
    HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
    urlConnection.setRequestMethod("DELETE");
    workWithContent(urlConnection, false);
}

The CRUDApp workWithContent method is responsible for:

  • Setting various request properties in the HTTP request header of the created HTTP URL connection object. For example, for the server to know that the content of the HTTP request is XML (for POST or PUT requests) the Content-Type attribute in the HTTP request header to is set to text/xml.
  • Through the HTTP URL connection object, connecting (opening a communications link) to the resource referenced by its URL.
  • For POST or PUT requests, reading their XML body content from a file and pushing it into Service Registry via the connection object's output stream, thus writing the payload to the connection's target.
  • Reading, checking, and reporting the response received from the open connection's input stream.
Listing 3. The workWithContent methods
/**
  * Make REST based API calls to Service Registry.
  * @param urlConnection Open HTTP URL connection to a specific REST API
  * @param useBody Set to true if action is create or update
  * @throws Exception
  */
private void workWithContent(HttpURLConnection urlConnection, boolean useBody) 
    throws Exception
{

  urlConnection.setRequestProperty("Content-Type", "text/xml-SOAP; charset=\"utf-8\"");
  urlConnection.setRequestProperty("Content-Length", "");
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setAllowUserInteraction(false); // no dialog boxes please		 
    
    // Do Connect
    urlConnection.connect();

    if(useBody) {
        // Read the file contents and send it to Service Registry
        InputStream in = new FileInputStream(bodyFile);
        OutputStream out = urlConnection.getOutputStream();
        
        int c;
        while((c = in.read()) != -1)
        {
            out.write(c);
        }
        out.flush();
        out.close();
    }

    // Read the response from the server
    BufferedReader reader = null;
    try
    {
        int rc = urlConnection.getResponseCode();
        // Check for a successful response to the action verb
        if(rc == 200 || rc == 201) // success
        {
            // Get Response	
            reader = new BufferedReader
                (new InputStreamReader(urlConnection.getInputStream()));
            StringBuffer stringBuffer = new StringBuffer();
            String line = null;

            while(null != (line = reader.readLine()))
            {
                stringBuffer.append(line);
            }
            reader.close();
            System.out.println("Received response code: " + rc);
            if(!stringBuffer.toString().isEmpty())
            System.out.println("The response was: " + stringBuffer.toString());	
            }
            else {  //failure  

                if(urlConnection.getRequestMethod().equals("POST")) { //creating
                    System.out.println("Unable to create: " + bodyFile.getName());
                }
                else {
                    //retrieve, update and delete
                    if(rc == 404) // The Object was not found
                    {
                        System.out.println("Object not found:" + bsrURI);
                    }
                }
                if(rc == 401) // Not authorised to perform the action
                {
                    System.out.println("Not authorised to perform the action");
                }

                reportProblem(urlConnection);
            }
        }
    }
    catch(IOException ex)
    {
    // If we fail to read the response, check the error stream as this may include 
    // details of the required dependency that we need to handle
        reportProblem(urlConnection);
    }
}

/**
  * Reports the status code and error response from a HTTP response message.
  * @param args List of arguments supplied by command line. See usage for more info.
  */
private void reportProblem(HttpURLConnection urlConnection) throws Exception
{
    StringBuffer stringBuffer = new StringBuffer();
    if(urlConnection.getErrorStream() != null) {
        BufferedReader reader = new BufferedReader(new
            InputStreamReader(urlConnection.getErrorStream()));	
        String line = null;

        while(null != (line = reader.readLine()))
        {
            stringBuffer.append(line);
        }
        reader.close();
    }

    // Unknown cause of error
    System.out.println("Received unexpected response: " 
        + urlConnection.getResponseCode());
    System.out.println(stringBuffer.toString());
}

You can download the complete source code of the application at the bottom of the article.

Known limitations of the sample application

This sample Java application shows how to create and retrieve content in Service Registry, specifically subscription or generic objects. It also facilitates the management of such objects through various stages in their life cycles, namely update and delete. Known limitations:

  • It only works when security is disabled.
  • The format of body content pushed to Service Registry is currently fixed to XML. However the sample application could easily be updated to accommodate JSON, an alternative format supported by Service Registry. The Content-Type attribute in the HTTP request header would be set to application/json.
  • To receive subscribed notifications tied to the creation and management of such objects, the subscription notification service must be enabled.

Terminology

Metadata
"Data about data." In Service Registry, metadata refers to data associated with the objects created in it, such as owner, last modified date, and relationships with other objects.
REST API
One of the API types supported by Service Registry apart from EJB APIs and web services. REST is an architectural style for accessing and manipulating resources.
Uniform Resource Identifier (URI)
Identifies a resource in a network in terms of its name and/or location.
bsrURI
An identifier that uniquely identifies an object in Service Registry. To determine the bsrURI of an object, use the Service Registry UI to view the object and then check the bsrURI field under Additional properties.
JavaScript Object Notation (JSON)
A lightweight data-interchange format based on the object-literal notation of JavaScript. JSON is programming-language neutral but uses conventions from languages that include C, C++, C#, Java, JavaScript, Perl, and Python.

Building the sample application

The source code of the sample application and additional resources accompanying it are contain in the JAR file SubscriptionSamples.jar, which you can download at the bottom of the article. The JAR file contains the following resources:

SampleXMLSubscription.xml
XML-formatted file used to described and create a single subscription object called SampleXMLSubscription.
SampleXMLGenericObject.xml
XML-formatted file used to describe and create a single generic object called SampleXMLGenericObject.
CRUDApp.java
Used to create and manipulate objects within the Service Registry content model.

Download SubscriptionSamples.jar and extract its contents into a temporary directory. You can compile and run the sample application using a standard Java SDK environment. For example, if the application has been downloaded to the same machine where Service Registry V8.0 is installed, then an IBM SDK Java Technology Edition V6.0 environment is available in the WebSphere Application Server home directory <WAS_INSTALL_ROOT>\java. No J2EE support or knowledge of the Service Registry EAR file is required. To compile the sample application CRUDApp, execute the following command if an SDK is present in your command line environment path: javac CRUDApp.java Otherwise, ensure that an SDK environment is picked up and used by referencing it directly in the command. For example, in Windows, execute:

<WAS_INSTALL_ROOT>\java\bin\javac CRUDApp.java

where <WAS_INSTALL_ROOT> could be: C:\PROGRA~2\IBM\WebSphere\AppServer.

After successfully compiling the sample application, the executable Java bytecode class file CRUDApp.class should be present in your temporary directory.

Exercising the sample application

Now you can use the sample Java application to demonstrate how subscription objects can be created and moved through their natural life cycle. The scenario below also demonstrates how such objects can be used to monitor changes on other objects contained in the repository via the subscription notification service.

Step 1. Create the subscription object SampleXMLSubscription

The subscription object's properties and subscribed operations are described through well-formed XML in the file SampleXMLSubscription.xml:

Listing 4. SampleXMLSubscription.xml
<resources>
  <resource>
    <properties>
      <property name="name" value="SampleXMLSubscription"/>
      <property name="namespace" value=""/>
      <property name="version" value="8.0"/>
      <property name="description" value=""/>
      <property name="targetName" value="SampleXMLGenericObject"/>
      <property name="targetNamespace" value=""/>
      <property name="targetVersion" value="8.0"/>
      <property name="targetBsrURI" value=""/>
      <property name="_targetQuery" value=""/>
      <property name="_referencedObjectMatchDepth" value="0"/>
      <property name="_notifySavedSearchResultChanges" value="false"/>
      <property name="_notifyPolicyUpdates" value="false"/>
      <property name="_notifyMonitoringPolicyUpdates" value="false"/>
      <property name="_notifierType" value="httppost"/>
      <property name="_endPointReference" value="http://localhost:9080/WSRR/8.0/
          Content/XMLDocument?name=SampleXMLSubscriptionHttpMsg"/>
      <property name="_endPointSecurityToken" value="wsgw10942123-sub45021287"/>
      <property name="_endPointSecurityAuthAlias" value=""/>
      <property name="_correlationID" value="wsgw10942123-sub45021287"/>
      <property name="_enableBatchNotification" value="false"/>
      <property name="_duration" value="7"/>
    </properties>
    <relationships/>
    <classifications/>
    <subscribedOperations>
      <subscribedOperation operation="create"/>
      <subscribedOperation operation="update"/>
      <subscribedOperation operation="delete"/>
    </subscribedOperations>
    <subscribedTransitions/>
  </resource>
</resources>

Key points from the above subscription definition:

  • The name of the subscription object, as indicated through property: name, is the same as the file -- SampleXMLSubscription.
  • The standard properties targetName and targetVersion are used to produce the set of target entities. In this case the subscription is only interested in objects in the content model whose names exactly match SampleXMLGenericObject and whose version is equal to 8.0. This scenario assumes that such an object doesn't currently exist, as one instance of it will be created, following the creation of the subscription object. Hence the target entity set will contain only one target to monitor.
  • The notifier type, which the subscription notification service will report subscribed events through, is the HTTP Post notifier, as indicated by the property _notifierType.
  • The target URL to which such events are posted points to Service Registry, as indicated by the property _endPointReference. From the URL, you can see that events are logged to Service Registry itself using its own REST API in a similar fashion to the sample application. Here for each event, a new XML document is created with the same name (SampleXMLSubscriptionHttpMsg), and it is stored in the content model for the repository system.
  • To optimize message flow, multiple notifications are not sent in a single message, as indicated by the false value for the property _enableBatchNotification.
  • Operations applied to objects in the target entity set (the generic objects named SampleXMLGenericObject at version 8.0) and subscribed to include create, update, and delete, as indicated through the list of subscribedOperation elements.

To create the above subscription object, disable security on Service Registry and run the following command. <extract_dir> refers to the location where you extracted the archive.

<extract_dir>\java CRUDApp -action create -bodyFile SampleXMLSubscription.xml 
-type subscription -hostname localhost -port 9080

The example assumes that the operating system is Windows, a Java SDK is present in your command-line environment path, the target Service Registry is local, and the default host port is 9080. A successful response like the one below should be displayed in the command console:

Received response code: 201
The response was: <properties>  <property name="bsrURI" 
value="e5608ee5-5b35-45a4.bcbf.07ce9f07bf54"/></properties>
create complete

The response indicates success, with Service Registry returning the value of the bsrURI uniquely identifying the newly created subscription object now present in Service Registry. This value will differ each time a subscription object is created. Make a note of the value so that you can identify the subscription object later in this scenario.

To confirm the creation of the subscription object matching the above definition:

  • Open the Service Registry web UI and log in as administrator. If you have a standalone application server, the URL will be something like http://localhost:9080/ServiceRegistry/. The port number may vary if you have more than one installation of WebSphere Application Server -- port numbers are specified during installation.
  • Use the Perspective dropdown at top right to switch to the Administrator perspective.
  • Use the My Service Registry dropdown and select All Subscriptions.
  • Select SampleXMLSubscription and confirm that its details match those expressed above in its body file SampleXMLSubscription.xml.

Alternatively, you can confirm creation of the subscription object by running the following command. <extract_dir> refers to the location where you extracted the archive.

<extract_dir>\java CRUDApp  -action read -bsrURI 
e5608ee5-5b35-45a4.bcbf.07ce9f07bf54 -hostname localhost -port 9080

A successful response like the one below should be displayed on the command console:

Listing 5
Received response code: 200    The response was: 
<?xml version="1.0" encoding="UTF-8"?><resources> 
<resource bsrURI="e5608ee5-5b35-45a4.bcbf.07ce9f07bf54" type="Subscription"> 
<properties> <property name="bsrURI" 
    value="e5608ee5-5b35-45a4.bcbf.07ce9f07bf54"/> 
<property name="name" value="SampleXMLSubscription"/> 
<property name="namespace" value=""/> <property name="version" value="8.0"/> 
<property name="description" value=""/> 
<property name="owner" value="UNAUTHENTICATED"/> 
<property name="lastModified" value="1321892414553"/> 
<property name="creationTimestamp" value="1321892414553"/> 
<property name="lastModifiedBy" value="UNAUTHENTICATED"/> 
<property name="emailAddress" value=""/> <property name="locale" value=""/> 
<property name="targetName" value="SampleXMLGenericObject"/> 
<property name="targetNamespace" value=""/> 
<property name="targetVersion" value="8.0"/> 
<property name="targetBsrURI" value=""/> 
<property name="_enableBatchNotification" value="false"/> 
<property name="_notifyPolicyUpdates" value="false"/> 
<property name="_endPointSecurityAuthAlias" value=""/> 
<property name="_referencedObjectMatchDepth" value="0"/>
<property name="_endPointReference" value="http://localhost:9080/WSRR/7.5/Content/
    XMLDocument?name=SampleXMLSubscriptionHttpMsg"/>      
<property name="_targetQuery" value=""/>      
<property name="_expiryStartTime" value="1321892414538"/> 
<property name="_notifySavedSearchResultChanges" value="false"/> 
<property name="_notifierType" value="httppost"/> 
<property name="_endPointSecurityToken" value="wsgw10942123-sub45021287"/> 
<property name="_notifyMonitoringPolicyUpdates" value="false"/>
<property name="_duration" value="7"/> 
<property name="_correlationID" value="wsgw10942123-sub45021287"/> 
</properties> <relationships/> <classifications/> <subscribedOperations>
<subscribedOperation operation="create"/> <subscribedOperation operation="update"/> 
<subscribedOperation operation="delete"/> </subscribedOperations> 
<subscribedTransitions/> <targetClassifications/> </resource> </resources>
read complete

Step 2. Create generic object and target of subscription object SampleXMLGenericObject

The generic object's properties are described through well formed XML in the file SampleXMLGenericObject.xml:

Listing 6. SampleXMLGenericObject.xml
<resources>
  <resource>
    <properties>
      <property name="name" value="SampleXMLGenericObject"/>
      <property name="namespace" value=""/>
      <property name="version" value="8.0"/>
      <property name="description" value=""/>
    </properties>
    <relationships/>
    <classifications/>
  </resource>
</resources>

Key points from the above generic object definition:

  • The name of the generic object, as indicated through the property name, is the same as the file -- SampleXMLGenericObject.
  • The version of the generic object, as indicated through the property version, is 8.0.

Based on the property values provided, the object will match as a valid target for the newly created subscription object. To create the above generic object, enable the subscription notification service on Service Registry and run the following command. <extract_dir> refers to the location where you extracted the archive.

<extract_dir>\java CRUDApp  -action 
create -bodyFile SampleXMLGenericObject.xml -type generic -hostname localhost -port 9080

A successful response should be displayed in the command console:

Received response code: 201
The response was: <properties>  <property name="bsrURI" 
value="97016997-b69c-4c36.a0bb.68ce9068bb0a"/></properties>
create complete

Again, the response indicates success, with Service Registry returning the value of the bsrURI uniquely identifying the newly created generic object now present in Service Registry. This value will differ each time a generic object is created. Make a note of the value so that you can identify the subscription object later in this scenario.

Now that you have created the generic object, it should match as a target for the new subscription, and since the subscription is listening for create operation events associated to this target object, a match should now have been made. Therefore you should now be able to see a logged subscription notification event in Service Registry in the form of an XML document named SampleXMLSubscriptionHttpMsg. Again, in the Administrator perspective of the Service Registry web UI, select Home at top left and then select XML documents in the Service Documents section. The resulting query returns all XML documents now present in the repository's content model. Within this list should be a single instance of the file SampleXMLSubscriptionHttpMsg.xml. Select this file and select the Contents tab in the details view:

Listing 7. SampleXMLSubscriptionHttpMsg.xml
<body:resources>
  <body:resource bsrURI="e5608ee5-5b35-45a4.bcbf.07ce9f07bf54" 
  correlationId="wsgw10942123-sub45021287" securityToken="wsgw10942123-sub45021287"
  type="Subscription"> 
  <body:notificationResource event="CREATE" 
  resourceBsrURI="97016997-b69c-4c36.a0bb.68ce9068bb0a" 
  resourceName="SampleXMLGenericObject" 
  resourceToSubscribedRelationship="sameObject" resourceType="GenericObject"     
  subscribedBsrUri="97016997-b69c-4c36.a0bb.68ce9068bb0a" 
  subscribedName="SampleXMLGenericObject" subscribedType="GenericObject" />
  </body:resource>
</body:resources>

The event message indicates that it is tied to a subscription resource with bsrURI: e5608ee5-5b35-45a4.bcbf.07ce9f07bf54, the new subscription object. The notification is tied to a create event for a GenericObject resource whose bsrURI 97016997-b69c-4c36.a0bb.68ce9068bb0a matches the new generic object. Thus you have now been notified through the subscription notification service that the generic object has moved through the create stage of its life cycle.

Step 3. Update subscription object to enable batch (optimised) mode notification

The next step is to collect further notification events for other life cycle stages the generic object moves through, namely update and delete. To reduce the number of event messages and resulting SampleXMLSubscriptionHttpMsg XML instance documents, you can choose to collect these remaining events in a reduced number of notifications. To do so, update the subscription object, setting its _enableBatchNotification property to true. Enabling this setting instructs the HTTP POST notifier for this subscription to send notifications to the target endpoint in batch mode, thus reducing the number of SampleXMLSubscriptionHttpMsg XML documents logged to Service Registry.

Only events that match this active subscription and that are available on the internal batch processing JMS queue at the time the scheduled tasks runs, are processed as a batch and logged in a single notification message. To proceed with this scenario, first update the subscription object by changing the _enableBatchNotification property value to true inside SampleXMLSubscription.xml. To put this change into effect, run the following update command. <extract_dir> refers to the location where you extracted the archive.

<extract_dir>\java CRUDApp -action update -bodyFile SampleXMLSubscription.xml 
-bsrURI e5608ee5-5b35-45a4.bcbf.07ce9f07bf54  -hostname localhost -port 9080

A successful response should be displayed in the command console:

Received response code: 200
update complete

In the Administrator perspective of the Service Registry web UI:

  • Use the My Service Registry dropdown and click All subscriptions.
  • Select SampleXMLSubscription and confirm that its details match those expressed above in its body file, SampleXMLSubscription.xml, and that the property _enableBatchNotification is now set to true.

Step 4. Update generic object multiple times

Move to the next stage of the generic object's CRUD life cycle: update. At the same time, you can demonstrate that the subscription object has truly been updated to notify in batch mode, where batched event messages are logged to Service Registry as a single XML document named SampleXMLSubscriptionHttpMsg.xml. You need to rapidly build up a collection of update events on the internal JMS queue, for the scheduled task to process them in one go as a single notification. The SubscriptionNotfifierPluginScheduler task runs once every five seconds, and therefore you need to repeatedly issue the same update command multiple times.

It is possible that update events could be picked up and processed across one or more invocations of the scheduled task, thus producing multiple instances of the file SampleXMLSubscriptionHttpMsg.xml. However, if the updates are repeated quickly, each new instance of this XML document should contain multiple batched update events within it, successfully demonstrating the batch mode subscription option.

In order to isolate only those XML documents logged through this activity by the subscription notification service, delete all current instances of this document produced from prior activity. In the Administrator perspective of the Service Registry web UI, select Home at top left and then select XML documents in the Service Documents section. The resulting query returns all XML documents now present in the repository's content model. Within this list should be one or more instances of the file SampleXMLSubscriptionHttpMsg.xml. Select all file instances with this name and delete them all.

Update the generic object multiple times. To do this, simply PUT the object's current body file, SampleXMLGenericObject.xml, unaltered to the existing object in Service Registry as replacement content. Even though you have not changed the properties of the object in any way, the PUT refreshes the generic object with its current definition, causing an update to occur. Run the following update command at the command line. <extract_dir> refers to the location where you extracted the archive.

<extract_dir>\java CRUDApp -action update -bodyFile SampleXMLGenericObject.xml 
-bsrURI 97016997-b69c-4c36.a0bb.68ce9068bb0a  -hostname localhost -port 9080

A successful response should be displayed in the command console:

Received response code: 200
update complete

Using the command console's command history, recall the last update command above and reissue it, then resubmit the same update command seven times in quick succession. You have now repeatedly updated the generic object, which is a match as a target for the new subscription, and you should expect one or more batched notification messages in the form of XML documents named SampleXMLSubscriptionHttpMsg. Once again, in the Administrator perspective of the Service Registry web UI, select the Home option at top left and then select XML documents in the Service Documents section. Within this list should be one or more instances of the file SampleXMLSubscriptionHttpMsg.xml. Examine each instance in turn by selecting it and then selecting the Contents tab in the Details view. The contents should look like this:

Listing 8. Sample contents of SampleXMLSubscriptionHttpMsg.xml instances in batch mode
<body:resources>
  <body:resource bsrURI="e5608ee5-5b35-45a4.bcbf.07ce9f07bf54" 
  correlationId="wsgw10942123-sub45021287" securityToken="wsgw10942123-sub45021287" 
  type="Subscription" > <body:notificationResource  event="UPDATE" 
  resourceBsrURI="97016997-b69c-4c36.a0bb.68ce9068bb0a" 
  resourceName="SampleXMLGenericObject" resourceToSubscribedRelationship="sameObject"
  resourceType="GenericObject" subscribedBsrUri="97016997-b69c-4c36.a0bb.68ce9068bb0a" 
  subscribedName="SampleXMLGenericObject" subscribedType="GenericObject" />
  <body:notificationResource  event="UPDATE"  
  resourceBsrURI="97016997-b69c-4c36.a0bb.68ce9068bb0a"  
  resourceName="SampleXMLGenericObject" resourceToSubscribedRelationship="sameObject" 
  resourceType="GenericObject" subscribedBsrUri="97016997-b69c-4c36.a0bb.68ce9068bb0a"
  subscribedName="SampleXMLGenericObject" subscribedType="GenericObject" />
  <body:notificationResource event="UPDATE" 
  resourceBsrURI="97016997-b69c-4c36.a0bb.68ce9068bb0a"  
  resourceName="SampleXMLGenericObject"  resourceToSubscribedRelationship="sameObject"
  resourceType="GenericObject" subscribedBsrUri="97016997-b69c-4c36.a0bb.68ce9068bb0a"
  subscribedName="SampleXMLGenericObject"  subscribedType="GenericObject" />
  <body:notificationResource  event="UPDATE"  
  resourceBsrURI="97016997-b69c-4c36.a0bb.68ce9068bb0a" 
  resourceName="SampleXMLGenericObject" resourceToSubscribedRelationship="sameObject" 
  resourceType="GenericObject" subscribedBsrUri="97016997-b69c-4c36.a0bb.68ce9068bb0a" 
  subscribedName="SampleXMLGenericObject"  subscribedType="GenericObject" />
  <body:notificationResource event="UPDATE"  
  resourceBsrURI="97016997-b69c-4c36.a0bb.68ce9068bb0a"  
  resourceName="SampleXMLGenericObject" resourceToSubscribedRelationship="sameObject" 
  resourceType="GenericObject" subscribedBsrUri="97016997-b69c-4c36.a0bb.68ce9068bb0a" 
  subscribedName="SampleXMLGenericObject"  subscribedType="GenericObject" />
  </body:resource>
</body:resources>

The event message indicates that it is tied to a subscription resource with bsrURI e5608ee5-5b35-45a4.bcbf.07ce9f07bf54, which is the subscription object. The notifications are tied to update events for the repeatedly updated GenericObject resource with bsrURI 97016997-b69c-4c36.a0bb.68ce9068bb0a. Thus you have been notified through the subscription notification service that the generic object has moved through the update stage of its life cycle multiple times and all these events are aggregated into a single notification message because the subscription property _enableBatchNotification was set to true.

Step 5. Delete generic object

Once again, in order to isolate only those XML documents logged through future activity by the subscription notification service, first delete all instances of XML document notification messages produced from update activity performed in the previous step:

  • From the Administrator perspective of the Service Registry Web UI, select Home at top left.
  • In the Service Documents section, select XML documents.
  • Within the Displayed Results list, select and delete all instances of the file SampleXMLSubscriptionHttpMsg.xml.

Complete the final stage of the generic objects CRUD life cycle: Delete, which you will be notified of in the form of a single event message. Run the following delete command at the command line. <extract_dir> is the location where you extracted the archive.

<extract_dir>\java CRUDApp -action delete -bsrURI 
97016997-b69c-4c36.a0bb.68ce9068bb0a  -hostname localhost -port 9080

A successful response should be displayed in the command console:

Received response code: 200
delete complete

Again, through the Service Registry Web UI, examine the list of XML instance documents stored in the Service Registry content model. You should see a single instance of the file SampleXMLSubscriptionHttpMsg.xml. Select this file and click on the Contents tab in the Details view. The file should look like this:

Listing 9. SampleXMLSubscriptionHttpMsg.xml
<body:resources>
  <body:resource bsrURI="e5608ee5-5b35-45a4.bcbf.07ce9f07bf54" 
  correlationId="wsgw10942123-sub45021287" securityToken="wsgw10942123-sub45021287" 
  type="Subscription" > <body:notificationResource event="DELETE" 
  resourceBsrURI="97016997-b69c-4c36.a0bb.68ce9068bb0a" 
  resourceName="SampleXMLGenericObject" resourceToSubscribedRelationship="sameObject"
  resourceType="GenericObject" subscribedBsrUri="97016997-b69c-4c36.a0bb.68ce9068bb0a" 
  subscribedName="SampleXMLGenericObject" subscribedType="GenericObject" />
  </body:resource>
</body:resources>

Step 6. Delete the subscription object

Complete the final stage of the subscription objects CRUD life cycle: Delete. Run the following delete command from the command line. <extract_dir> is the location where you extracted the archive.

<extract_dir>\java CRUDApp -action delete -bsrURI 
e5608ee5-5b35-45a4.bcbf.07ce9f07bf54  -hostname localhost -port 9080

A successful response should be displayed in the command console:

Received response code: 200
delete complete

To confirm that the subscription object has been removed and the repository is back to its original state prior to this life cycle test, select the My Service Registry dropdown in the Administrator perspective and click All subscriptions. The subscription object named SampleXMLSubscription should no longer be available for selection.


Download

DescriptionNameSize
Code sampleSourceCode.zip100 KB

Resources

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


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. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

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.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

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

 


All information submitted is secure.

Dig deeper into WebSphere on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere
ArticleID=857507
ArticleTitle=Working with subscriptions in WebSphere Service Registry and Repository V8
publish-date=02062013