Java IoT Authors: Zakia Bouachraoui, Yeshim Deniz, Carmen Gonzalez, Elizabeth White, Pat Romanski

Related Topics: Java IoT

Java IoT: Article

Java Unplugged

Java Unplugged

The Web is moving to wireless and Java is making it happen! How is a wireless environment different from the Web? What languages are used for wireless devices and what features do they have? Most important, what role does the Java 2 Enterprise Edition (J2EE) play in a wireless architecture?

Wireless vs Web
There are several key differences between clients in a Web world and those in a wireless world. For example, in the wireless world network connections have a lower bandwidth and a higher latency than a typical Internet connection. Also, wireless connections are unstable and unpredictable since they're built on a wireless network - a fact you're likely familiar with from your cell phone service! The Wireless Access Protocol (WAP) was created to address network computing in this restricted environment. It defines two key aspects of wireless communication: an end-to-end application protocol and an application environment.

As shown in Figure 1, the WAP's end-to-end application protocol is built on three major components: an application server, a WAP gateway and a wireless device. The WAP gateway is responsible for routing and translating WAP data on the wireless network to and from HTTP data on a TCP/IP-based network such as the Internet. Some WAP gateways even convert HTML to languages that WAP-enabled devices can understand in a process called transcoding. The end-to-end aspect of the WAP protocol consists of four layers carried by various bearers or providers. Figure 2 compares the WAP protocol stack with a typical Internet one.

In addition to the end-to-end application protocol, the WAP specification also defines the application environment. This environment consists of a WML browser for rendering content and a script interpreter for executing applications on the user device. The Wireless Markup Language (WML) defines the content to be rendered by the browser using WMLScript as the scripting language. This is analogous to the Internet environment in which HTML is rendered by the browser and JavaScript is the scripting language.

The application environment was included in the WAP specification to ensure that the myriad of WAP-enabled devices can execute the same applications. No doubt you're familiar with browser compatibility problems on the Internet. Imagine if every cell phone manufacturer created their own proprietary browser - there would be hundreds maybe thousands of different browsers. What a mess!

WML and WMLScript
WML is similar to HTML in its structure and elements. However, two major distinctions are worth mentioning. The first is that WML is a subset of XML and all the rules regarding standard XML apply. This means that the entire WML document must be well formed and adhere to a DTD that describes all WML documents. The second is that WML provides extremely limited control over presentation. If you thought HTML was restrictive, wait until you start playing with WML. These severe restrictions allow for flexibility on the rendering device. Only the lowest common denominator can be assumed across all client devices. It's not just missing attributes in WML tags. Even the rendering of individual tags can appear radically different on different phones. The model for WML rendering, however, is quite similar to Java's approach. Each platform has the freedom to determine how to render a particular widget, as long as it achieves the intended functionality in a manner consistent for that platform. Although the language definition and functionality is rigid to ensure compatibility, the implementation is loosely defined to enable support for a wide variety of devices.

WMLScript is analogous to JavaScript as it's executed on the client browser. WMLScript provides a basic set of libraries to perform string manipulation, math functions, URL facilities and interaction with the WML browser. Additional libraries are being developed that allow the WMLScript programmer to access telephony aspects of the device, such as dialing a phone number or accessing the phonebook. WMLScript's purpose is to provide a richer user environment over static WML.

The easiest way to begin learning both WML and WMLScript is to work with an example. Listing 1 is an extremely simple business model: purchasing your favorite java-based product, such as a cup of coffee or a latte. A user can select the items for purchase, calculate the total and check out. The basic application flow is shown in Figure 3. The code was developed and simulated under Nokia's WAP SDK (see "References" for links).

Let's look at the code for the main WML page in Listing 1.

  • Lines 1-2: Standard XML syntax that indicates this document is XML and conforms to the DTD specified at http://www.wapforum.org/DTD/wml_1.1.xml.

  • Line 3: The root of a WML document is the <wml> element, similar to the <html> element of an HTML document. Since it's an XML document, it must be well formed. Without the <wml> element and the corresponding element at line 39, the document won't be processed.

  • Line 4: The basic working unit of a WML document is a card. A WML document, or deck, can be composed of one or more cards. Each card is completely self-contained and represents an individual interaction with the user. Due to the high latency inherent in wireless connections, a collection of related cards is transmitted in one deck to improve overall performance for the end user.

    Each card must have a unique identifier specified by the ID attribute. A title for the card can be specified as well. The title is usually displayed across the top of the screen, but that can change due to the creative liberty the browser takes during rendering. The newcontext attribute indicates that each time this card is entered, any variable or state should be reset. Since this first card is a splash screen, it's a good place to reset any variables that may be lingering in the context of the browser.

    The final attribute is set in line 4 in the ontimer attribute. The value for the ontimer attribute is a URL, which can be either a complete location, such as http://java.sun.com, or simply a bookmark that references another card in this deck, such as #main. In this case, when a timer expires within this card, the user will be directed to the card identified as "main."

  • Line 5: This single line sets the timer referred to in line 4. The value for this tag indicates a length of time in tenths of a second until the timer expires. Once the timer expires, the ontimer event is triggered.

  • Lines 6-13: This looks like standard HTML. The display tags of WML are extremely similar to HTML, although they're severely restricted when it comes to adjusting the display of data. For example, there's no tag to set the vertical alignment of the columns within a table. However, if you're familiar with HTML, you can probably jump right into writing WML display logic.

    Although HTML and WML provide functionality for displaying images, the WML specification only allows for WBMP image types. Many freeware converters and plug-ins can convert existing image files into WBMP format. However, since most phones are monochromatic, images that are converted from a high-resolution color source may need some tweaking in order to display nicely.

  • Line 15: This is the beginning tag for the main card in our application.

  • Lines 17-18: Here are our first input elements. Unlike HTML, there's no need for a <form> tag to enclose your input fields. Later on we'll see how these elements make it into the next request. For now, these input elements set the value of local variables within the browser context. The name of the variable is indicated by the name attribute in the input tag. These variables can be displayed elsewhere on the page with the syntax $(variablename). To display a single dollar sign, a double dollar sign ($$) is used.
    It's worth mentioning the format attribute for an input tag. This attribute indicates to the rendering device what sort of character patterns are acceptable as input. For example, the format mask in line 17 indicates that an arbitrary number of alphanumeric characters may be entered, whereas the format mask in line 18 indicates that only four characters may be entered. Format masks may also contain characters to be inserted into the input field. These characters are indicated by prefixing the character with a \ in the format mask. For example, the format mask "NNNNN\-NNNN" could be used to format a zip code entry field by supplying a dash between the first five numbers and the last four numbers during entry.

    The final attribute used for input elements is the title element. It's often used when entry for an input field actually takes place on a special edit screen. The WML browser can display this title on that screen for identification purposes.

  • Lines 19-25: The <select> element, also similar to HTML, provides a selection list that enables multiple selections as determined by the multiple attribute. In this example we want our clients to be able to purchase more than one item at a time, so the multiple attribute is set to true. Enclosed within the select element are the various choices or options to be displayed. The text within the element is displayed to the user, while the value attribute indicates the value assigned to the variable that's defined by the name attribute in the select tag. For a multiple selection element the values will all be placed into this variable with semicolon delimiters.
  • Line 26: This line displays the contents of the totalPurchase variable. Since we haven't defined it yet, the rendering agent will display a blank value. We'll update this variable using WMLScript in just a bit.

  • Lines 27-29: The <do> tag is one of the few action tags available in WML. The type attribute indicates what sort of action is required. This value determines which physical button should be linked to this action. You don't have much control over which button is chosen. On most phones the accept type used in this example is linked to the OK button on a mobile phone. Other types include prev, help and delete. Enclosed within the <do> tag is the action to be performed - in this case, to navigate to another URL. This is actually a call to a WMLScript function, so we'll hold off.

  • Lines 30-36: We have another <do> tag here with the same action type, which is perfectly legal; the user agent determines how to render it. On many cell phones it's rendered by providing a menu to select which action to perform when the button linked to this type is pressed. Here we're navigating to a different URL. The method attribute indicates whether we're performing a GET or a POST operation to this URL. And a new tag is enclosed within the <go> tag. The <postfield> tag is used to add data to a request string. The name/value pairs are provided as attributes to the <postfield> tag, and it's up to the WML browser to properly add these to the request as a query string in the case of a GET or as data fields for a POST.
At this point we have a nearly functional application. The only mysterious functionality is the URL defined in line 28, which doesn't look like a standard HTML or WML page location. This location is actually the syntax for calling a WMLScript function. The first part of the location, JavaCafe.wmls, identifies the location of the WMLScript library in which the function is contained. The second part of the URL, #calculateTotal, identifies the function we want to call. The final part of the URL, ('$(purchase)'), passes along the value of the variable purchase as a parameter to this function. The actual syntax of WMLScript is fairly similar to JavaScript, so let's look at Listing 2 to see what the JavaCafe.wmls code is doing.
  • Line 1: It declares the method signature for this function. The keyword extern indicates that this function may be called from outside this package, similar to the public keyword in Java. Our function takes a single parameter named inputPurchase. It's not necessary to declare the type of the parameter since WMLScript is a weakly typed language. Data is converted automatically from one data type to another on the fly by the script execution engine.

  • Lines 2-4: Declare and initialize three variables. Again, variables are weakly typed so no data types are required. The function call in the initialization of the purchase variable translates the escaped character string required by HTTP back into a standard string. For example, %20 is translated back into a space character.

  • Lines 5-17: This simple "for" loop iterates over the values in the purchase variable that are separated by semicolons. The elements method counts the number of elements in the string separated by the provided delimiter. The elementAt method returns the nth element of the string delimited by the provided delimiter. The "if" block is then used to calculate the total price of the order.

  • Line 18: This is the key of the entire script. The call to WMLBrowser.setVar sets the value of a variable in the scope of the WML browser to the supplied value. Here we're changing the value of the totalPurchase variable, which is displayed in line 25 of JavaCafe.wml. The String.format method, which is similar to the C function printf, is used to perform basic message formatting.

  • Line 19: The call to WMLBrowser.refresh() causes the WML browser to redisplay the current card with the latest variable information. However, this refresh is performed on the browser side. No trip back to the server is required.

A look at this example shows the similarities between WML/WMLScript and HTML/JavaScript to be fairly obvious. Although WML/WMLScript doesn't provide as much functionality as HTML/JavaScript, the basic purpose of each technology remains the same. WML and HTML are used for displaying a page of information, while WMLScript and JavaScript allow for a more interactive user experience within a page. However, one question remains: How do we generate dynamic content for the WML decks?

JSPs, Servlets and Wireless Devices
Although there are many variations within J2EE architectures, in general, JSPs develop presentation-oriented dynamic content and servlets process user input and perform conditional navigation. Ideally, all your business logic would be located outside the JSPs and servlets in either EJBs or pure Java classes. Once the business logic tier is written, different presentation layers, such as WAP, can provide the interface to the business logic.

This paradigm is extremely applicable in current Internet technology. Many businesses operate transactional HTML sites. If their business logic is kept separate from the presentation logic, providing a new presentation layer such as WAP while still using a common layer for business functionality is a fairly straightforward process.

A few simple changes need to be made to enable our JSP/Servlet engine to serve up JSPs to a wireless device. The first set of changes must be made to the Web server that serves up the output of the JSP/Servlet engine in order to recognize the new MIME types for the content being displayed. Table 1 shows the typical MIME types.

To set the proper MIME type the next change must be made to the pages or decks. We can rename JavaCafe.wml from Listing 1 to JavaCafe.jsp and simply add the following code after line 2:

<%@ page contentType="text/vnd.wap.wml" %>
After these changes, your JSP/Servlet engine shouldn't have a problem serving up JSPs to a simulated WAP device. Of course, to serve up these responses to an actual WAP device you'd need a WAP gateway that linked your network to the cellular network. However, the JSP/Servlet engine setup would remain the same.

Using servlets in this model is just as simple. For example, the Check Out action (see Listing 3) directs the user to a servlet, then returns a simple WML deck with a Thank You message that includes the user's name. The user's name was retrieved as a field posted in the request to this URL. It's a simple modification to change this servlet to interact with any existing Java purchase logic. However, keeping in line with the clean separation of business and presentation logic, this servlet could also make calls to the business tier to perform the required business logic for checkout, then redirect to a JSP page to produce the presentation to be returned to the mobile user.

Industry Support
Nearly every application server on the market is moving to support wireless in some fashion. At the most basic level, any Web server or JSP/Servlet engine can become WAP-enabled simply by defining the MIME types discussed above. However, many application servers are beginning to offer transcoding-type services. Transcoding services provide a semi- to fully automatic way to convert existing HTML or XML pages to WML. The idea is that by using a transcoding application server, your existing site will be available to any wireless device with a minimal amount of modification to existing code. Many application server vendors are also partnering with wireless vendors to provide a complete end-to-end wireless technology stack in a single solution.

The Internet revolution has spawned billions if not trillions of dollars in new revenue streams. This is due in large part to the huge number of previously isolated people who are now empowered by the PC and the Internet to communicate in an easy and effective manner. Wireless technology extends the Internet's entry point beyond the PC. The number of wireless phones is predicted to surpass the number of land-based phones within the next three years. Most of them will be connected to some sort of wireless data service, which in turn will be connected to the Internet. The impact of this vast number of Internet clients is unimaginable. However, the implementation success that Java has had in the B2B and B2C space easily translates over to the wireless paradigm. In terms of scalability, reliability and maintainability, all the J2EE features can still be used in nearly the same way. Although it's certain that wireless architectures will evolve over time, Java will be there to help blaze the way.


  1. Nokia's WAP information center, free SDK available: www.nokia.com/corporate/wap
  2. Home of the WAP specification: www.wapforum.org
  3. Great repository of information on wireless technology: www.AnywhereYouGo.com
  4. Another excellent wireless developer portal site: www.phone.com

More Stories By Kristian Cibulskis

Kristian Cibulskis is the CTO of Vertica Systems, which provides XML and Java based data integration solutions for clinical trials. He also holds a BS in computer science from Cornell University.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

IoT & Smart Cities Stories
Blockchain is a new buzzword that promises to revolutionize the way we manage data. If the data is stored in a blockchain there is no need for a middleman - the distributed database is stored on multiple and there is no need to have a centralized server that will ensure that the transactions can be trusted. The best way to understand how a blockchain works is to build one. During this presentation, we'll start with covering the basics (hash, nounce, block, smart contracts) and then we'll crea...
As the fourth industrial revolution continues to march forward, key questions remain related to the protection of software, cloud, AI, and automation intellectual property. Recent developments in Supreme Court and lower court case law will be reviewed to explain the intricacies of what inventions are eligible for patent protection, how copyright law may be used to protect application programming interfaces (APIs), and the extent to which trademark and trade secret law may have expanded relev...
History of how we got here. What IoT devices are most vulnerable? This presentation will demonstrate where hacks are most successful, through hardware, software, firmware or the radio connected to the network. The hacking of IoT devices and systems explained in 6 basic steps. On the other side, protecting devices continue to be a challenging effort. Product vendors/developers and customers are all responsible for improving IoT device security. The top 10 vulnerabilities will be presented a...
Never mind that we might not know what the future holds for cryptocurrencies and how much values will fluctuate or even how the process of mining a coin could cost as much as the value of the coin itself - cryptocurrency mining is a hot industry and shows no signs of slowing down. However, energy consumption to mine cryptocurrency is one of the biggest issues facing this industry. Burning huge amounts of electricity isn't incidental to cryptocurrency, it's basically embedded in the core of "mini...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Atmosera delivers modern cloud services that maximize the advantages of cloud-based infrastructures. Offering private, hybrid, and public cloud solutions, Atmosera works closely with customers to engineer, deploy, and operate cloud architectures with advanced services that deliver strategic business outcomes. Atmosera's expertise simplifies the process of cloud transformation and our 20+ years of experience managing complex IT environments provides our customers with the confidence and trust tha...
Where many organizations get into trouble, however, is that they try to have a broad and deep knowledge in each of these areas. This is a huge blow to an organization's productivity. By automating or outsourcing some of these pieces, such as databases, infrastructure, and networks, your team can instead focus on development, testing, and deployment. Further, organizations that focus their attention on these areas can eventually move to a test-driven development structure that condenses several l...