Access all areas

This article was originally published in VSJ, which is now part of Developer Fusion.
With the introduction of the iPhone and iPod Touch devices from Apple, the era of multi-purpose mobile data access devices has finally arrived. The cross-over from mono-purpose music-playing gadgets has been phenomenally successful, creating a high demand for these devices from a wide spectrum of users worldwide. Under the hood, they have powerful processors running a fully featured multi-tasking operating system supporting industry standard web access technologies – including a full TCP/IP stack, WiFi, mobile network data access, and full web browser/email client capabilities. Add to this foundation a fashionable touch-sensitive input interface, a sleek industrial design with high sex appeal, affordable pricepoint, long battery life, and a pocket-pleasing form factor that even Agent Bond would envy, and you have a formidable mobile software delivery platform in the making.

This article shows you how to create applications for this platform using software development technologies that you’re probably already familiar with. You will create a small contact management application to access corporate backoffice relational databases, and make that data available anytime, anywhere, to a user with an iPod Touch or iPhone.

Mobile high-performance low-power devices

Similar in processor hardware, the iPod Touch and iPhone are highly extensible iPod mobile devices that run a general purpose CPU and multi-tasking operating system (Mac OS X) inside. Current models feature a low power ARM 1176 32 bit processor running at 533 MHz with built-in hardware acceleration for video and audio operations. Because of this powerful underpinning, the promise of custom application development on the operating system level practically guarantees an endless stream of innovative applications from third party developers. Apple plans to address this market with a Software Development Kit (SDK) that will become available in February 2008.

Beyond the usual music, video, photo and podcast playing features, the iPod Touch/iPhone also include Internet connectivity via a fully-featured Safari browser and standard WiFi connectivity. This enables developers to get busy writing functional web applications for the mobile devices without waiting for the availability of the SDK. Web applications run purely within the control of the Safari web browser, and don’t require low level access to the operating system at all. Furthermore, there exists very rich tools support for development of web applications from established vendors. For example, you can readily use your Java EE development environment to create applications for execution on iPod Touch or iPhone. The support for web applications on these devices are rock solid, thanks to the Safari browser, which in turn is based on the open source WebKit engine project. This mature open source project provides a browser engine that is compliant to the current HTML 4.01, JavaScript (ECMAScript 3), W3C DOM Level 2, and CSS 2.1/CSS3 standards – ensuring that your web application will run well on these mobile devices.

A Contact Manager web app

This article shows a contact manager application example that enables you to access data residing in your back-office databases over WiFi, at any location where you can connect via your iPhone.

You will be using familiar Java EE 5 development tools, such as the Eclipse IDE, the Spring framework and the Hibernate JPA provider, to put the application together.

Figure 1 provides a high level view of the application that you will create.

Figure 1
Figure 1: A high level view of the application

The actual contact data is hosted on a MySQL database, hypothetically located in your back office. A ContactServer is created that access the contact information as objects via the Spring 2 Framework’s JPA support. The JPA provider used in this case is the Hibernate JPA provider. The contact objects fetched from the database are made available over the Intranet to the front-end server. The communications between the ContactServer and the DataService is via standard Java RMI (Remote Method Invocation). The RMI remoting support of the Spring 2 framework is used by the ContactServer to make the objects available.

The front-end server is a Tomcat 5.5 server running a DataService servlet. This server hosts the Ajax based web application – utilizing HTML, JavaScript, and CSS. It also hosts a front-end servlet that services data fetch requests from the Ajax application. The returned data from this front-end servlet is in XML/HTML format.

To simplify the programming of the Ajax application, the de facto standard Prototype JavaScript framework is used. In addition, to perform smooth sliding animation of contact information, the glider.js script from Scripteka is used. This script, in turn, depends on the Prototype JavaScript Framework, and the effects.js from Scriptaculous.

For a more thorough discussion of the ContactServer, and three-tiered systems in general, see A multi-tiered Java application with GWT from the last issue of VSJ. You can also learn a lot more about the design, coding and setup of the ContactServer in this article. While the reference article focuses on the use of the Google Web Toolkit (GWT), this article’s focus is on creating the Ajax application for execution on the iPod Touch/iPhone.

