Integrating SOAP Web services in WebSphere sMash applications

Using the REST to SOAP extension

You can probably think of many scenarios in which you might want to reuse existing SOAP Web services in new applications. The IBM® WebSphere® sMash REST to SOAP extension enables you to provide REST access to existing SOAP Web services, providing easier and more intuitive access to such functions. This tutorial demonstrates how you can use the WebSphere sMash REST to SOAP extension to leverage a SOAP Web service deployed on IBM WebSphere Application Server. The SOAP Web service will serve to provide data for a Dojo-based widget provided by WebSphere sMash.

Dustin Amrhein, Staff Software Engineer, IBM

Author photoDustin Amrhein joined IBM as a member of the development team for the WebSphere Application Server. While in that position, Dustin worked primarily on web services infrastructure and web services programming models. In addition, Dustin worked on the development of a RESTful services framework for Java runtimes. In his current role Dustin is a WebSphere Client Technical Professional.



26 August 2009

Also available in Chinese

Before you start

This tutorial provides guidance for using the IBM WebSphere sMash REST to SOAP extension, which enables you to leverage existing SOAP Web services functionality in new Web applications. This tutorial also discusses the WebSphere sMash Zero Resource Model (ZRM), and demonstrates pre-built Dojo widgets that are delivered with the WebSphere sMash product.

Objectives

This tutorial walks you through the process of building a sample widget that pulls stock prices for specified companies. The widget will communicate RESTfully with a WebSphere sMash application script written in PHP. The result of this communication will be the integration of data stored in a relational database, and data retrieved from a SOAP Web service application hosted on IBM WebSphere Application Sever. The end result will be a graphical user interface (GUI) that displays company names, their stock symbols, and stock prices. The interface will let users add companies of interest to display and remove those that are no longer needed.

Through this exercise, you will learn about the WebSphere sMash REST to SOAP extension, the WebSphere sMash Zero Resource Model, and a subset of the prebuilt Dojo widgets delivered with WebSphere sMash. As part of the tutorial, you will also install a Java™ Enterprise Edition (Java EE) Web service application to the WebSphere Application Server environment.

Prerequisites

This tutorial is intended for Web application developers, and assumes a general knowledge of Web application technologies, such as HTML, Java, and JavaScript™. It is helpful if you understand both REST and SOAP Web services concepts, but expertise in either area is not required. Familiarity with WebSphere sMash is also helpful, but not mandatory.

System requirements

To follow this tutorial, you need access to both a WebSphere sMash (V1.1.1) and WebSphere Application Server (V6.1 or V7.0) installation. You can download both WebSphere sMash Developer's Edition and WebSphere Application Server for Developers for free (see Resources). For the WebSphere Application Server, you will need to create a default application server profile that can host a Web service application.

As an alternative to installing WebSphere sMash and WebSphere Application Server on your own machine, you can leverage the Amazon Machine Images for each of these products and host instances on the Amazon Elastic Compute Cloud (EC2). You can get started with these products (and more) on Amazon EC2 by visiting the developerWorks Cloud Computing Resource Center.

Regardless of whether you install the software locally or leverage them on Amazon EC2, the steps in this tutorial will be the same.

Duration

If you already have WebSphere sMash and WebSphere Application Server already installed, this tutorial will take approximately 2 hours to complete.


Install the Web service

