Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Web and WebWorks Development

LAB – Create a typical mobile enterprise application using the BlackBerry® WebWorks SDK, AJAX, JSON, web services and MySQL

by Retired on ‎02-25-2011 09:45 AM (8,073 Views)

Introduction

Enterprise solutions typically involve mobile applications running on a BlackBerry® smartphone which are integrated somehow with a "back end" enterprise system. In this article and associated practical work, we will see how developing with the BlackBerry® WebWorks™ SDK makes it easy to create BlackBerry smartphone applications which are integrated with back end systems such as databases, using standard technologies and techniques such as AAJX, JSON and Web Services.


Note that the server elements of the lab are based on Java®, the Apache Tomcat™ application server and the MySQL database. If you're completely unfamiliar with these components, this may be a challenging lab for you (but if you're feeling brave, give it a try anyway). If you know your way around these products already, you should find this a useful but straightforward exercise.

Objectives

After completing this lab you will be able to:

  • Create a BlackBerry web application which can interact with a backend system such as a database via a web services interface
  • Use AJAX techniques from within your BlackBerry web application when interacting with web services
  • Use the JSON data format with your web application
  • Pass data between different pages of your web application

Prerequisites

Scenario

In this lab, we will develop version one of a mobile application called “Mobile Engineer”. The use cases that the application supports centre around the activities of engineers whose work requires them to travel to different locations and to repair, inspect or service various types of industrial equipment. There’s a simple workflow that applies, and the engineers must change the status of the “job records” that they are assigned and provide other feedback, as they progress through the workflow and whilst they are “in the field”.

“Job records” which describe an item of work to be carried out by a specified engineer, are maintained in a central, enterprise MySQL RDBMS. The “Mobile Engineer” application is to be integrated with this database so that these records can be viewed and updated by engineers.

Our appplication will consist of two screens; a home screen which lists the jobs assigned to the engineer and a job details screen which is displayed when one of the jobs listed on the home screen is selected, shows more information about the job and allows the engineer to change the job’s status and send feedback to the MySQL database. Screenshots from the provided solution follow:

figure1.png 

figure2.png 

Figure 1 – The home screen listing the engineer's jobs

Figure 2 - The job details screen

 


Solution Architecture

The BlackBerry web application that we shall develop in this lab is a part of an overall solution architecture which is depicted below:

 figure3.png

 

Our focus will of course be the development of the BlackBerry web application. An implementation of a simple web service, written in Java and using the Apache Axis™ 2 framework is provided in the solution part of this lab, along with a MySQL schema. You are free to develop your own web service using the technology of your choice provided it exposes a suitable interface and you are prepared to make adjustments to your  web application code to accommodate any differences. The remainder of this lab is written assuming you are using the web application and MySQL database schema that are supplied.

Our Mobile Engineer application will utilise AJAX (Asynchronous Javascript® and XML) to make calls to our web service using the SOAP (Simple Object Access Protocol). Results from our web services calls will be returned to our application in the JSON (JavaScript Object Notation) format since this is a format which is less verbose than XML and lends itself well to easy parsing and manipulation from JavaScript.

We’ll be using the Eclipse® IDE in this lab, put you may prefer to use Microsoft® Visual Studio® instead. Note that if you use this tool, you will not be able to work with the Java based web service implementation provided with the lab solution. Eclipse users will be able to work with both the mobile engineer BlackBerry web application and the associated web service from within a single Eclipse workspace.

Setup

 

This lab requires Apache Tomcat with Apache Axis 2 and JSON support and a MySQL database. If you happen to already have these items installed and working on your machine, you can skip this section. Otherwise, you have some work to do to set up a suitable testing environment. In summary, we need to accomplish the following:

- Set up a database and some test data

- Set up the Apache Tomcat application server
- Install and configure Apache Axis 2 so that Tomcat can expose standard Java objects as web services
- Install components which allow SOAP requests to be dynamically mapped to JSON format by Apache  Axis2
- Install a JDBC driver so our web service can interact with our database
- Deploy the sample web service supplied with this lab