Fitting in with iPhone look and feel

The Safari browser on the iPhone/iPod Touch can work with web pages of any arbitrary size. However, to navigate around a large web page on the small device screen can be a hassle for the user – making your application unfriendly and less likely to be used by the user. Apple provides some very strong and specific guidelines for designing the look and feel of your iPhone applications.

For the contact application, we try to mimic the user interface of the built-in Address Book application as much as possible. This is good practice since the user is likely to be familiar with the use of the built-in application and can transfer the knowledge to your web application. The physical display resolution of these devices is 320 by 480 pixels. However, there are fixed elements in the Safari browser that make the visible design area slightly smaller.

Figure 2 shows the usable design area when Safari is used with the URL text field visible.

Figure 2
Figure 2: The standard Safari layout

The web application makes use of a DOM trick to scroll away and hide the URL text field, providing an extra 60 pixels for use by the application. See Figure 3.

Figure 3
Figure 3: The layout used for the application

The JavaScript method that carries this out is the shiftTop() function, with the method to scroll away the URL text highlighted.

function shiftTop() {
	window.scrollTo(0, 1);
	list_contacts();
}

Components of the Ajax Application

Table 1 shows the files that make up the Ajax client-side application that runs on the iPhone Safari. The pages for this application are served by the Tomcat 5.5 server. In this case, the Tomcat server acts only as a web server.

Table 1: iPhone Safari Ajax files
File Description
index.html The main layout area of the Ajax application. It defines the various named <div> elements that will be manipulated by the Ajax JavaScript coding through the browser’s DOM. This is the page that the application loads by default.
vsjcontact.css A CSS defines the look of the visual elements of the application. This stylesheet attempts to follow Apple’s web application layout guideline as much as possible. All visual elements in the application are stylized via this stylesheet.
vsjcontact.js This is where the programming logic for the Ajax application resides. Calls to the Prototype framework and the glider.js script are made from here. Asynchronous calls to the servlet for contact information are also made via functions in this file.
js/prototype.js, js/effects.js, js/glider.js These are open source JavaScript framework and libraries used by the application.
images/boxback.png, images/gradback.png, images/leftbutton.png, images/singpix.gif Graphical images used in creating the user interface. The boxback.png and gradback.png are actually images used in tiling the background of the elements in the user interface.

Flow of the Application

Once you locate the files that make up the Ajax application, you can use this section as your guide to the flow through the application.

First, when the URL http://<host>/DataService is reached by a user on an iPhone, the Tomcat 5.5 server looks for a welcome page to display, and it finds index.html.

The index.html file sets the size of the display using an iPhone specific viewport meta tag, highlighted below:

<!DOCTYPE HTML PUBLIC
	"-//W3C//DTD HTML 4.01//EN">
<html lang="en">
	<head>
		<meta name="viewport"
				content="width=device-width,
				height=416 user-scalable=no" />
		<title>VSJ Contacts</title>
This tag ensures that the page is scaled properly, and prevents user-controlled manual scaling from distorting the user interface.

This page also applies the CSS stylesheet and loads the JavaScript files in the <head> element:

<head>
	...
	<style type="text/css">
		@import './vsjcontact.css';
	</style>
	<script src="./js/prototype.js"
		type="text/javascript">
	</script>
	<script src="./js/effects.js"
		type="text/javascript">
	</script>
	<script src="./js/glider.js"
		type="text/javascript">
	<script>
	<script src="./vsjcontact.js"
		type="text/javascript"></script>