To begin this exercise, you need to install the stock quote SOAP Web service application to the WebSphere Application Server environment. The stock quote application is a sample application that is included with WebSphere Application Server.

  1. To install the application, navigate to the WAS_PROFILE_ROOT/bin directory of your WebSphere Application Server environment, where WAS_PROFILE_ROOT represents the installed location of your default application server profile.
  2. From here, install the application using this wsadmin command:
    Listing 1. Application installation command
    wsadmin -connType NONE -lang jython -c 
    "AdminApp.install('<app_location>/WebServicesSample.ear', '[-usedefaultbindings]')"
  3. Start the application to verify that the installation was successful. Do this by logging in to the WebSphere Application Server administrative console at http://<was_host>:<was_admin_port>/ibm/console and select Applications => Application Types => WebSphere enterprise applications. You should see the WebServicesSamples application listed (Figure 1).
    Figure 1. WebServicesSamples Application listed in admin console
    WebServicesSamples Application listed in admin console

    Enlarge image

  4. Select the checkbox next to the application name in the console and click the Start button.
  5. After the application has successfully started, confirm it is available to serve requests by navigating to http://<was_host>:<was_http_port>/StockQuote/services/xmltoday-delayed-quotes in a browser. If you see a panel similar to Figure 2, then the stock quote Web service is installed and ready to receive requests.
    Figure 2. Stock quote service message
    Hello message from the stock quote web service

Create the WebSphere sMash application

Before you can begin developing the WebSphere sMash application, you need to create the a new application with the WebSphere sMash App Builder. The App Builder is itself an application that provides a Web-based development environment for building WebSphere sMash applications.

  1. Open a command line shell for your operating system and navigate to the WebSphere sMash install directory (you do not have to navigate to this directory if the WebSphere sMash directory is in your PATH environment variable).
  2. Enter appbuilder open to start and open the App Builder application. You should see a browser window with the display shown in Figure 3.
    Figure 3. App Builder welcome page
    Image of App Builder welcome page

    Enlarge image

  3. Using the App Builder, create a new application called "Stocks" by clicking on the Create new application link on the left side of the App Builder welcome page (Figure 4).
    Figure 4. Create a new application
    Creating a new WebSphere sMash application

    Enlarge image

The WebSphere sMash application is now created and is ready to be edited.


Create resource models

The first thing you will do is utilize the WebSphere sMash Zero Resource Model (ZRM) framework to define the resource that will be used by this application. The ZRM provides a framework for defining resources that contain your application state or data, store and retrieve those resources from a relational data store, and provide HTTP REST access to those resources. For this exercise, you will create a company resource containing data attributes that represent the company name, company stock symbol, and stock price.

  1. To begin editing the WebSphere sMash application, click on the Stocks application name. The File Editor for the application will display (Figure 5).
    Figure 5. Stocks File Editor page
    Stocks File Editor page

    Enlarge image

  2. To create the resource model select New file => Zero Resource Model in /app/models => New model (Figure 6).
    Figure 6. Creating the company resource model
    Creating the company resource model

    Enlarge image

  3. When prompted for the name of the resource model file, enter company.json and click Create.
  4. When asked if you want to add the zero.resource dependency, click Add.
  5. The next panel (Figure 7) is for editing the resource model for the company stock quote application. This model has three distinct fields:
    • name: (required) a string that represents the company's name.
    • symbol: (required) a string that represents the company's stock symbol.
    • price: (optional) a float that represents the company's stock price per share.
    Figure 7. The company resource model
    Image of the company resource model definition

    Enlarge image


Create database tables

Create a database table from the company resource model that you just defined. For the purpose of this tutorial, you will use the Derby database that is provided with WebSphere sMash; this means that no database configuration is necessary. (See the ZRM documentation to learn about other databases supported by the ZRM and their required configurations.)

  1. Before you create the Derby database tables from the company resource model, you can provide an initial set of data by defining an /app/models/fixtures/initial_data.json file. To create this file, select New file => Other File and supply the file path and name (Figure 8).
    Figure 8. Creating the initial_data.json file
    Creating the initial_data.json file

    Enlarge image

  2. The initial_data.json file is used to create instances of the resource models defined in a WebSphere sMash application. This data in the file is used to populate the database tables with an initial set of data. You can define as many instances of the company resource as you like. In the example shown in Figure 9, three instances are provided.
    Figure 9. Supplying initial data
    Contents of the initial_data.json file

    Enlarge image

    In each case shown here, the initial stock price is set to 0. This is fine because the actual values will be retrieved through the stock quote SOAP Web service you installed on WebSphere Application Server.

  3. Navigate to the root directory of your Stocks application. (This directory was established when you created the application earlier in this tutorial.) From this directory, run the zero model sync command (the root directory of the WebSphere sMash installation must be set in your PATH environment variable).

    The console output in Figure 10 shows that a table called COMPANY was created in the default Derby database. It also shows that the data in the initial_data.json file was used to populate the newly created table.

    Figure 10. Running the zero model sync command
    Running the zero model sync command

    Enlarge image