After this, the BlackBerry WebWorks development fun can begin.

So, work through the following steps to install and configure the testing environment required for this lab.

1. Database

We’ll start by setting up the engineering jobs database. If you don’t already have it installed, download and install MySQL Community Edition version 5.1. You can obtain it from:

http://dev.mysql.com/downloads/mysql/

It is assumed in the remainder of this lab, that you have installed MySQL on the same machine as your Eclipse environment and your application server.

We next need to create the mobile engineer database and to populate it with some test data. You can use the mysql command line client from a suitable shell, or you can use the MySQL Query Browser or MySQL Workbench, either of which may be a little easier to use. The Query Browser can be obtained from:

http://dev.mysql.com/downloads/gui-tools/5.0.html

The solution folder contains a file called MobileEngineerService\database\schema.sql. Open this file in a text editor. Now, using the SQL client of your choice, connect to MySQL as the “root” user, supplying the password you specified during installation:

 

figure4.png

 

From the SQL command line, execute the commands contained within the schema.sql file, copying and pasting one at a time or executing the whole file as a script, as you prefer.

Check that everything worked as expected by executing the SQL command:

 

                select * from jobs;

 

You should see 5 records returned by this query.

 

2. Application Server and Web Services Interface

This lab utilises Apache Tomcat as a web applicaton server, and hosts a web service which is written as a POJO (Plain Old Java Object) which it exposes as a SOAP based web service using the Apache Axis2 framework. Tomcat is set up to support the JSON data format by installing a library called Jettison. If you’re not familiar with any of these products, don’t worry…. feel free to use whatever products, tools and technologies you are most comfortable with here. Setting up is not too difficult however and basic instructions follow:

 

2.1 Install Apache Tomcat
Download and install Apache Tomcat 6.0. It’s available from http://tomcat.apache.org/
To install, simply unpack the archive onto your hard drive. I installed in the root directory of my C drive:

tomcat1.png

 

2.2 Configure Apache Tomcat
At this stage we will make only one change to the default configuration. Change the port that Tomcat listens on for HTTP requests from the default of 8080 to something else such as 9090. This is to avoid clashing with the BlackBerry® MDS simulator which also uses 8080. Do this by editing the Tomcat server.xml file in the conf\ directory and changing the element shown:

tomcat2.png

 

2.3 Add web services support to Apache Tomcat
The Apache Axis 2 framework should now be installed within Tomcat. This will enable Tomcat to expose Java objects as web services.
Download Apache Axis 2 from http://ws.apache.org/axis2/
Extract the contents of the archive to your local hard drive. I extracted to the root of my C drive once again.
The Apache Axis 2 distribution includes a web archive file (a WAR file) which makes it very easy to deploy Apache Axis to your Tomcat server. Find the war file within your Apache Axis 2 directory:
 axis1.png

 

Now copy the war file to your Tomcat webapps directory:

 

axis2.png

 

Start Tomcat by running the bin/startup.bat script (or startup.sh for *nix users). You should see the war file automatically expanded in the webapps directory. Stop Tomcat.

 

2.4 Add JSON support to Apache Tomcat
To add support for the JSON format, we will use the Jettison implementation. Download the jettison-1.2.jar jar file from here:
http://jettison.codehaus.org/Download
Copy the jettison-1.2.jar file into the webapps\axis2\WEB-INF\lib sub-directory of your Tomcat installation. If you don’t see these directories then make sure you copied the axis2.war file into the webapps directory per the previous step and that you started and then stopped Tomcat. Starting Tomcat should cause the war file to be expanded.
 
jettison1.png

 

Your final set-up task prior to testing your Tomcat server is to configure Apache Axis2 so that it uses Jettison to dynamically reformat SOAP responses using JSON. Note that there are various ways of mapping XML to JSON, some of which are supported by Jettison. We will use the “badgerfish” scheme.
Find the axis2.xml configuration file and open it in your text editor. It should be in yout Tomcat \webapps\axis2\WEB-INF\conf directory as shown:

axis3.png

 

Find the messageFormatters element and add a new messageFormatter child element identical to this one (you can paste it straight into your axis2.xml file):

 

<messageFormatter contentType="application/json/badgerfish" 
      class="org.apache.axis2.json.JSONBadgerfishMessageFormatter"/>

 The messageFormatters element should now look something like this:

 

axis4.png

 

Next, find the messageBuilders element and add the following child element to it:

 

<messageBuilder contentType="application/json/badgerfish" 
      class="org.apache.axis2.json.JSONBadgerfishOMBuilder"/>

 The messageBuilders element should now look something like this:

 

axis5.png

 

Now download the dynamic response module for Apache Axis2 from here:
http://dist.wso2.org/maven2/org/wso2/dynamicresponse/wso2dynamic-response/1.5/wso2dynamic-response-1...
Install the mar file in webapps\axis2\WEB-INF\modules:

axis6.png

 

And finally, add the following entry to your axis2.xml file in the Global Modules section:

 

 

    <module ref="DynamicResponseHandler"/>

The Global Modules section should now look something like this:

 

axis7.png 

 

 

3. JDBC Driver

Download the MySQL JDBC driver from http://dev.mysql.com/downloads/connector/j/
Expand the archive and copy the MySQL connector jar file into the \jre\lib\ext directory of your Java JDK installation directory:

mysql1.png 

 

 

4. Web Application and Web Service

Create a standard Java  project in Eclipse called MobileEngineerService and copy the source files contained within solution\MobileEngineerService\src to your project’s src\ folder.

Copy the solution\MobileEngineerService\build.xml file into the root of your new Eclipse project also. This is a configuration file for use with the Ant build automation tool.

Open build.xml in the Eclipse text editor. Inspect and if necessary, change the property definitions at the head of the file to correctly reflect the locations of your Apache Axis 2 and Tomcat installations.

OK, let’s deploy and test our MobileEngineerService to make sure it’s ready for us to proceed with the development of our BlackBerry web application. With Tomcat running, in Eclipse, right click on the build.xml file and select Run As/Ant Build… (note the “…” at the end of the menu item). From the dialogue that appears, select the deploy.service target only and click the Run button.

 

figure5.png

 

If all goes well, the Eclipse console will show “BUILD SUCCESSFUL”.

Perform the following checks from within a standard web browser such as Windows® Internet Explorer® or Mozilla® Firefox® (it is assumed you have Tomcat running on the same machine as your web browser and listening on port 9090):

 

 

4.1 Basic Tomcat / Axis health checks

Go to http://localhost:9090/axis2/ . Click the Validate link and check the results look OK. Click the Services link. The services page should include the MobileEngineerService with three available operations listed:

 

figure6.png

 

4.2 MobileEngineerService test

In your browser, go to the following URL:

 

http://localhost:9090/axis2/services/MobileEngineerService/getNewWork?args0=1&response=application/j...

 

This should result in a JSON formatted response from the server. How your browser handles this depends on which browser you are using. The content of the response should be similar (if not identical) to that which is shown in Appendix A.

Assuming you were successful with all the preceding setup steps, we can now move on to developing our BlackBerry web application!

 

Starter and Solution Files

 

There are starter and solution files associated with this lab.  The starter files can be found in the install_folder\Labs\Lab_MobileEngineer\starter folder and the solution files are in the install_folder\Labs\Lab_MobileEngineer\solution folder.

The starter folder should contain the following:

 

  • index.html and details.html starter files
  • json2.js in the actions folder
  • style.css in the css folder
  • app_icon.png, status0_tl.png, status1_tl.png and status2_tl.png in the img folder.

 

The solution folder contains the complete source code for the MobileEngineer BlackBerry web application and the supporting web service.

Estimated time to complete this lab: 120 minutes


Exercise

 

1. Creating the Eclipse Project

