Lab : Network Security



Wireless Java with J2ME

Telecommunications Program

Wireless Java with J2ME

Part I: Objective

The goal of this lab is to introduce the student to a Java programming for wireless devices such as mobile phone and the personal digital assistants (PDAs). Student will learn about the programming with Java 2 Platform, Micro Edition (J2ME) wireless toolkit. Basic graphic user interface example is introduced and converted into Palm OS application.

Part II: Equipment List

1. A personal computer with Windows OS

2. A handheld device (Palm Pilot or Handspring Visor) with Palm OS 3.5 or higher with at least 4 MB memory

3. Java 2 Standard Edition Development Kit (JDK) Version 1.4.2 or higher

4. Java 2 Micro Edition Wireless Toolkit Version 2.2 or higher

5. IBM WebSphere Micro Environment Toolkit Software

6. Palm Desktop software

7. Any text editor of your choice

Part III: Introduction

The popularity of cellular phones and personal digital assistants and their increasing capability suggests that more people will adopt these small devices and use them extensively in daily life. However, these devices have limited capabilities such as small display screen, limited memory, and low end computing processors. The applications running on these devices have to be programmed differently from normal computer applications. Fortunately, there is a simple way to develop the applications for small mobile devices using Java language and mobile device emulator. An application created in Java for mobile devices is called a MIDlet. Developing MIDlets consists of the following steps [1]:

1. Write the MIDlet code in Java language.

2. Compile the MIDlet’s source code into Java byte code.

3. Preverify the MIDlet’s .class file to ensure that non-support commands are not included in the program.

4. Package the application in a Java Archive (JAR) file.

5. Create a Java Application Descriptor (JAD) file to describe the Java application.

These steps can be done manually using the command-line technique (e.g., in Part IV) or done with an integrate development environment called KToolbar which is part of the J2ME Wireless Toolkit (e.g., in Part V). The life cycle of a MIDlet is shown in Fig. 1. The cycle consists of paused, active, and destroyed states. The list of methods in the code is denoted on the arrows from one state to another state.

[pic]

Figure 1: MIDlet State Transitions [1]

The source code of all MIDlets consists of four main parts: the constructor part, the start-application part, the pause-application part, and the destroy-application part. The MIDlet skeleton is shown below.

import javax.microedition.midlet.*;

public class MyMIDlet extends MIDlet {

public MyMIDlet() {

// constructor

}

public void startApp() {

// entering active state

}

public void pauseApp() {

// entering paused state

}

public void destroyApp(boolean unconditional) {

// entering destroyed state

}

}

Developing applications for mobile devices should adhere to the followings guidelines [1]:

• Use local variables instead of fields. Accessing local variables is quicker than accessing class members.

• Minimize unnecessary method calls

• Avoid string concatenation. That is avoiding object creation and garbage collection. Reduce memory usage.

• Minimize object creation. Try to recycle objects. Considering passing in a reference to returning object and modifying its values.

• Avoid synchronization. If an operation takes longer than a fraction of a second to run, consider placing it in a separate thread.

Before Getting Started:

Before starting the lab, please do the followings:

1. Delete the following directories (if exists) on PC.

• C:\WTK22\apps\hellomidlet

• C:\WTK22\apps\testgui

• C:\WTK22\apps\fetchpagemidlet

2. Delete the “testgui” application (if exists) on Palm device.

1. Tap Home icon

2. Tap the clock display located at the top left of the screen and then choose “Delete”

3. Select “testgui” and then tap “Delete” button to delete the testgui application from a palm device.

[pic]

Part IV: Procedure for Manual Development (Optional)

This part introduces a procedure to develop a MIDlet application manually using a command-line technique. You may skip this part and continue at Part V (developing a MIDlet application with KToolbar). However, you are recommended to read through this part.

1. Setup System Parameters

For Windows OS

SET PATH = %PATH%; C:\wtk22\bin

SET J2MEWTK_HOME = C:\wtk22

SET MIDPAPI = %J2MEWTK_HOME%\lib\midpapi10.jar;

%J2MEWTK_HOME%\lib\cldcapi10.jar

SET J2MECLASSPATH = %J2MEWTK_HOME%\wtklib\kenv.zip; %J2MEWTK_HOME%\wtklib\kvem.jar; %J2MEWTK_HOME%\wtklib\lime.jar

2. Hello World Example

Use any text editor to input following code and save the file name as “HelloMidlet.java.”

import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