Create resource handlers

Now that you have defined a table and populated it with an initial set of company resource data, you can provide RESTful access to the data in that table. To do this, you need to create a new resource handler script file. These scripts live in the /app/resources directory and can be implemented in either PHP or Groovy. For the purpose of this tutorial, you will create a PHP handler.

  1. Before creating a PHP resource handler, you first need to add a few dependencies to your application. Click on the Dependencies tab at the top of App Builder display, then click the Add button to have WebSphere sMash search for a list of dependencies that can be added to the application.
  2. To proceed further, you need to add dependencies on these components:
    • zero.php
    • zero.resource.php
    • zero.php.connection
    • zero.connection.soap
    If these components are not in the dependencies list, you can directly edit the /config/ivy.xml file in the application's root directory, if necessary. In either case, the resulting ivy.xml file should contain the code shown in Listing 2.
    Listing 2. Updated ivy.xml file
    <ivy-module version="1.3">
      <info module="Stocks" organisation="zero" revision="1.0.0">
        <license name="type of license" url="http://license.page"/>
        <ivyauthor name="author name" url="http://authors.home.page"/>
        <description homepage="http://module.description.page"/>
      </info>
      <publications>
        <artifact type="zip"/>
      </publications>
      <dependencies>
        <dependency name="zero.core" org="zero" rev="[1.0.0.0, 2.0.0.0["/>
        <dependency name="zero.resource" org="zero" rev="[1.0.0.0,2.0.0.0["/>
        <dependency name="zero.php" org="zero" rev="[1.0.0.0,2.0.0.0["/>
        <dependency name="zero.php.connection" org="zero" rev="[1.0.0.0,2.0.0.0["/>
        <dependency name="zero.connection.soap" org="zero" rev="[1.0.0.0,2.0.0.0["/>
        <dependency name="zero.resource.php" org="zero" rev="[1.0.0.0,2.0.0.0["/>
      </dependencies>
    </ivy-module>

    To be sure the dependencies are up to date in the application, run the zero resolve command from the root directory of the Stocks application.

    Now you are ready to create the PHP resource handler for the company resource.

  3. Select New File => Resource Handler in /app/resources. When prompted for the name of the resource handler, enter company.php and select default.php for the Template Name value (Figure 11).
    Figure 11. Creating a PHP resource handler
    Creating a PHP resource handler

    Enlarge image

  4. Within the company.php resource handler, you need to define a "Company" class that contains these methods:
    • onList
    • onRetrieve
    • onCreate
    • onUpdate
    • onDelete
    Each of these methods map to HTTP requests made for the company resource data stored in the COMPANY table of the Derby database. (Figure 12)
    Figure 12. The company resource handler
    The company resource handler

    Enlarge image

The company.php resource handler utilizes the zrm_delegate function in all methods (with the exception of the onList method). This means that the ZRM will control:

  • Creating a new company resource.
  • Persisting it to your Derby database.
  • Retrieving a specified company resource from the database.
  • Updating an existing company resource.
  • Removing an existing company resource.

This is all done simply by calling the zrm_delegate function.

The onList method does not call the zrm_delegate function because custom code will be inserted in the method to return up-to-date stock price information for each company.


Integrate the Web service