Create a new BlackBerry web application Project in the same Eclipse workspace you used for the MobileEngineerService. Call this project MobileEngineerweb application and accept all defaults whilst creating the project. From the lab starter folder, copy the following items into your project’s folder and refresh the project in Eclipse:

                The actions folder;

                The css folder;

                The img folder;

                Files index.html and details.html;

After refreshing your Eclipse project, it should like the following screenshot when viewed in the Navigator View:

 

 figure7.png

 

2. Developing the home screen

The MobileEngineer home screen lists the jobs allocated to our engineer. Each item listed must be a hyperlink which when clicked, causes the details screen for the selected job to be displayed. We’ll achieve these bevaviours by triggering some JavaScript from the index.html onLoad event and the JavaScript will make an AJAX call to our web service, parse the JSON formatted response and dynamically insert html elements into our index.html screen to create the links that are required. Note that Appendix A contains an example of the JSON format response which your web application will receive from the web service.

To begin, open the index.html file in the Eclipse HTML Editor.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

  <meta name="viewport" id="viewport"

      content="initial-scale=1.0,user-scalable=no">

  <link rel="stylesheet" type="text/css" href="css/style.css" />

  <title>Mobile Engineer web application</title>

</head>

<body>

  <h2>Mobile Engineer</h2>

  <img src="img/app_icon.png"/>

</body>

</html>

 

Make the following changes to this file:

  1. Modify index.html so that  it loads the two JavaScript files “actions/actions.js” and “actions/json2.js”. Note that we will create the actions.js file shortly.
  2. Add an onLoad attribute to the <body> tag and set it to execute a JavaScript function  called “getWork()”.
  3. Add an empty <table> element which has an id of “jobs” and border size 0 within the body of the page.

Your page should now look like this:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" id="viewport"
	content="initial-scale=1.0,user-scalable=no">
<SCRIPT type="text/javascript" src="actions/actions.js"></SCRIPT>
<SCRIPT type="text/javascript" src="actions/json2.js"></SCRIPT>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>Mobile Engineer Widget</title>
</head>
<body onLoad="getWork()">
<h2>Mobile Engineer</h2>
<img src="img/app_icon.png"/>
<table border="0" id='jobs'>

</table>
</body>
</html>

 

Next we’ll write the JavaScript which loads our data into the empty table in the index.html page. It will need to make a call to our web servces operation “getNewWork”, parse the JSON formatted response and then insert rows into the  <table> element, each one containing a link derived from the data relating to one job record returned from the database. Proceed as follows:

 

-  In Eclipse, create a JavaScript source file called actions/actions.js

- Write a JavaScript function which POSTs a request to the following URL using AJAX :

 

http://"+ip+":9090/axis2/services/MobileEngineerService/getNewWork?args0=1&response=application/json...

 

Your function must provide a callback function which the AJAXrequest can invoke as Ajax events take place. For now, just include simple code which uses alert statements to indicate success or failure of the call where the request.readystate attribute is 4 (which means “DONE”).  Include a global variable called ip which has the IP address of your web service assigned to it. Do not use 127.0.0.1.

 

Your actions.js file will now look something like this:

// set the IP address of your web service endpoint here

var ip="10.131.217.55";

function postGetWork(url) {

      var request = new XMLHttpRequest();

      var params = '';

      request.onreadystatechange = function() {

            if (request.readyState == 4) {

                  if (request.status == 200) {

                        alert("HTTP 200 OK calling web service");

                  } else {

                        if (request.status == 500) {

                              alert("HTTP 500 Error calling web service");

                        }

                  }

            }

      };

      request.open('POST', url, true);

      // with POST you must set certain request headers

      request.setRequestHeader('Content-type',

                  'application/x-www-form-urlencoded');

      request.setRequestHeader('Content-length', params.length);

      request.setRequestHeader('Connection', 'close');

      request.send(params);

}

function getWork() {

      postGetWork("http://"+ip+":9090/axis2/services/MobileEngineerService/getNewWork?args0=1&response=application/json/badgerfish");

}

 