</head>
When loading the vsjcontact.js script, an onload handler function is registered. This function is the shiftTop() function shown in earlier discussion. The function is called once the index.html page loading completes. This function scroll away the URL text field of Safari and reclaims 60 pixels of visible space, and it also calls list_contacts() function as the last step. The list_contacts() function fetches contact information from the ContactServlet (actually the uk.co.vsj.iphone.ContactServlet class in the source code) and then uses the browser’s DOM to make them visible as a list on the index.html page. The code is shown in the following listing:
function list_contacts(){
		if (loading == 0){
			new Ajax.Request(
				'./ContactServlet',
			{
				method:'get',
				onSuccess: function(transport){
					loading = 0;
					show_contacts(
						transport.responseText);
				},
				onLoading: function(){
					window.scrollTo(0, 1);
					loading = 1
				}
			});
		}
	}
The highlighted code is an asynchronous call, via the Prototype JavaScript Framework, to the servlet for contact data. Since the call is asynchronous, it returns immediately. The work that you want it to do is specified via the onSuccess: function. In this case, a call to show_contacts() is made when the servlet returns with the contact data some times later.

Note that browser safety restricts the location of the data producing URL – in this case, the URL ./ContactServlet maps to a servlet running on the same Tomcat 5.5 server as the application. In fact, if you look into the WEB-INF/web.xml deployment descriptor, you will see the mapping:

<servlet>
	<description>
		A servlet to supply iphone with
		contact data from back office RDBMS
	</description>
	<display-name>
		ContactServlet
	</display-name>
	<servlet-name>
		ContactServlet
	</servlet-name>
	<servlet-class>
		uk.co.vsj.iphone.ContactServlet
	</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>
		ContactServlet
	</servlet-name>
	<url-pattern>
		/ContactServlet
	</url-pattern>
</servlet-mapping>
The servlet returns the list of contacts as HTML fragment. The general format of the returned data is:
<div class="contact"
		onclick="get_contact('1');">
	<div class='text'>
		<b>Li</b> Sing
	</div>
</div>
<div class="contact"
		onclick="get_contact('2');">
	<div class='text'>
		<b>Smart</b> Robert
</div>
...
This HTML fragment contact data is supplied as a text argument to the show_contacts() function when it is called upon the completion of the asynchronous request. show_contacts() displays the contacts as a list by changing the innerHTML property of the <div> element with the id of list_area:
function show_contacts(text) {
	back_button = $('back');
	back_text = $('back_text');
	head_text = $('headtext');
	back_display = back_button.style;
...
	back_display.display = 'none';
	back_text.innerHTML = '';
	$('list_area').innerHTML = text;
	showingdetails = false;
}
This flow is how the list of contacts, shown in Figure 4, is populated with all the contact names from the MySQL database.

Figure 4
Figure 4: A contact list

Displaying Contact Details

Every contact name displayed in the list is specified with the following servlet generated HTML <div> element:
<div class="contact"
	onclick="get_contact('1');">
	<div class='text'>
		<b>Li</b> Sing
	</div>
This means that when the contact name is touched by the user, the get_contact() function is called with the corresponding id of the contact. The get_contact() function makes an asynchronous call to the ContactServlet, this time supplying the id as a request parameter. This code is highlighted in the following listing:
	function get_contact(contactid){
		if (loading == 0) {
			new Ajax.Request(
				"./ContactServlet?ID=" +
					 contactid,
			{
				method:'get',
				onSuccess: function(transport){
					loading = 0;
					show_details(
			transport.
	responseText);
				},
		onLoading:
			function(){
	window.scrollTo(
				0, 1);
			loading = 1;
				}
			});
		}
	}
When the servlet is called with a request parameter named ID, it fetches the details of the contact from the ContactServer and returns an HTML fragment that shows the contact details (similar to the case with the contact list). This HTML fragment is passed to the show_details() function. The show_details() function replaces the HTML of the <div> element with id details_area, rendering the details of the selected contact. The contact_glider is used in this case to “glide in” the newly populated <div>.
function show_details(text){
	back_button = $('back');
	back_text = $('back_text');
	head_text = $('headtext');
	back_display = back_button.style;
	back_display.display = 'block';
	head_text.innerHTML = 'Info';
	back_text.innerHTML = 'Contacts';
	$('details_area').innerHTML = text;
	contact_glider.moveTo(
		contact_glider.sections[1],
		contact_glider.scroller, {duration:
		contact_glider.options.duration});
	 showingdetails = true;
	}
