Making SOAP service calls using SUDS.js

In many Enterprise market segments, SOAP services remain the dominant web service protocol. Since SOAP is generally implemented over HTTP, most network clients including Titanium's Ti.Network can interact effectively with this protocol.

Even with Titanium's Ti.Network module working with SOAP, envelopes and XML results can be challenging, and often requires creating a SOAP envelope and a huge amount of XML manipulation. This recipe demonstrates how a few open-source modules can increase your productivity when interacting with SOAP services and their XML results.

To help illustrate how to interact with SOAP services, the recipe uses the www.webserviceX.NET weather SOAP service to return weather results for a city entered in the City: field, as shown in the following screenshots:

Making SOAP service calls using SUDS.js

Getting ready

This recipe uses the SUDS and XMLTools CommonJS modules. These modules and other code assets can be downloaded from the source code provided by the book, or individually through the links provided in the See also section at the end of this recipe. Installing these modules is straightforward and simply requires copying the suds2.js and XMLTools.js files into your Titanium project, as highlighted in the following screenshot:

Getting ready

How to do it…

Once you've added the suds2.js and XMLTools.js modules to your project, you need to create your application namespaces in the app.js file and use require to import the module into your code, as shown in the following snippet:

//Create our application namespace
var my = {
  suds : require('suds2'),
  xmlTools : require("XMLTools"),
  isAndroid : (Ti.Platform.osname === 'android')
};

SOAP helper methods

In addition to the two CommonJS modules imported earlier, this recipe uses the soapHelper object to handle formatting and configuration activities.

var soapHelper = {
  1. The configuration object contains all the configuration details that suds.js needs to return an XML result:
      config : {
        endpoint:"http://www.webservicex.com/globalweather.asmx";  targetNamespace: 'http://www.webserviceX.NET/',
        includeNS : false,
        addTargetSchema : true 
      },
  2. The resultParser object is used to format the returned XML result into JavaScript objects:
      resultParser : {
  3. The removeHeader object is used to remove the XML header node. Android requires the header to be removed before the parseString function will correctly create an XML document object.
        removeHeader : function(text){
          return text.replace(
            '<?xml version="1.0" encoding="utf-16"?>',''), 
        },
  4. The xmlToObject function converts a Ti.XML.Document object into JavaScript objects.
        xmlToObject : function(doc){
  5. The first step is to get a Ti.XML.Nodelist for the tag GetWeatherResponse.
    var results = doc.documentElement.getElementsByTagName(
     'GetWeatherResponse'),
  6. Android and iOS handle the conversion process differently. Use the my.isAndroid property to branch the conversion logic.
    if(my.isAndroid){
  7. The weather service result contains a nested XML document. The following example demonstrates how to read the embedded XML document from the GetWeatherResponse node into a new Ti.XML.Document. The removeHeader function is used to fix the textContent value, to be compliant with Android's XML Document format.
    var docCurrent =Ti.XML.parseString(
      soapHelper.resultParser.removeHeader(
      results.item(0).textContent));
  8. Next, the Ti.XML.Document object is provided to the XMLTools module's constructor and then converted into JavaScript objects using the toObject method, as demonstrated in the following snippet:
          return new my.xmlTools(docCurrent).toObject();
        }else{
  9. On iOS, we use the getChildNodes function to obtain the weather child node:
        var weather =results.item(0).getChildNodes()
          .item(0).getChildNodes();
  10. The XML string from the weather node is then loaded into the XMLTools module's constructor, and then converted into JavaScript objects using the toObject method, as demonstrated in the following code block:
            var docCurrentFromString = Ti.XML.parseString(soapHelper.resultParser.removeHeader(weather.item(0).textContent));
            return new my.xmlTools(docCurrentFromString).toObject();
          }
        }
      }
    };

Creating the UI

This section of the recipe outlines the sample UI used to call and display results from the weather SOAP service.

  1. A new Ti.UI.Window is created for all UI elements to be attached.
      var win = Ti.UI.createWindow({
        backgroundColor:'#fff', layout:'vertical'
      });
  2. The text field txtCity is to allow the user to enter the city whose weather they wish to be displayed.
      var txtCity = Ti.UI.createTextField({
          value:'New York', hintText:'Enter city',top:10, height:40, left:10, right:10,textAlign:'left', borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED 
      });
      win.add(txtCity);
  3. The text field txtCountry is to allow the user to input the name of the country to which the city belongs.
      var txtCountry = Ti.UI.createTextField({
        value:'United States', hintText:'Enter country',top:10, height:40, left:10, right:10, textAlign:'left', borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED 
      });
      win.add(txtCountry);
  4. The goButton is a Ti.UI.Button used to call the weather SOAP service.
      var goButton = Ti.UI.createButton({
        title:'Find Weather', left:10, top:10
      });
      win.add(goButton);
  5. The tableView is a Ti.UI.TableView used to display the results of the SOAP service.
      var tableView = Ti.UI.createTableView({
        visible : false, top:10, height:100, width:Ti.UI.FILL
      });
      win.add(tableView);

The uiHelpers object

The uiHelpers object is used to update the UI objects with different states of the app as well as load the tableView with the SOAP service result.

var uiHelpers = {

The updateUI is used to format the object results from the SOAP service for display.

  updateUI : function(weather){
    var data = [];
    tableView.visible = true;
    data.push({title: "Sky Conditions: " + weather.SkyConditions, color:'#000'});
    data.push({title: "Temperature: " + weather.Temperature, color:'#000'});
    data.push({title: "Time: " + weather.Time});
    tableView.setData(data);	
  };

The resetUI method is used to hide the tableView from the user when SUDS is calling the web service. This method is also used to hide the tableView when the a SUDS call results in an error.

  resetUI :function(){
    tableView.visible = false;
  };
};

Calling the SOAP service

The click event on the goButton is used to perform the weather SOAP service call.

goButton.addEventListener('click',function(e){
  1. The resetUI method is first called to hide the tableView while the service is being called.
      uiHelpers.resetUI()
  2. A new instance of sudsClient is created with the configuration information defined earlier in the soapHelper.config object.
      var sudsClient = new my.suds(soapHelper.config);
  3. The invoke method is then called on sudsClient. The first argument provided is the SOAP method that suds should call.
      sudsClient.invoke('GetWeather', 
  4. The second argument provided to sudsClient is the name of the city and country that the user has requested, to retrieve weather information.
      {
        CityName: txtCity.value,
        CountryName: txtCountry.value
      }, 
  5. The final argument of the invoke method is the callback method SUDS. This callback method will be provided will to provide a Ti.XML.Document with the service's results. The following example demonstrates using an inline function as a callback method:
      function(xml) {
  6. The inline callback method will receive a Ti.XML.Document once the service has completed. Once received, the result is parsed into JavaScript objects using the resultParser object, as detailed earlier in the recipe.
        var weather = soapHelper.resultParser.xml2Object(xml);
  7. The Status property is changed on the parsed object to determine if the weather objects have successfully been created.
        if(weather.Status==='Success'){
  8. If the service results have successfully been converted into objects, they are provided to the updateUI method, to be displayed to the user.
          uiHelpers.updateUI(weather);
        }else{
  9. If an error occurred in calling the service or processing the results, we alert the user and then hide the tableView display object.
          alert("Sorry a problem happened");
          uiHelpers.resetUI();
        }
      });
    });

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.82.244