To integrate the stock quote Web service deployed on WebSphere Application Server into the WebSphere sMash application, you need to configure a WebSphere sMash connection destination, and then create a Groovy template. The template file will be the SOAP body template for requests sent to the stock quote Web service, and, as such, tells the WebSphere sMash runtime how to render the SOAP body for requests sent to the service.

  1. To configure a WebSphere sMash connection destination, you need to modify the /config/zero.config file. Insert the code shown in Listing 3 into your zero.config file.
    Listing 3. Connection destination configuration
    /config/connection/destinations += {
      "/StockQuote/*" : {
         "handlers" : [{
            "name" : "restToSoap",
            "config" : {
               "endpointAddress" : 
                 "http://localhost:9083/StockQuote/services/xmltoday-delayed-quotes",
               "SOAPVersion" : "1.1",
               "r2sMapping" : [{
                  "RESTOperation" : "GET",
                  "URLMatch" : "/StockQuote/{symbol}",
                  "SOAPBodyTemplate" : "stockSOAPBodyContents.gt"
               }]
            }
         }]
      }
    }

    This configuration ensures that any HTTP GET request sent using the WebSphere sMash Connection API with a path like /StockQuote/* will be redirected to the http://localhost:9083/StockQuote/services/xmltoday-delayed-quotes Web service.

  2. Next, you need to create the stockSOAPBodyContents.gt Groovy template. Select New File => View in /app/views and specify stockSOAPBodyContents.gt as the file name. The contents of the file are shown in Listing 5.
    Listing 5. SOAP body Groovy template file
    <p875:getQuote xmlns:p875="xmltoday-delayed-quotes">
        <symbol><%= r2s_getParam("symbol") %></symbol>
    </p875:getQuote>

    The r2s_getParam("symbol") reference in the template tells WebSphere sMash to retrieve the symbol parameter from the request (includes query parameters, form-encoded parameters, and URL match parameters) and use it as the value of the symbol XML element.

    For example, an HTTP GET request using the WebSphere sMash Connection API to /StockQuote/IBM would result in the SOAP body shown in Listing 6.

    Listing 6. Example SOAP body rendering
    <p875:getQuote xmlns:p875="xmltoday-delayed-quotes">
        <symbol>IBM</symbol>
    </p875:getQuote>

The stock quote SOAP Web service on WebSphere Application Server has been successfully integrated into your WebSphere sMash application. The next step is to make use of this configuration from the company resource handler.


Update the company resource handler

With the integration of the stock quote Web service in place, you need to update the onList method in the company resource handler (/app/resources/company.php file) to return the list of stored companies and their current stock price -- which is obtained via the stock quote Web service.

To do this, you need to add code to the onList method that results in a call to the Stock Quote Web service for each company resource. You can do this with the WebSphere sMash Connection API, as shown in Listing 7.

Listing 7. Using the WebSphere sMash Connection API
<?php

class Company {

    function onList() {
        $companies = $collection->list();
        $i = 0;
        foreach($companies as $company){
            $symbol = $company->symbol;
            $rspBody = connection_get('/StockQuote/' . $symbol);
            $jsonBody = json_decode($rspBody['body']);
            $price = $jsonBody['getQuoteResponse']['getQuoteReturn'];
            $json['name'] = $company->name;
            $json['symbol'] = $symbol;
            $json['price'] = $price;
            $jsonArray[$i] = $json;
            $i = $i + 1;
        }
        zput('/request/view', 'JSON');
        zput('/request/json/output', $jsonArray);
        render_view();
    }
    ...

The first step in the code is to retrieve a list of all the company resources using the provided ZRM APIs. For each company resource, a request is then sent to the /StockQuote/<company_stock_sybmol> URL using the connection_get function. Due to the integration steps taken in the previous section, this request sent via the connection API results in a SOAP request being sent to the Stock Quote Web service on WebSphere Application Server. The result of the GET request is JSON content that specifies the current stock price of the indicated stock symbol.

After you have retrieved the necessary information, you need to store it in a manner that is congruent with the resource model for the company resource. This means the output fields need to match exactly with the fields specified in the resource model. This mapping makes integrating with a Dojo widget much easier.

After you have retrieved and stored all the needed information, you can specify output using the WebSphere sMash global context:

  1. Set the rendered return type by setting JSON as the value for the /request/view value in the global context.
  2. Set the output by placing the array of all company resources in the global context under the /request/json/output key.
  3. Render the JSON output by calling the render_view function.

Create a Dojo widget

At this point, you have the company resource handler returning the company resource information along with the current stock price for each company. Next, you will work on building a front-end Dojo widget to expose this data.

  1. For the purpose of this tutorial, you first need to create an HTML file that will contain the widget. Select New File => HTML Page in /public and specify index.html as the file name. When prompted, click Add to add a dependency on the zero.dojo module.
  2. On the source editor for the index.html page, add the necessary Dojo widget. Select the Design tab at the bottom of the page editor. In the visual HTML editor, select the Data tab from the toolbar on the right, then select New => ZRM Store.
  3. In the configuration panel for the ZRM Store, enter companyStore for the Variable Name and enter company as the Resource Collection (Figure 13).
    Figure 13. The ZRM company data store
    The ZRM company data store

    Enlarge image

    Since you specified the company resource in the ZRM store, this data store will automatically retrieve and store data from the company resource handler. When the store retrieves data from the company resource handler, it does so by issuing an HTTP GET request that maps to your company resource handler's onList method. This method contains the necessary customizations to return all of the company resources along with their current stock price.
  4. To configure the widget, select the Create tab in the right toolbar and scroll down until you see the Zero section. Select the Data Grid element and drag-and-drop it on to the HTML page. The element is indicated in Figure 14.
    Figure 14. The Zero Data Grid element
    The Zero Data Grid element

    Enlarge image

  5. Right-click on the Data Grid element in your HTML page, and select Properties. You can now configure the grid to display the company resource data.
    Figure 15. Configuring the Zero Data Grid
    Configuring the Zero Data Grid

    Enlarge image

    The ID and Name properties map to the HTML element's ID and Name attributes, and you can insert any value you would like. After specifying an ID and Name value, make sure that Read Only is not checked. By permitting the widget to read and write, your users can create new company resources, edit existing company resources, and remove company resources directly from the widget interface.
  6. Specify the name, symbol, and price fields for the Visible Fields property. This ensures the widget will display each of these values in the company resource to the user.
  7. Select the companyStore for the Data Store property. This sets the previously configured data store as the data source for the grid.

Now you are ready to start your application and test the widget.


Test the Dojo widget

To test the Dojo stock price widget, you must first start the WebSphere sMash application. To do this, click the green arrow labeled Start in the upper right corner of the App Builder panel. When the application has started, open the http://<smash_host>:<smash_port>/index.html URL. You should see the widget you created earlier. The widget should display the data that was defined in the initial_data.json file (Figure 16).

Figure 16. Viewing the Dojo stock price widget
Viewing the Dojo stock price widget

Enlarge image

You can interact with this widget to resize columns, add new companies, remove companies, or edit the existing companies. Remember that if you add a new company, you should specify 0 as the stock price since it will be automatically retrieved via the stock quote SOAP Web service.


Summary

Using WebSphere sMash to deliver Web-based applications opens up a diverse range of options. As you could see in this tutorial, integrating existing applications, like SOAP Web service applications, can be easily accomplished to create new uses for existing functions. This integration can be achieved with a mix of code, configuration, and convention.

Far from being just a back-end application hosting environment, WebSphere sMash also offers up a set of tools that can help you quickly build rich, interactive user interfaces that leverage application function and data. The code used for this tutorial can be downloaded and used either as a reference or simply as proof of the technology.

Actually trying this tutorial is now easier than ever before because of the availability of both WebSphere sMash and WebSphere Application Server Amazon Machine Images and Developer Editions(see Resources). These offerings can help you expedite your development with little or no cost. Try them out with this tutorial and see for yourself.

Resources

Learn

Get products and technologies

Discuss

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, Web development
ArticleID=422486
ArticleTitle=Integrating SOAP Web services in WebSphere sMash applications
publish-date=08262009