Figure 5 shows the application with the contact details displayed by the show_details() function gliding in the <div>.

Figure 5
Figure 5: Contact details displayed

Handling the Go Back button

Once the contact details are shown, as in Figure 5, a user can click the Contacts button in the top right hand corner to go back to the list. This is a user interface detail that Apple’s design guidelines recommend.

To implement this button click behavior, index.html contains the <div>:

<div id="back"
		style="display: none;"
		onclick="back_clicked();">
	<div class="back_text"
		id="back_text">
	</div>
</div>
The show_details() method makes the button visible with the highlighted code.
function show_details(text){
	back_button = $('back');
	back_text = $('back_text');
	head_text = $('headtext');
	back_display = back_button.style;
	back_display.display = 'block';
	head_text.innerHTML = 'Info';
	back_text.innerHTML = 'Contacts';
	$('details_area').innerHTML = text;
	contact_glider.moveTo(
		contact_glider.sections[1],
		contact_glider.scroller,
		{duration: contact_glider.
			options.duration});
	showingdetails = true;
}
When the button is clicked, the back_clicked() function is called. This function uses the contact_glider to glide back the list of contacts. The title is changed back to “VSJ Contacts”.
function back_clicked(){
	back_button = $('back');
	back_text = $('back_text');
	head_text = $('headtext');
	back_display = back_button.style;
	if (showingdetails){
		showingdetails = false;
		contact_glider.moveTo(
			contact_glider.sections[0],
			contact_glider.scroller,
			{duration: contact_glider.
				options.duration});
		back_text.innerHTML = '';
		head_text.innerHTML='VSJ Contacts';
		back_display.display = 'none';
		}
}

Trying out the application

There are two separate Eclipse projects for this application – the ContactServer and the DataService. To try out the application, you need to:
  1. Make sure the MySQL server is installed and running, a database named vsjdb must be created and available; a user named dbuser must be able to access the database (edit the META-INF/context.xml file of the ContactServer project if you need to change user).
  2. In Eclipse, open the ContactServer project, and seed the contact data by running the SeedData configuration (select menu Run->Open Run Dialog…, then select SeedData on the left and click the Run button)
  3. In Eclipse, start the RMI based ContactServer by running the RunService configuration
  4. With the ContactServer running, open the DataService project in Eclipse. Highlight the DataService project, right click and select Run As.. –> Run on Server…. Then select Tomcat 5.5 as the server to run (you may need to setup a server runtime if Tomcat 5.5 is not setup already).
  5. From an iPhone or iPod Touch, start the Safari browser and access the URL:
    http://<IP address of the Tomcat
    	server>/DataService
At this point, you should see the contact list as shown back in Figure 4. Touch a contact to see its detail gliding in. When the details of the contact are shown, you can touch the Contacts button at the top left to go back to the list.

Conclusions

Finally, it is possible to deliver on the long elusive mobile data access promise – the ability to access your entire corporate information assets easily and conveniently anywhere and anytime.

Apple successfully created the iPod touch and iPhone family, providing tiny yet powerful terminal devices with ubiquitous wireless connectivity, a fully-featured browser, and a killer user interface with a features set that contemporary users crave. This innovation single-handedly realized the hardware side of the equation, leaving the software side of the equation at your disposal.

Leveraging on this work, you can create highly interactive data access applications harvesting corporate data from databases and other legacy data source, deploying robust and proven backoffice technology such as Java EE 5.


Sing Li has been writing software, and writing about software, for twenty plus years. His specialties include scalable distributed computing systems and peer-to-peer technologies. He now spends a lot of time working with open source Java technologies. Sing’s most recent publications include Professional Geronimo and Professional Apache Tomcat from Wrox Press.

You might also like...

Comments

About the author

Sing Li United States

Sing Li has been writing software, and writing about software for twenty plus years. His specialities include scalable distributed computing systems and peer-to-peer technologies. He now spends ...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“It works on my machine.” - Anonymous