Test your web application by right clicking on your project in Eclipse and selecting Run As BlackBerry Simulator. Make sure you have your simulator configured to start the MDS simulator automatically.

You *should* get an HTTP 500 error from this test. The reason for this error is that the BlackBerry® web application must grant access to any remote domains accessed by the web application using the config.xml document. Open the config.xml document in the Eclipse BlackBerry web application Config Editor and add the wildcard “*” domain to the list of whitelisted domains:

 

figure8.png

 

 

Note that for a production application it is strongly recommended that you do *not*use the wildcard domain and instead grant access to the specific domains which your web application must access specifically and solely.

Test your web application again. This time you should get an HTTP 200 response which indicates that the web service operation is being invoked. If not, check your Tomcat logs for errors.

Next we’ll modify our actions.js JavaScript file to parse the response from the web services call and use this data to dynamically insert links into the <table> element of our index.html page by interacting with the DOM.

Change the AJAXcallback function to call a function called writeJobTable in the event that we receive a HTTP 200 response. Pass this function the responseText attribute of the request object. Your callback function in the postGetWork function should now look like this:

      request.onreadystatechange = function() {

            if (request.readyState == 4) {

                  if (request.status == 200) {

                        writeJobTable(request.responseText);

                  } else {

                        if (request.status == 500) {

                              alert("HTTP 500 Error calling web service:"+request.statusText);

                        }

                  }

            }

      };

 

Now let’s write the new function. This actually breaks down into the following sub-tasks and you may wish to implement separate functions accordingly:

  1. Parse the JSON data in the request using JSON.parse. The actions/json2.js script contains the parse function and this loads our data into a JavaScript variable called “getNewWorkResponse” which itself contains an associative array with each row having the name “return”. These names were generated by Apache Axis 2 by the way.
  2. We need to iterate through the associative array and for each “return” element, and dynamically construct and insert a row into our page’s <table> element. Each row should contain two columns, the first of which contains an image and the second of which contains a link.
  3. In the first column, select from either img/status0_tl.png, img/status1_tl.png or img/status2_tl.png depending on the value of the status field for this record.
  4. In the second column, we need a link which is per the following:

      var link = '<a class="joblink" href="details.html?job_id='+job_id+

                 '&customer_name='+customer_name+

                 '&customer_address='+customer_address+

                 '&date_accepted='+date_accepted+

                 '&date_started='+date_started+

                 '&work_instruction='+work_instruction+

                 '&status='+status+

              '">'+customer_name+'</a>';

This link, when selected, will cause our second screen to open and will pass across details of the selected job record. We’ll get to that later.

Your code may of course vary, but here are example implementations of the various functions needed to achieve these steps:

First, the writeJobTable function:

 

function writeJobTable(response_data) {

	job_data = JSON.parse(response_data);
	var num = job_data['ns:getNewWorkResponse']['ns:return'].length;
	for (i = 0; i < num; i++) {
		insertRow(
				job_data['ns:getNewWorkResponse']['ns:return'][i]['ax21:job_id']['$'], 
				job_data['ns:getNewWorkResponse']['ns:return'][i]['ax21:status']['$'], 
				job_data['ns:getNewWorkResponse']['ns:return'][i]['ax21:customer_name']['$'],
				job_data['ns:getNewWorkResponse']['ns:return'][i]['ax21:customer_address']['$'],
				job_data['ns:getNewWorkResponse']['ns:return'][i]['ax21:date_accepted']['$'],
				job_data['ns:getNewWorkResponse']['ns:return'][i]['ax21:date_started']['$'],
				job_data['ns:getNewWorkResponse']['ns:return'][i]['ax21:work_instruction']['$']
		);
	}
}

 

 

writeJobTable calls a function “insertRow” for each row found in the associative array. This function, with the help of other functions, manipulates the DOM to insert the required rows in our table:

function insertRow(job_id,status, customer_name, customer_address, date_accepted, date_started, work_instruction) {

                var row = document.getElementById('jobs').insertRow(0);

                var status_cell = row.insertCell(0);

                status_cell.innerHTML = getStatusIcon(status);

                var cname_cell = row.insertCell(1);

                cname_cell.innerHTML = getDetailsPageLink(job_id, status, customer_name, customer_address, date_accepted, date_started, work_instruction);

}

 

 

 

The utility functions called by insertRow are as follows:

function getStatusIcon(status) {

                var icon_name = 'img/status' + status + '_tl.png';

                var icon_url = '<img src="'+icon_name+'"/>';

                return icon_url;

}

function getDetailsPageLink(job_id, status, customer_name, customer_address, date_accepted, date_started, work_instruction) {

                var link = '<a class="joblink" href="details.html?job_id='+job_id+

                           '&customer_name='+customer_name+

                           '&customer_address='+customer_address+

                           '&date_accepted='+date_accepted+

                           '&date_started='+date_started+

                           '&work_instruction='+work_instruction+

                           '&status='+status+

                           '">'+customer_name+'</a>';

                return link;

}

 

Test your web application. You should see a screen very much like the following in the BlackBerry® simulator:

 figure9.png

 

The white region in the bottom half of the screen is due to the fact that we have not set our web application’s background colour to match that of the style sheet we’re using (css/style.css). Do this by opening the config.xml document and setting the background colour to #000000.

 

figure10.png

 

Test again and your web application should look correct:

 

figure11.png

 

We’ve implemented our first screen! Let’s move on to the details screen now.

 

3. Developing the job details screen

The job details screen lists various attributes of a job selected from the home page and allows the engineer to either change the job’s status, submit a comment relating to the job or both. A web services call sends the engineer’s updates to the backend system and into the MySQL database. The web services interface has an operation “updateJob” for this purpose.

To start, open the details.html file and familiarise yourself with it, in particular the form it contains:

<form method="post" action="">

    <table border="0" id='job_details'>

    </table>

    <table border="0" id='job_update'>

       <tr>

          <td>

             Status:

          </td>

          <td>

            <SELECT>

              <OPTION SELECTED VALUE="0">Accepted</OPTION>

              <OPTION VALUE="1">Started</OPTION>

              <OPTION VALUE="2">Finished</OPTION>

            </SELECT>

          </td>

       </tr>

       <tr>

          <td>

             Comments:

          </td>

          <td>

             <input size="40" maxlength="40" value="" >

          </td>

          <td>

       </tr>

       <tr>

          <td>

          </td>

          <td>

             <input value="Submit" onclick="updateJob()">

          </td>

          <td>

       </tr>

                </table>

</form>

As can be seen, the form includes two tables, one of which is empty at this stage. We will dynamically insert into this table, details of the selected job record with attribute names in the first column and values in the second.

There’s also a button which when clicked, will invoke a JavaScript function called “updateJob()” and it is this function which will submit the changes to the web service.

Let’s start by populating our empty table with job record attributes. We need this to take place as soon as our page is loaded, so add an onLoad attribute to the body of details.html which will invoke a JavaScript function called loadJobDetails().

 

<body onLoad="loadJobDetails()">

 

Now let’s implement loadJobDetails() in our actions.js file. We actually need to do three things here:

  1. Extract the job record’s attributes from the URL which caused details.html to be loaded. Since we’re dealing with a URL, some of the parameters will need to be processed by the JavaScript unescape function to remove the URL encoding. You should use the BlackBerry web application API blackberry.utils.parseURL function and the getURLParameter function in your solution. Consult the SDK documentation for details of these functions but please note the following; early releases of the web application SDK and associated simulators do have a known issue in this area which affects the parsing of URLs which refer to locally stored resources within the web application itself. The SDK documentation explains this and the solution illustrates how to work around this issue.
  2. Insert a series of rows into our empty table, which has an ID of “job_details”
  3. Select the correct initial value in the the drop down list which contains the job’s status to the right.

