Integrating mobile applications with WebSphere Message Broker using IBM Worklight

This article shows you how to use IBM Worklight and the Worklight server to develop hybrid mobile applications that invoke enterprise services deployed on WebSphere Message Broker. The integration with WebSphere Message Broker addresses any enterprise connectivity requirements of the mobile applications.

Abhinav Priyadarshi (pabhinav@in.ibm.com), Technical Project Lead, WebSphere Message Broker Development team, IBM

Photo of Abhinav PriyadarshiAbhinav Priyadarshi is an Advisory IT Architect and Technical Lead for the IBM Integration Bus Development Team at the IBM India Software Lab in Bangalore. He has 12 years of experience with IBM. He develops new features and nodes for IBM Integration Bus, and provides consultancy on IBM Integration Bus Proofs of Concept, EAI design, and implementation for customers in India and the Asia-Pacific region. You can contact Abhinav at pabhinav@in.ibm.com.



Harish Shenoy (harish_shenoy@in.ibm.com), Solution Designer, WebSphere Worldwide Business Partner team, IBM

Photo of Harish S. ShenoyHarish Shenoy is an IBM Certified SOA Solution Designer with the IBM India WWW BP team, providing technical architecture for Application Connectivity and Application Infrastructure projects. His expertise includes IBM Mobile Platform, DataPower XC10, WebSphere Application Server, WebSphere eXtreme Scale, WebSphere Message Broker, and BPM. He is certified on WebSphere Application Server, WebSphere Message Broker, and WebSphere Process Server. You can contact Harish at harish_shenoy@in.ibm.com.


developerWorks Contributing author
        level

Ravi SK Sinha (ravssinh@in.ibm.com), Software Engineer, IBM

Photo of Ravi SinhaRavi SK Sinha is a Software Engineer with four years of experience in IBM product development and support. He currently works on the WebSphere MQ JMS Level-3 Support team. You can contact Ravi at ravssinh@in.ibm.com.



24 April 2013

Also available in Chinese

Introduction

IBM® WebSphere® Message Broker (hereafter called Message Broker) is widely used as an Enterprise Service Bus (ESB) to act as a flexible connectivity infrastructure for integrating applications, services, and systems. Message broker provides state-of-the-art infrastructure for any enterprise to match and route communications between services, convert between various transport protocols, transform between different data formats, and identify and distribute business events.

Worklight provides an advanced mobile application development and deployment platform for mobile devices. It helps organizations of all sizes to develop, run, and manage HTML5, hybrid, and native applications using a powerful and flexible mobile IDE, next-generation mobile middleware, end-to-end security, and integrated management and analytics capabilities. Worklight provides a cross-platform mobile application platform for enterprises so a minimum amount of code can be developed for a maximum set of mobile operating systems. Worklight Adapters are server-side components facilitate connections to various back-end systems via Cast Iron, HTTP, JMS, and SQL Adapters.

This article shows you how to develop hybrid mobile applications in IBM Worklight, and then integrate them with Message Broker to address any enterprise application connectivity requirements. The mobile application invokes an enterprise service deployed on Message Broker using the Worklight server. This article contains the following sections:

  1. Developing a message flow using Message Broker
  2. Developing Worklight Adapters
  3. Developing the mobile Worklight application
  4. Deploying the mobile Worklight application

The JK Financials Bill Payment sample application will be used to demonstrate the integration. The application has the following components:

  • A back-end bill-payment process implemented as a Message Broker message flow.
  • A Worklight HTTP Adapter that invokes the message flow with bill payment details. The HTTP Adapter is used because it provides connectivity with an HTTP application, and this scenario needs synchronous request/reply. In an asynchronous scenario, you could use JMS Adapter.
  • A hybrid Worklight application to get bill-payment details from the user for processing.

1. Developing a message flow using Message Broker

Begin by using the Message Broker Toolkit to develop a message flow to do the payment processing for the mobile application:

  1. Open the Message Broker Toolkit and create a message flow project with the following nodes: HTTPInput Node => Compute Node => Java Compute Node => HTTPReply Node.
  2. Rename the Compute node to ValidatePaymentDueDate and rename the Java™ Compute node to Convert XML to JSON.
  3. Set the HTTP Input Node URL as /test, as shown below:
    Figure 1
    Figure 1
  4. For the Message domain, select XMLNSC, and for the Input message select XML. The ESQL code ValidatePaymentDueDate below is for the Compute node to validate the bill due date. The bill payment is valid until the due date. After that, the validation fails and bill payments cannot be processed:
CREATE COMPUTE MODULE DevWorkSampleApp_ValidatePaymentDueDate
   CREATE FUNCTION Main() RETURNS BOOLEAN
   BEGIN
      -- CALL CopyMessageHeaders();
      --  CALL CopyEntireMessage();
   IF (CAST(InputRoot.XMLNSC.PaymentDetails.BillDueDate AS DATE) >= CURRENT_DATE) THEN
      SET OutputRoot.XMLNSC.Message.Status = 'Your Payment is validated successfully and 
         transaction is processed with bill amount :  ' 
         || InputRoot.XMLNSC.PaymentDetails.BillAmount;
      ELSE 
      SET OutputRoot.XMLNSC.Message.Status = 'Your Payment validation failed, 
         the due date is expired.' || InputRoot.XMLNSC.PaymentDetails.BillAmount;
      END IF;

      RETURN TRUE;
   END;

   CREATE PROCEDURE CopyMessageHeaders() BEGIN
      DECLARE I INTEGER 1;
      DECLARE J INTEGER;
      SET J = CARDINALITY(InputRoot.*[]);
      WHILE I < J DO
         SET OutputRoot.*[I] = InputRoot.*[I];
         SET I = I + 1;
      END WHILE;
   END;

   CREATE PROCEDURE CopyEntireMessage() BEGIN
      SET OutputRoot = InputRoot;
   END;
END MODULE;
  1. The following Java code in the JavaCompute Node Convert XML to JSON converts the XML message structure to JSON format, which will be returned to the invoking application. For the complete code, see the files WorklightFlow_XMLToJSON.java and Utility.java.
public void evaluate(MbMessageAssembly inAssembly) throws MbException {
      MbOutputTerminal out = getOutputTerminal("out");
      MbMessage inMessage = inAssembly.getMessage();

      // create new message
      MbMessage outMessage = new MbMessage();
      MbMessageAssembly outAssembly = new MbMessageAssembly(inAssembly,
         outMessage);

      try {
         copyMessageHeaders(inMessage, outMessage);

         MbElement jsonDataElement = outMessage.getRootElement().createElementAsLastChild
            (MbJSON.PARSER_NAME).createElementAsFirstChild(MbElement.TYPE_NAME);
         jsonDataElement.setName(MbJSON.DATA_ELEMENT_NAME);

         MbElement xmlnscElement = inMessage.getRootElement().getLastChild();
         if(null==xmlnscElement ){
            MbUserException mbue = new MbUserException(this, "evaluate()", "",
               "", "No body", null);
            throw mbue;
      }
  1. Finally connect the HTTPReply node and deploy the DevWorkSampleApp.msgflow on execution group.

2. Developing Worklight Adapters

In this section, you develop a Worklight Adapter to integrate the mobile bill-payment application with the Message Broker flow. The Worklight adapter invokes the message flow from the Worklight server. You create an HTTP Adapter to integrate with Message Broker. The Adapter receives the parameters from the mobile application client and invokes the message flow. The mobile application then invokes the Adapter, which invokes the Message Broker services.

  1. In Worklight Studio, right-click on Adapter and select New => Worklight Adapter, as shown below:
    Figure 2
    Figure 2
  2. For Adapter Type, select HTTP, and for Adapter Name, specify HTTPAdapterForBillPayment, as shown below. Click Finish.
    Figure 3
    Figure 3
  3. The HTTPAdapterForBillPayment.xml and HTTPAdapterForBillPayment-impl.js files are created under the HTTPAdapterForBillPayment folder. Use these files to specify the configuration for the Adapter and implement the logic to invoke the integration flow.
  4. Open HTTPAdapterForBillPayment.xml. In the Connectivity settings, set the Connection Policy, and change the Domain to localhost. These are the server details for Message Broker where this adapter needs to send data to the back-end HTTP server to process.
  5. Set the HTTP Server Port to 7080, as shown below in HTTPAdapterForBillPayment.xml.
  6. Add the Procedure Signature getPaymentDetailsAdpater, which will be implemented to invoke the Message flow.
<?xml version="1.0" encoding="UTF-8"?>
<wl:adapter name="HTTPAdapterForBillPayment"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xmlns:wl="http://www.worklight.com/integration"
   xmlns:http="http://www.worklight.com/integration/http">
   <displayName>HTTPAdapterForBillPayment</displayName>
   <description>HTTPAdapterForBillPayment</description>
   <connectivity>
      <connectionPolicy xsi:type="http:HTTPConnectionPolicyType">
         <protocol>http</protocol>
         <domain>localhost</domain>
         <port>7080</port>			
      </connectionPolicy>
      <loadConstraints maxConcurrentConnectionsPerNode="2" />
   </connectivity>
   <procedure name=>"getPaymentDetailsAdapter"/>
   </wl:adapter>
  1. Open the file HTTPAdapterForBillPayment-impl.js and implement the procedure in JavaScript to receive the mobile application client request and post it to the HTTP Server hosted on Message Broker
function getPaymentDetailsAdapter(name,billNumber,billDueDate,billAmount)
{
  /*
   * Construct input message in XML format or you can keep in default JSON format.
   */
  var inputMessage = '<PaymentDetails>'+ ' <Name>'+name+ '</Name>'+
  ' <BillNumber>'+billNumber+  '</BillNumber>'+' <BillDueDate>'+billDueDate+
   '</BillDueDate>'+' <BillAmount>'+billAmount+'</BillAmount>'+
   '</PaymentDetails>';
  /*
   * Construct Input object with post method which is to sent 
   */
  var input = {
         method : 'post',
         returnedContentType : 'json',
         path : 'test',
         body: {
            content:inputMessage.toString(),
            contentType:'text/xml'
         }
      };
 
      WL.Logger.debug("@@@"+input);
/ * Send input to HTTP Server hosted by Message Broker and wait for response.
  */
   response = WL.Server.invokeHttp(input);
   return response;
      WL.Logger.debug("@@@"+response);

      var type = gv1 input;  
      if ("object" == type)
      { 
         9if (true == response) 
      6{
// Drill down into the response object. 
         var results = response; 
         var result = results[0]; 
         WL.Logger.debug("@@@ result "+result);
         return result; // sent the result received from Broker to mobile app client
      6}
      6}
}
  1. You can test the Adapter procedure getPaymentDetailsAdapter by invoking it as shown in Figure 4:
    Figure 4.
    Figure 4

3. Developing the mobile Worklight application

  1. Open Worklight Studio and create a Worklight project: Select File => New => Worklight Project, as shown below:
    Figure 5
    Figure 5
  2. Select Hybrid Application in the project template and enter the Worklight Project Name as DevWorkSampleProject :
    Figure 6.
    Figure 6
  3. In the next screen, enter the Hybrid Application Name as DevWorkSampleApp, and then click Finish to create the DevWorkSampleApp project, as shown below. The Worklight hybrid application is created under the apps folder.
    Figure 7.
    Figure 7

The Worklight project is created and the file application-descriptor.xml is opened. It contains the application configuration details, including the server details where the application will be running in the property worklightServerRootURL. You can edit this property to provide the IP address and domain name for the Worklight server.

<?xml version="1.0" encoding="UTF-8"?>
<!-- Licensed Materials - Property of IBM 5725-G92 (C) Copyright IBM 2006, 2012. 
   All Rights Reserved. US Government Users Restricted Rights - Use, duplication or
   disclosure restricted by GSA ADP Schedule Contract with IBM -->
<!-- Attribute "id" must be identical to application folder name -->
<application id="DevWorkSampleApp" platformVersion="5.0.2" 
      xmlns="http://www.worklight.com/application-descriptor">
   <displayName>DevWorkSampleApp</displayName>
   <description>DevWorkSampleApp</description>
   <author>
      <name>application's author</name>
      <email>application author's e-mail</email>
      <homepage>http://mycompany.com</homepage>
      <copyright>Copyright My Company</copyright>
   </author>
   <height>460</height>
   <width>320</width>
   <mainFile>DevWorkSampleApp.html</mainFile>
   <thumbnailImage>common/images/thumbnail.png</thumbnailImage>
   <android version="1.0">
      <worklightSettings include="true"/>
      <security>
         <encryptWebResources enabled="false"/>
         <testWebResourcesChecksum enabled="false" 
            ignoreFileExtensions="png, jpg, jpeg, gif, mp4, mp3"/>
         <publicSigningKey>Replace this text with public key of the certificate
            with which you sign the APK. For details, see Worklight Developers 
            Reference Guide.</publicSigningKey>
      </security>
   </android>
   <blackberry version="1.0"/>
   <worklightServerRootURL>http://www.jkfinancial.com:8080</worklightServerRootURL>
</application>

When the Worklight application is created, Worklight by default creates an HTML page with the same name as the application name in Worklight Studio. In the project created above, you need to edit the page to add the UI components to obtain the details for the mobile application from the user. This example has text input fields to get the billing details from the customer. Here is the code forDevWorksSampleApp.html:

<!DOCTYPE html>
<html> <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, 
               initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, 
               user-scalable=0" />
            <title>DevWorkSampleApp</title>
            <link rel="shortcut icon" href="images/favicon.png" />
            <link rel="apple-touch-icon" 
               href="images/apple-touch-icon.png" />
            <link rel="stylesheet" href="css/DevWorkSampleApp.css" />
   </head>
   <body id="content" style="display: none">
         <h1 font face="Georgia, Garamond, Times New Roman" 
            color="#FF0000">
      JK Financial Bill Payment</h1>
         <h2 font face="Georgia, Garamond, Times New Roman" 
            color="#FF0000">
   Enter the bill payment details : </h2>
      <font face="Verdana, Tahoma, Arial" size="3">
      <form name="BillPaymentApp">
      <table border="0" cellpadding="0" cellspacing="0">
      <tr>
         <td width="100">Name:</td>
         <td><input type="text" name="txtName" 
            size="20"></td>
      </tr>
      <tr>
         <td width="200">Bill Number:</td>
         <td><input type="text" name="txtBillNumber" 
            size="15"></td>
      </tr>
      <tr>
         <td width="250">Bill Due Date(yyyy-mm-dd):</td>
         <td><input type="text" name="txtBillDueDate" 
            size="15"></td>
      </tr>
      <tr>
         <td width="100">Amount:</td>
         <td><input type="text" name="txtAmount" 
            size="15"></td>
      </tr>
         <tr>
      <td width="100"><br><br></td>
         <td>
            <input type="button" value="Submit" 
               onClick="getPaymentDetails()">
            <input type="button" value="Cancel" 
               onClick="">
         </td>
      </tr>
   </table>
</form>
</font>
   <script src="js/initOptions.js"></script>
      <script src="js/DevWorkSampleApp.js"></script>
      <script src="js/messages.js"></script>
   </body>
</html>

In the above HTML code, the getPaymentDetails() method is implemented in the DevWorkSampleApp.js JavaScript file in the js folder. This function takes the text values entered by the user and calls the Worklight Adapter created earlier to invoke the back-end process.

function getPaymentDetails()
{
   var name, billNumber, billDueDate, billAmount;
   name = document.BillPaymentApp.txtName.value;
   billNumber = document.BillPaymentApp.txtBillNumber.value;
   billNumber = document.BillPaymentApp.txtBillNumber.value;
   billDueDate = document.BillPaymentApp.txtBillDueDate.value;
   billAmount = document.BillPaymentApp.txtAmount.value;

var invocationData = {
      adapter: "HTTPAdapterForBillPayment",
      procedure: "getPaymentDetailsAdapter",
      parameters: [name, billNumber,billDueDate,billAmount]
WL.Client.invokeProcedure(invocationData, {
      onSuccess : getStatusDetailsSuccess,
      timeout : 500000,
      onFailure: function(){alert('Payment Request Failed for bill number '
         +billNumber +' Name : ' + name); 
      }
   });
}

function getStatusDetailsSuccess(result) {
      console.log("Entering getPaymentDetailsSuccess");
         try {
      if (result.status == 200) {

      var response1 = result.invocationResult; 
         alert("Status : " + response1.Message.Status); 
         var msg = res.get("Message");
            var billNumber = msg.get("billNumber");
         $('#billNumber').value = response1.Data.Message.billNumber;
      }
   } catch (e) {
         busyIndicator.hide();
      }  
}
}

4. Deploying the mobile Worklight application

  1. Right-click on each DevWorkSampleApp and Adapter created, and select Build and deploy. The application and Adapter will be deployed on Worklight Server. After the application is deployed, you can see the console messages, as shown below in Figure 8. You can add other environments such as Android, if the mobile applications need to be packaged for other mobile operating systems.
    Figure 8.
    Figure 8
  2. After deploying the application and Adapters, you can test the application using the Worklight console at http://<host>:8080/console:
    Figure 9.
    Figure 9
  3. Click on Preview as Common Resources, enter the values for the input options, and then click Submit:
    Figure 10.
    Figure 10
  4. The message flow is invoked using the Adapter, and a response is returned as shown below:
    Figure 11.
    Figure 11
  5. If the message flow is running in Debug mode on Message Broker, you can also see the details in Message Broker, as shown below:
    Figure 12.
    Figure 12

You can download the message flow project interchange file at the bottom of the article. You can then try this scenario by exporting the message flow project interchange file into the Message Broker Toolkit, and then deploying the flow into a Message Broker execution group.

Conclusion

This article showed you how easy it is to integrate a mobile application with a Message Broker flow using Worklight. The sample application involving a bill payment process can be extended for any type of existing Message Broker process that needs to be integrated with a new mobile application. Working together, Message Broker and IBM Worklight can address many requirements for integrating new mobile applications into the enterprise.


Downloads

DescriptionNameSize
Code sampleWorklight_Project.zip584 KB
Code sampleWorklight_WMB_IntegrationMsgFlow.zip10 KB

Resources

  • IBM Worklight resources
    • Getting started with IBM Worklight
      Step-by-step guidance with self-paced modules, exercises, and code samples to show you how to set up Worklight and start using it to develop mobile apps.
    • IBM Worklight V5.0.5 information center
      A single Web portal to all IBM Worklight documentation, with conceptual, task, and reference information on installing, configuring, and using IBM Worklight.
    • Worklight demo
      Learn how to easily create a mobile app using an orchestration created in WebSphere Cast Iron Cloud and then calling it in IBM Worklight using the Cast Iron Adapter type.
  • WebSphere Message Broker 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=877680
ArticleTitle=Integrating mobile applications with WebSphere Message Broker using IBM Worklight
publish-date=04242013