public class HelloMidlet extends MIDlet {

private Display display;

TextBox box = null;

public HelloMidlet() {

}

public void startApp() {

display = Display.getDisplay(this);

box = new TextBox("Simple Example", "Hello World", 20, 0);

display.setCurrent(box);

}

public void pauseApp(){

}

public void destroyApp(boolean unconditional){

}

}

3. Compile and Verify Java Code

3.1 Create a directory to hold a compile Java’s .class file:

c:\current_dir> mkdir tmpclasses

3.2 Create a directory to hold a verified Java’s .class file:

c:\current_dir> mkdir classes

3.3 Compile the MIDlet from command line without any debugging info and set the appropriate boot and J2ME classpath and put the result in \tmpclasses:

For Windows OS

C:\current_dir> javac –g:none –d tmpclasses –bootclasspath

%MIDPAPI% -classpath %J2MECLASSPATH% HelloMidlet.java

3.4 Preverify java code

For Windows OS

C:\current_dir>c:\wtk22\bin\preverify –classpath %MIDPAPI%;

tmpclasses -d classes tmpclasses

4. Create Manifest file and Compress Java Code

Change the current directory into \classes directory and use text editor to create the following file saving it as HelloMidlet.mf.

Manifest-Version: 1.0

MIDlet-1: Hello,,HelloMidlet

MIDlet-Name: HelloMidlet

MIDlet-Version: 1.0

MIDlet-Vendor: PITT

MicroEdition-Profile: MIDP-1.0

MicroEdition-Configuration: CLDC-1.0

Change the current directory into \classes directory and compress the .class file together with the manifest file (.mf) using the jar command.

For Windows OS

classes> jar cvfm HelloMidlet.jar HelloMidlet.mf

HelloMidlet.class

5. Create Java Application Descriptor (JAD) file

Use text editor to create the following file and save it as HelloMidlet.jad. Find the MIDlet-Jar-Size from the size of the real file by using command “dir” in the command line prompt and enter the correct Size in this file.

MIDlet-1: Hello,,HelloMidlet

MIDlet-Name: HelloMidlet

MIDlet-Version: 1.0

MIDlet-Vendor: PITT

MIDlet-Jar-URL: HelloMidlet.jar

MIDlet-Jar-Size: 930

MicroEdition-Profile: MIPD-1.0

MicroEdition-Configuration: CLDC-1.0

6. Run the Application on Mobile Phone Emulator

Make sure that you are in \classes directory and enter following command:

For Windows OS

>c:\wtk22\bin\emulator –Xdescriptor:HelloMidlet.jad

Use your mouse to click on the select button in the emulator.

[pic] [pic]

Figure 2: Mobile Phone Emulator with the HelloMidlet.class

Part V: Procedure for Development with KToolbar

This section introduces a simpler method to develop a MIDlet application using the J2ME Wireless Toolkit and the same source code of HelloMidlet.java (see source code in Part IV)

1. Starting KToolbar

For Windows OS

• Choose Start ( Programs ( J2ME Wireless Toolkit ( KToolbar.

2. Create New Project

For Windows OS

• Click on the New Project button and enter the Project Name “hellomidlet” and fill in the MIDlet Class Name as “HelloMidlet” (must be the same name as the .java file name).

• Click on the Create Project button. A window of settings for project “hellomidlet” will pop up.

3. MIDlet Attributes

A setting project window will pop up after the creation of the project. The user can modify both required and optional attributes by selecting the tabs.

For Windows OS

• Change the Target Platform drop-down menu from JTWI to MIDP1.0.

• Accept the default setting for both required and optional attributes by clicking on OK button.

4. Source Code Directory

The original KToolbar screen will provide the information of the directory that the user should put the source code and the resource files.

For Windows OS

• Copy the HelloMidlet.java into “C:\WTK22\apps\hellomidlet\src” directory.

• If the java program has any resource such as icon file or picture files, copy them into “C:\WTK22\apps\hellomidlet\res” directory. (Current project has no additional resource so you can skip this step.)

5. Compile MIDlet

The KToolbar program will automatically perform the necessary steps that are compiling, preverifying, compressing the code into JAR, and creating the corresponding JAD file with only one command button.

For Windows OS

• Click Build button on the KToolbar window and check for any errors report in the KToolbar window.

6. Run MIDlet with Emulator

If there is no error during the compile process in step 5, the MIDlet application is ready to run.

For Windows OS

• Click Run button on the KToolbar. The default emulator will be loaded with the application.

7. Change Emulator

The user can select different emulator by selecting testing device from the device drop-down menu on the KToolbar.

8. Save the MIDlet’s JAD/JAR Files

For Windows OS

• Click on the Project menu and navigate to the Package submenu.

• Select the Create Package command (the corresponding JAD/JAR files would be created automatically. They are located in /bin directory).

Part VI: Testing GUI Components with MIDlet

This section demonstrates how the high-level GUI component can be implemented using MIDlet. Use any text editor to create following source code and save the file name as “testGUI.java.” Please follow previous procedure of KToolbar in Part V to compile and run this application (use “testgui” as a project name).

import javax.microedition.lcdui.*;

import javax.microedition.midlet.*;

public class testGUI extends MIDlet implements CommandListener {

// display manager

Display display = null;

// a menu with items

List menu = null; // main menu

// list of choices

List choose = null;

// textbox

TextBox input = null;

// ticker

Ticker ticker = new Ticker("Test GUI Components");

// alerts

final Alert soundAlert = new Alert("sound Alert");

// date

DateField date = new DateField("Today's date: ", DateField.DATE);

// form

Form form = new Form("Form for Stuff");

// gauge

Gauge gauge = new Gauge("Gauge Label", true, 10, 0);

// text field

TextField textfield = new TextField("TextField Label", "abc", 50, 0);

// command

static final Command backCommand = new Command("Back",

Command.BACK, 0);

static final Command mainMenuCommand = new Command("Main",

Command.SCREEN, 1);

static final Command exitCommand = new Command("Exit",

Command.STOP, 2);

String currentMenu = null;

public testGUI() {

// constructor

}

public void startApp() throws MIDletStateChangeException {

display = Display.getDisplay(this);

menu = new List("Test Components", Choice.IMPLICIT);

menu.append("Test TextBox",null);

menu.append("Test List",null);

menu.append("Test Alert",null);

menu.append("Test Date",null);

menu.append("Test Form",null);

menu.addCommand(exitCommand);

menu.setCommandListener(this);

menu.setTicker(ticker);

mainMenu();

}

public void pauseApp() {

display = null;

choose = null;

menu = null;

ticker = null;

form = null;

input = null;

gauge = null;

textfield = null;

}

public void destroyApp(boolean unconditional) {

notifyDestroyed();

}

//main menu

void mainMenu(){

display.setCurrent(menu);

currentMenu = "Main";

}

/**

* Test the TextBox component

*/

public void testTextBox() {

input = new TextBox("Enter Some Text:", "", 5, TextField.ANY);

input.setTicker(new Ticker("testTextBox "));

input.addCommand(backCommand);

input.setCommandListener(this);

input.setString("");

display.setCurrent(input);

currentMenu = "input";

}

/**

* Test the List component.

*/

public void testList() {

choose = new List("Choose Items", Choice.MULTIPLE);

choose.setTicker(new Ticker("listTest "));

choose.addCommand(backCommand);

choose.setCommandListener(this);

choose.append("Item 1",null);

choose.append("Item 2",null);

choose.append("Item 3",null);

display.setCurrent(choose);

currentMenu = "list";

}

/**

* Test the Alert component.

*/

public void testAlert() {

soundAlert.setType(AlertType.ERROR);

soundAlert.setString("** ERROR **");

display.setCurrent(soundAlert);

}

/**

* Test the DataField component.

*/

public void testDate() {

java.util.Date now = new java.util.Date();

date.setDate(now);

Form f = new Form("Today's date");

f.append(date);

f.addCommand(backCommand);

f.setCommandListener(this);

display.setCurrent(f);

currentMenu = "date";

}

/**

* Test the Form component.

*/

public void testForm() {

form.append(gauge);

form.append(textfield);

form.addCommand(backCommand);

form.setCommandListener(this);

display.setCurrent(form);

currentMenu = "form";

}

/**

* Handle events.

*/

public void commandAction(Command c, Displayable d) {

String label = c.getLabel();

if (label.equals("Exit")) {

destroyApp(true);

} else if (label.equals("Back")) {

if(currentMenu.equals("list") ||

currentMenu.equals("input") ||

currentMenu.equals("date") ||

currentMenu.equals("form")) {

// go back to menu

mainMenu();

}

} else {

List down = (List)display.getCurrent();

switch(down.getSelectedIndex()) {

case 0: testTextBox(); break;

case 1: testList(); break;

case 2: testAlert(); break;

case 3: testDate(); break;

case 4: testForm(); break;

}

}

}

}

Part VII: Simple HTTP Programming

A simple network application can be implemented using CLDC Generic Connection framework. A network connection can be created using a java class called javax.microedition.io.Connector. An “open()” method is called with a string of HTTP’s URL to fetch a file from the world wide web. Create a file name “FetchPageMidlet.java” with any text editor and follow the KToolbar procedure to compile and run this application (use “fetchpagemidlet” as a project name).

import java.io.*;

import javax.microedition.io.*;

import javax.microedition.lcdui.*;

import javax.microedition.midlet.*;

public class FetchPageMidlet extends MIDlet {

private Display display;

String url = "";

public FetchPageMidlet() {

display = Display.getDisplay(this);

}

/**

* This will be invoked when we start the MIDlet.

*/

public void startApp() {

try {

getViaStreamConnection(url);

} catch (IOException e) {

// Handle Exceptions

System.out.println("IOException " + e);

e.printStackTrace();

}

}

/**

* Pause, discontinue ....

*/

public void pauseApp() {

// no code

}

/**

* Destroy must cleanup everything

*/

public void destroyApp(boolean unconditional) {

// no code

}

/**

* read url via stream connection

*/

void getViaStreamConnection(String url) throws IOException {

StreamConnection c = null;

InputStream s = null;

StringBuffer b = new StringBuffer();

TextBox t = null;

try {

c = (StreamConnection)Connector.open(url);

s = c.openInputStream();

int ch;

while((ch = s.read()) != -1) {

b.append((char) ch);

}

System.out.println(b.toString());

t = new TextBox("Fetch Page", b.toString(), 1024, 0);

} finally {

if(s != null) {

s.close();

}

if(c != null) {

c.close();

}

}

// display the contents of the file in a text box.

display.setCurrent(t);

}

}

Question: What is the content of the hello.txt file? (The content of the hello.txt file will displayed on the emulator after launching the “fetchpagemidlet” application)

Answer: _________________________________

Part VIII: Converting to Palm OS Application Using IBM’s WebSphere Micro Environment

The benefit of developing application using Java language is that it can run on any machine that supports Java Virtual Machine. The IBM WebSphere Micro Environment is a run-time platform compliant with Java 2 Micro Edition (J2ME). On Palm OS 5 (such as Palm Tungsten C, Zire 72 and Tungsten T5), WebSphere implements the J2ME specifications for the Connected Limited Device Configuration (CLDC) Version 1.1 and the Mobile Information Device Profile (MIDP) Version 2.0 [2]. This section demonstrates on how to install the Java platform on handheld device and convert a MIDlet application to a Palm OS application for Palm OS 5. Please use the same source code in Part VI. We will convert it into Palm Resource Code (PRC) file format, which is an executable format for Palm OS. A summary of Palm application development life cycle are [1]:

1. Develop a MIDlet or a MIDlet suite (multiple MIDlet files).

2. Convert the JAR/JAD file pair into a PRC file (executable Palm application).

3. Install the PRC file on the Palm and test the application.

1. Install the WebSphere Micro Environment Toolkit for Palm OS on PC

This procedure is optional. The lab machine is already installed for you.

• Download a package called WME_Toolkit_MIDP2_GA.zip which is the MIDP runtime environment for new Palm OS from the following URL:

• Unzip the package into C:\webshpere\ and check for two Palm OS files called J9JavaVMMidpNG.prc and J9pref.prc. They should be found under the directory C:\websphere\03_09_04\IBM\Websphere Micro Environment\prc\ARM. The first file is a Java Virtual Machine. Both files must be transferred onto Palm device in the next step. These PRC files can also be found from the following URL:

2. Install the WebSphere Micro Environment run-time on the new Palm Device

This procedure is optional. The lab machine is already installed for you.

• Make sure that the Palm cradle is connected to the PC’s USB port.

• Place the Palm device on the cradle.

• Start the Palm desktop software and click on the Install icon and go to C:\websphere\03_09_04\IBM\Websphere Micro Environment\prc\ARM to choose the J9JavaVMMidpNG.prc and J9pref.prc.

• Tap the HotSync icon on a Palm device (or press the HotSync button on the cradle) to install the file.

• Look on the Palm device and make sure that the new Java Virtual Machine is present.

3. Convert a MIDlet into a PRC file for WebShpere

Locate a Windows based tool kit program called jartoprc_w.exe under the directory C:\websphere\03_09_04\IBM\Websphere Micro Environment\bin\. Use this PRC converter tool to convert the MIDlet JAR/JAD file into an executable Palm application. Start this PRC converter tool by clicking on the file icon under Windows or issue the following command line:

For Windows OS

C:\websphere\03_09_04\IBM\Websphere Micro Environment\bin> jartoprc_w

• After issue the command, an application Windows will pop-up for the JarToPRC tool.

• Click the Browse… button of JAD File or URL field, Navigate through file chooser for existing JAD file under C:\WTK22\apps\testgui\bin\.

• Select the file testgui.jad or other JAD file to be converted. Click OK to select the file. Note that some of the files are filled automatically. Optionally, users can add icon image and splash screen for their application.

• Click on the Generate PRC button to convert the file into a PRC file. The converted file will be saved in the same directory as the JAD/JAR file pair

4. Install and Test the PRC file on the Device

Use HotSync to install the “testgui.prc” file with the following procedure:

• Connect Palm device to PC via USB port (or place Palm device in the cradle).

• Start the Palm Desktop software on the PC by choosing

Start[pic]All Programs[pic]Palm Desktop[pic]Palm Desktop

• Click the Install icon and browse to C:\WTK22\apps\testgui\bin\testgui.prc.

• Tap the HotSync icon (i.e., a star icon at the bottom right of the screen) on the Palm device (or press the HotSync button on the cradle) to install the file.

• Tap the corresponding icon on the Palm device to test your application.

Part X: Assignments

Modify the testGUI.java example so that before displaying test component main menu, the user must enter a correct username and a correct password. Create a new form which is called “Sign in” and added two textfields with corresponding labels called “username” and “password” using the following code:

username = new TextField(“Username:”, “”, 10, TextField.ANY);

password= new TextField(“Password:”, “”, 10, TextField.PASSWORD);

Also modify the two soft buttons on the mobile phone emulator to be “cancel” and “login” with the following code:

cancel = new Command(“Cancel”, Command.Cancel, 2);

login = new Command(“Login”, Command.OK, 2);

If the user enters incorrect username or password, the program must show an alert that notify the user that the login is incorrect and should try again.

Hints:

• Use the same technique to create the alert as in the testGUI.java.

• To check the user name and password strings, use the method “.equals” on String variable type.

Email your code (.java) to GSA. GSA will test your application using Wireless Toolkit Emulator.

Questions:

1. Is there any advantage of using a KToolbar to create and test MIDlets versus using command lines?

________________________________________________________________________________________________________________________________________________________________________________________________________________________

2. What is the purpose of having a JAD file in a MIDlet package?

________________________________________________________________________________________________________________________________________________________________________________________________________________________

3. Briefly explain the following partial code from part VI. You may consult any J2ME book.

public void startApp() throws MIDletStateChangeException {

display = Display.getDisplay(this);

menu = new List("Test Components", Choice.IMPLICIT);

menu.append("Test TextBox",null);

menu.append("Test List",null);

menu.append("Test Alert",null);

menu.append("Test Date",null);

menu.append("Test Form",null);

menu.addCommand(exitCommand);

menu.setCommandListener(this);

menu.setTicker(ticker);

mainMenu();

}

.

.

void mainMenu(){

display.setCurrent(menu);

currentMenu = "Main";

}

________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

4. Briefly explain the following partial code from Part VI. You may consult any J2ME book.

.

.

Form form = new Form("Form for Stuff");

Gauge gauge = new Gauge("Gauge Label", true, 10, 0);

TextField textfield = new TextField("TextField Label", "abc", 50, 0);

static final Command backCommand = new Command("Back",

Command.BACK, 0);

.

.

public void testForm() {

form.append(gauge);

form.append(textfield);

form.addCommand(backCommand);

form.setCommandListener(this);

display.setCurrent(form);

currentMenu = "form";

}

________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

5. To establish an HTTP connection, what must you pass into the Connector.open() method?

________________________________________________________________________

Reference:

[1] Q. H. Mahmoud, Learning Wireless Java, Cambridge, O’Reilly, 2002.

[2] --, palmOne Java Solutions with WebSphere, Online Available



Appendix:

Procedure for Java SDK and J2ME installation:

1. Download the latest J2SE SDK from or

2. Install the Java SDK first.

3. Add “c:\j2sdk1.4.2_xx\bin” to PATH in User Variables under Environment Variables of Windows.

4. Download the J2ME Wireless Toolkit from the following URL:

5. Install the toolkit and specify the version of existing Java SDK installation in previous step.

-----------------------

Student Name: _________________________

HotSync icon

Home icon

destroyApp()

destroyApp()

Destroyed

Active

Paused

startApp()

pauseApp()

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download