Since we’re going to use one of the BlackBerry web application SDK API functions, we need to add the relevant package to the web application Permissions for our project. Open the config.xml document, click on the web application Permissions tab and add the blackberry.utils package  to the Local domain.

 

figure12.png

 

Let’s implement the JavaScript functions required to extract our URL’s parameters into global JavaScript variables now. Your code should look similar to the following:

 

 

// global variables to hold our job data

// attributes of a single job

var job_id;

var status;

var customer_name;

var customer_address;

var date_accepted;

var date_started;

var work_instruction;

 

function getJobDetailUrlParameters() {

                var url_string = window.location.toString();

// workaround known issue with parseUrl by editing the URL to include a hostname

                var url_with_host = "local://localhost/";

                url_string = url_with_host + url_string.substring(9,url_string.length);

                var url = blackberry.utils.parseURL( url_string );

                work_instruction = url.getURLParameter('work_instruction');

                date_accepted = url.getURLParameter('date_accepted');

                date_started = url.getURLParameter('date_started');

                customer_address = url.getURLParameter('customer_address');

                customer_name = url.getURLParameter('customer_name');

                status = url.getURLParameter('status');

                job_id = url.getURLParameter('job_id');

}

 

function loadJobDetails() {

                // extract the job's attributes from the URL

                getJobDetailUrlParameters();

}

 

Add an alert statement to your code to display the global variables you just extracted and check that all is well so far. Once you have tested, let’s move on to insert these details into the job_details table in our form. This involves similar manipulation of the DOM to that which was used to populate the index.html page. Example code as follows:

function insertJobDetail(label,value) {

                var row = document.getElementById('job_details').insertRow(0);

                var cell_label = row.insertCell(0);

                cell_label.innerHTML = label;

                var cell_value = row.insertCell(1);

                cell_value.innerHTML = value;

}

function insertJobDetailsInTable() {

                insertJobDetail("Instruction:",unescape(work_instruction));

                var ds = "";

                if (status > 0) {

                                ds = extractDate(date_started);

                }

                insertJobDetail("Started:",ds);

                insertJobDetail("Accepted:",extractDate(date_accepted));

                insertJobDetail("Address:",unescape(customer_address));

                insertJobDetail("Customer:",unescape(customer_name));

                insertJobDetail("ID:",job_id);

} 

function loadJobDetails() {

                // extract the job's attributes from the URL

                getJobDetailUrlParameters();

                // insert these attributes as rows in our empty table

                insertJobDetailsInTable();

}

function extractDate(datetime) {
 if (datetime.length > 9) {
  return datetime.substring(0,10);
 } else {
  return datetime;
 }
 return datetime;
}

 

Test your web application. You should see details of the selected job appear in the page.

Now let’s make sure the drop down status list has the right value selected when the page loads. Modify your web application so that it manipulates the job_status element accordingly.

function setStatusSelection() {

                var status_list = document.getElementById("job_status");

                var status_option = document.getElementById( "status"+status );

                status_option.selected = true;

}

function loadJobDetails() {

                // extract the job's attributes from the URL

                getJobDetailUrlParameters();

 

                // insert these attributes as rows in our empty table

                insertJobDetailsInTable();        

                // set the status drop down to the right selected value

                setStatusSelection();

}

 

Test your web application again, selecting various different jobs from the home page. The drop down list’s initial value should vary according to the status of the record you select.

Finally, let’s implement the web services call which will send our update to the database. Once again, this involves using AJAX and posting a request.  This time we’ll invoke the updateJob operation and we’ll navigate back to the home page afterwards. Modify your JavaScript to post the following request using similar AJAX code to that which we used to obtain the list of jobs shown on the home page:

 

http://"+ip+":9090/axis2/services/MobileEngineerService/updateJob?args0="+job_id+"&args1="+status+"&...

 

Here’s an example of what’s required:

function postUpdateJob(url) {

                var request =  new XMLHttpRequest();

                var params = '';

                request.onreadystatechange = function() {

                                if (request.readyState == 4) {

                                                if (request.status == 200||request.status == 202) {

                                                                alert("Job status updated OK");

                                                                window.history.back();

                                                } else {

                                                                if (request.status == 500) {

                                                                                alert("HTTP 500 Error calling web service:"+request.statusText);

                                                                }

                                                }

                                }

                };

                request.open('POST', url, true);

                // with POST you must set certain request headers

                request.setRequestHeader('Content-type',

                                                'application/x-www-form-urlencoded');

                request.setRequestHeader('Content-length', params.length);

                request.setRequestHeader('Connection', 'close');

                request.send(params);

}

function updateJob() {

                var status = document.jobform.job_status.value;

                var comment = document.jobform.comment.value;

                postUpdateJob("http://"+ip+":9090/axis2/services/MobileEngineerService/updateJob?args0="+job_id+"&args1="+status+"&args2="+comment);

}

 

That’s it! You’ve just implemented a BlackBerry® web application which is integrated with a typical backend system using web services.

 

Review

In this exercise you built a BlackBerry web application which was part of a fairly typical enterprise solution, with a backend database and an application server providing a web services interface. You used AJAX to asynchronously invoke the web service and you parsed and made use of data which was returned by the web service in the JSON format. JSON is a relatively lightweight format and so good for mobile applications.

 

 

Appendix A – Sample JSON format output

 

{"ns:getNewWorkResponse":
  {"@xmlns":
    {"ns":"http:\/\/ws.mobileengineer.fictionalcompany.com","ax21":"http:\/\/data.mobileengineer.fictionalcompany.com\/xsd"},
     "ns:return":[
       {
         "@xmlns":{"xsi":"http:\/\/www.w3.org\/2001\/XMLSchema-instance"},
         "@xsi:type":"ax21:WorkRecord",
         "ax21:address_latitude":{"$":"51.672545"},
         "ax21:address_longitude":{"$":"-0.176339"},
         "ax21:customer_address":{"$":"33 Industrial Road, Manchester"},
         "ax21:customer_name":{"$":"Smith & Co."},
         "ax21:date_accepted":{"$":"2011-02-04T10:04:04.000Z"},
         "ax21:date_completed":{"@xsi:nil":"true"},
         "ax21:date_started":{"$":"2011-02-04T10:04:04.000Z"},
         "ax21:engineer_comment":{"$":""},
         "ax21:engineer_id":{"$":"0"},
         "ax21:job_id":{"$":"1"},
         "ax21:job_report":{"$":""},
         "ax21:status":{"$":"1"},
         "ax21:work_instruction":{"$":"Repair main duct"},
         "ax21:work_latitude":{"$":""},"
         ax21:work_longitude":{"$":""}
       },
       {
         "@xmlns":{"xsi":"http:\/\/www.w3.org\/2001\/XMLSchema-instance"},
         "@xsi:type":"ax21:WorkRecord",
         "ax21:address_latitude":{"$":"52.935397"},
         "ax21:address_longitude":{"$":"-1.483154"},
         "ax21:customer_address":{"$":"66 Factory Street, London"},
         "ax21:customer_name":{"$":"British Something PLC"},
         "ax21:date_accepted":{"$":"2011-02-04T10:04:04.000Z"},
         "ax21:date_completed":{"$":"2011-02-04T10:44:52.000Z"},
         "ax21:date_started":{"@xsi:nil":"true"},
         "ax21:engineer_comment":{"$":""},
         "ax21:engineer_id":{"$":"0"},
         "ax21:job_id":{"$":"2"},
         "ax21:job_report":{"$":""},
         "ax21:status":{"$":"2"},
         "ax21:work_instruction":{"$":"Install size 17 fan"},
         "ax21:work_latitude":{"$":""},
         "ax21:work_longitude":{"$":""}
       }
     ]
   }
}
Contributors
Users Online
Currently online: 20 members 1,813 guests
Please welcome our newest community members: