JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Java ME and Web services

March 31, 2011 by Krishna Srinivasan Leave a Comment

Introduction

Java Micro Edition (Java ME) is a platform for running applications on smaller devices such as mobile phones, PDAs etc. These devices have restrictions in terms of Memory and Processing power. Java ME defines various configurations and profiles. Midlets are java applications that operate on Mobile Information Device Profile (MIDP) which is targeted on Mobile phones that has limited memory and processing power. If you are new to Java ME please refer to the articles Introduction to J2ME and J2ME User Interface in Java Beat.

also read:

  • What is UDDI?
  • Apache Axis 2 Web Services
  • RESTFul Java Web Services

Due to the limitations on the mobile phones, the midlets can’t be exposed as a web service. But the midlets can consume web services. Java ME provides a subset of JAX-RPC APIs to work with web services. This article will provide a step by step procedure to access web services from a midlet.

Invoking web services from a Midlet

To access web services, the Midlet has to make remote calls on the web services. But the Midlets won’t do this directly. A stub has to be created and calls are made via the stub instance. Using wireless toolkit it is made very simple to create stub code. Invocation on web service method is a synchrous process. The parameters for the methods are passes by value instead of pass by references. Similarly the values are returned by web services as pass by value. On the stubs midlets can set some properties like USERNAME_PROPERTY, PASSWORD_PROPERTY (User name and password for authentication), ENDPOINT_ADDRESS_PROPERTY(Address of the endpoint) and SESSION_MAINTAIN_PROPERTY(if true:session will be maintained between endpoint and midlet) using _setProperty method.
[code lang=”java”]stub._setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY,serviceUrl);
stub._setProperty(Stub.SESSION_MAINTAIN_PROPERTY, new Boolean(true));[/code]
The generated stub code and the supportive classes have to be bundled in the jar file along with the midlet. While accessing web services the best practice is to write the sub invocation code in a seperate thread. This will avoid your application hanging as your thread will be blocked during web service invocation.

Example

This example will help you in understanding how to access web service from a midlet. Netbeans IDE, Glassfish application server and Wireless tool kit 2.5.2 are used.

Create the web service and deploy it in the application server

Web service:
[code lang=”java”]package mypack;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
@WebService()
public class HelloService {
@WebMethod(operationName = "getMessage")
public String getMessage(@WebParam(name = "name")
String name) {
return "Hi "+name+"! Welcome to JME Programming";
}
}[/code]
WSDL URL:
http://localhost:17754/HelloWebService/HelloServiceService?WSDL

Create a Midlet with a form with a text field and command buttons.

[code lang=”java”]public class Midlet extends MIDlet implements CommandListener{
private Form myform;
private TextField field;
private Command exit,getMessage;
private Display d;
public void startApp() {
d=Display.getDisplay(this);
myform=new Form("Access Webservice");
field=new TextField("Name", "", 20, TextField.PLAIN);
exit=new Command("Exit", Command.EXIT, 0);
getMessage=new Command("GetMsg", Command.SCREEN, 1);
myform.append(field);
myform.addCommand(exit);
myform.addCommand(getMessage);
myform.setCommandListener(this);
d.setCurrent(myform);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if(c==exit){
notifyDestroyed();
}else if(c==getMessage){
//Code to Access Webservice
}
}
}[/code]

Use Wireless tool kit tool to create the stub

a) Open Wireless Toolkit

(b) Select File -> Utilities

(c) Select Stub Generator

d) Provide WSDL URL and the Output folder(src folder in Netbeans project) and the package details. Click on Ok

(e) The Stub and the other classes are generated in the src folder

Access Web service

For accessing web service,

  1. Create a new thread.
  2. In the new thread, Instantiate the stub
  3. Set properties on the stub if required
  4. Invoke the web service methods on the stub

[code lang=”java”]//Extend the code written earlier
import mypack.HelloService_Stub;
public class Midlet extends MIDlet implements CommandListener{
private Form myform;
private TextField field;
private Command exit,getMessage;
private Display d;
public TextField getField() {
return field;
}
public Form getMyform() {
return myform;
}
….
public void commandAction(Command c, Displayable d) {
if(c==exit){
notifyDestroyed();
}else if(c==getMessage){
Thread t=new Thread(new NewThread(this));
t.start();
}
}
}
class NewThread implements Runnable{
Midlet m;
NewThread(Midlet m){
this.m=m;
}
public void run() {
Form frm=m.getMyform();
TextField txt=m.getField();
HelloService_Stub stub=new HelloService_Stub();
String msg="";
try {
msg = stub.getMessage(txt.getString());
frm.append(msg);
} catch (RemoteException ex) {
frm.append(ex.getMessage());
}
}
}[/code]

Run the Midlet

Run the midlet. Provide the Name and select the command button GetMsg. The following output will be displayed.

Conclusion

Java ME Midlets can act only as the consumer for web services. It can’t be exposed as a web service. Wireless Tool Kit helps in creating stubs for web services. Midlets by invoking methods on the stub invokes methods on web services. Both simple types and complex types can be passed as parameters to the web services.

Filed Under: WebServices Tagged With: J2ME, WebServices

Writing JSF applications for J2ME clients

October 26, 2010 by Krishna Srinivasan Leave a Comment

Introduction


JSF
is a Web framework for developing Component oriented web applications in the User Interface layer. Amongst the various capabilities that JSF provides, one of the major strengths of JSF is that it is not tied to any specific target device. For example, currently most of the JSF applications are running in a web server and are accessible through a web browser. However, web browser is not the only target for a JSF application to be viewed; it can be even accessed through a hand-held device, for example through a mobile phone. In this example, we will see how to develop JSF applications targeted for mobile phones. This article assumes that the reader has a good understanding of JSF, its life-cycle and some understanding on JSF renderer kits.

also read:

  • Introduction to JSF
  • JSF Interview Questions
  • Request Processing Lifecycle phases in JSF

Renderer kits

The responsibility of displaying a view in a target device is done through renderer kits. Renderer kits in JSF are nicely abstracted so it is possible to write custom implementation of renderer kits.
Sun’s implementation of JSF provides a reference implementation of a HTML renderer kit. The HTML renderer kit is responsible for displaying the view in a web browser. So while writing a renderer kit implementation amongst the various factors to be taken into consideration, the important things are the target device, the protocol, the markup language and the scripting language. For a HTML renderer kit implementation, these would be the Web browsers, HTTP, hyper text markup language and java script.
Similarly a render kit implementation would consider the mobile phone browser, Wireless application protocol, the Wireless markup language (WML) and WML Script for providing suitable support in the mobile or any WAP browser. Wireless application protocol is the standard defined for displaying contents on wireless devices such as mobile phones. Similar to HTML that targets Web browsers, WML is the markup language for mobile phones. Consider the sample WML script,

[code lang=”xml”]
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
"http://www.wapforum.org/DTD/wml_1.1.xml" >
<wml>
<card id="test" title="Test card">
<p>This is a test WML page.
</card>
</wml>[/code]
Usually WML document can be thought of as a collection of cards. Each user interaction will be modeled as a card and each card will be inter-dependant. The syntax will mostly look like HTML for displaying the UI elements and content in the WML browser.
WML script, similar to Java script, is the client side scripting language for WML. It is mainly used for dynamically validating user input and it generally will appear in a separate file. Consider the following example script,

[code lang=”java”]extern function sayHello()
{
WMLBrowser.setVar("message", "Hello World.");
WMLBrowser.refresh();
}[/code]
The above script will appear in a separate file, say ‘hello.wmls’ and the following wml page will provide a reference to the above wml script.

[code lang=”xml”]
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
"http://www.wapforum.org/DTD/wml_1.1.xml" >
<wml>
<card id="test" title="Test card">
<p><a

href="hello.wmls#sayHello()">Run</a><br/>
$(message)

</card>
</wml>[/code]

Mobile Faces

Mobile Faces for JSF provides a framework for simplifying the development of JSF applications targeted for wireless devices. The framework comes packaged with an implementation of renderer kits for HTML, XHTML-MP and WML. Also it supports various commonly used scripting languages such as Java Script, WML Script and ECMA Script. For testing JSF faces developed through Mobile Faces framework, we will be using OpenWave Browser for WAP. It serves as an emulator for testing WAP applications. In this article, we will be showing how to develop applications using the Mobile Faces toolkit.

Setting up the development environment

OpenWave is used for testing the JSF application in the WAP Browser. Mobile Faces distribution has to be downloaded, jar file has to be built from the distribution’s ant file and the same has to be made available in the application’s class path.

Hello World JSF-J2ME Application

In this example, we will develop a JSF application that will display the message ‘Hello World’ when it is invoked. Since this is the first application, we will keep the components to the minimal that we can. For example, we will not be using backing beans in this example.

Web Configuration file

Take the look at the web configuration file which is given below. Plenty of things need to be considered in the descriptor file. The first thing is that we have registered the Faces servlet for handling all the requests that matches the pattern “.JSF“. This is done by defining the faces servlet ‘javax.faces.webapp.FacesServlet’.

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"

xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<context-param>

<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>

<context-param>

<param-name>javax.faces.CONFIG_FILES</param-name>

<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<context-param>

<param-name>ericsson.mobilefaces.CONFIG_FILE</param-name>

<param-value>/WEB-INF/mfaces-config.xml</param-value>
</context-param>

<filter>
<filter-name>MobileFaces Init

Filter</filter-name>

<filter-class>com.ericsson.sn.mobilefaces.MobileFacesSer

vletFilter</filter-class>
<init-param>
<description>Set to "true" to turn on the debug </description>
<param-name>Debug</param-name>
<param-value>true</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>MobileFaces Init

Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<servlet>
<servlet-name>Faces Servlet</servlet-name>

<servlet-class>javax.faces.webapp.FacesServlet</servlet-

class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>Faces

Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>

</web-app>[/code]
We have also defined a filter servlet called ‘MobileFacesServletFilter’ that will be invoked for all requests. This filter servlet is responsible for various things – for example, this servlet takes responsibility in finding out the device used for invoking the application and based on that it loads the media adapter and the script renderer implementations. For a JSF web application, ‘faces-config.xml’ is essential as it contains the managed beans and the navigation rules declaration. Similarly for mobile applications, the configuration file has to be specified through the parameter ‘ericsson.mobilefaces.CONFIG_FILE’. The details of this configuration file will be covered in the next section.

Mobile Faces Configuration file

The definition for mobile faces configuration file is given below. This configuration file is useful for configuring the factory implementation for defining the devices, scripting implementation and media adapters. For this simple example, the listing for the configuration file contains information for configuring the devices information.

[code lang=”xml”]<?xml version=’1.0′

encoding=’UTF-8′?>

<!–
MobileFaces System Configuration File.
–>
<mfaces-config>

<configuration-file>
<devices>conf/devices.xml</devices>
</configuration-file>

</mfaces-config>[/code]
Note that the configuration file refers to devices configuration file ‘devices.xml’ which is described in the next section.

Devices Configuration file

The listing for devices configuration file is given below. Here we define the mapping information for various devices with the list of supported configuration.

[code lang=”xml”]<?xml version="1.0"

encoding="UTF-8"?>
<device-list>
<!– Default Device. Use this one if no other

device can be matched. –>
<device>
<DEVICE_NAME>DefaultDevice</DEVICE_NAME>
<USER_AGENT>default</USER_AGENT>
<SCREEN_LEVEL>9</SCREEN_LEVEL>
<MARKUP>HTML_BASIC</MARKUP>
<SCRIPT>javascript</SCRIPT>

<IMAGE_SUPPORT>jpg;jpeg;gif;png;</IMAGE_SUPPORT>
</device>

<!– Firefox. Web browser with HTML language.

–>
<device>
<DEVICE_NAME>Firefox</DEVICE_NAME>
<USER_AGENT>Firefox</USER_AGENT>
<SCREEN_LEVEL>9</SCREEN_LEVEL>
<MARKUP>HTML_BASIC</MARKUP>
<SCRIPT>javascript</SCRIPT>

<IMAGE_SUPPORT>jpg;jpeg;gif;png;</IMAGE_SUPPORT>
</device>

<!– InternetExplorer. Web browser with HTML

language. –>
<device>

<DEVICE_NAME>InternetExplorer</DEVICE_NAME>
<USER_AGENT>MSIE</USER_AGENT>
<SCREEN_LEVEL>9</SCREEN_LEVEL>
<MARKUP>HTML_BASIC</MARKUP>
<SCRIPT>javascript</SCRIPT>

<IMAGE_SUPPORT>jpg;jpeg;bmp;gif;png;tiff;</IMAGE_SUPPORT

>
</device>

<!– OpenWave-WML. WAP1 browser with WML

language. –>
<device>
<DEVICE_NAME>OpenWaveWML</DEVICE_NAME>
<USER_AGENT>OPWV-SDK-WML</USER_AGENT>
<SCREEN_LEVEL>5</SCREEN_LEVEL>
<MARKUP>WML</MARKUP>
<SCRIPT>wmlscript</SCRIPT>

<IMAGE_SUPPORT>png;gif;wbmp;</IMAGE_SUPPORT>
</device>

<!– OpenWave-XMP. WAP2 browser with XHTML-MP

language. –>
<device>
<DEVICE_NAME>OpenWaveXMP</DEVICE_NAME>
<USER_AGENT>OPWV-SDK-XMP</USER_AGENT>
<SCREEN_LEVEL>5</SCREEN_LEVEL>
<MARKUP>XHTML_MP</MARKUP>
<SCRIPT></SCRIPT>
<IMAGE_SUPPORT>png;gif;</IMAGE_SUPPORT>
</device>

<!– NetFront Content Viewer. WAP2 browser with

XHTML-MP language. –>
<device>
<DEVICE_NAME>NetFront</DEVICE_NAME>
<USER_AGENT>NetFront</USER_AGENT>
<SCREEN_LEVEL>5</SCREEN_LEVEL>
<MARKUP>XHTML_MP</MARKUP>
<SCRIPT>ecmascriptmp</SCRIPT>

<IMAGE_SUPPORT>png;gif;jpg;jpeg;</IMAGE_SUPPORT>
</device>
</device-list>[/code]
For example, for the web browser ‘Firefox’, we have defined the markup language to be ‘HTML’ and the scripting language to be Javascript. Similarly for the device ‘OpenWave’, we have defined the markup language to be ‘WML’ and the scripting language as WML Script. So, after deploying this application in a server, when an application is accessing this application, the framework will determine the type of device by examining the ‘User-Agent’ field from the request parameter. It will then try to match the User-Agent information with the list of user agents that is defined in the ‘devices.xml’ configuration file. And appropriately the responses will be delivered to the target device. If the framework cannot find a suitable device, then it will lookup for the default device (mentioned below) in which case the markup language and the scripting language are HTML and Javascript respectively.

[code lang=”html”]<!– Default Device. Use this one if no other device can be matched. –>
<device>
<DEVICE_NAME>DefaultDevice</DEVICE_NAME>
<USER_AGENT>default</USER_AGENT>
<SCREEN_LEVEL>9</SCREEN_LEVEL>
<MARKUP>HTML_BASIC</MARKUP>
<SCRIPT>javascript</SCRIPT>
<IMAGE_SUPPORT>jpg;jpeg;gif;png;</IMAGE_SUPPORT>
</device>[/code]

Index Page

This page will be invoked during application’s startup. Note that this page doesn’t really do anything other than forwarding the request to the page ‘demo.jsf’.

[code lang=”java”]<jsp:forward page="/hello.jsf" />[/code]

Hello Page

The complete listing for the hello page is given below. Note the tag library declaration at the top. We have used the core and the html tags along with the customized tags representing the mobile devices from the uri ‘http://www.ericsson.com/sn/mobilefaces’.

[code lang=”java”]<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h"

uri="http://java.sun.com/jsf/html"%>
<%@taglib prefix="m"

uri="http://www.ericsson.com/sn/mobilefaces"%>
<f:view>
<m:doctype/>

<m:html>
<head>
<m:title content="Hello JSF!"/>
</head>
<m:body>
<h:form id="f">
<m:h3>Hello World</m:h3>
<p>
<h:messages/>

<p>
<h:outputText id="hello"

value="Hello World"/>

</h:form>
</m:body>
</m:html>
</f:view>[/code]
Note that definition of the document type tag ‘m:doctype’. This is necessary for defining the Document type heading, whether the page has to be rendered as HTML or WML will be determined through the request parameter and the rendering will happen accordingly. Also we have defined the m:title which will render the text described in the ‘content’ attribute as a title text in the target device.

Faces Configuration file

The definition for faces configuration file is given below. Note that for this simple application, we haven’t declared any managed beans as well as the navigation rules.

[code lang=”xml”]<?xml version=’1.0′

encoding=’UTF-8′?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xs d" version="1.2">

</faces-config>[/code]

Testing the application

As discussed already we will be making use of OpenWave for testing the application. Launch the application and type the url ‘http://localhost:8080/JSF-WML-Hello’. This assumes that the application is running on the port number ‘8080’ and the application’s context root is ‘JSF-WML-Hello’. Have a look at the screenshot.


Note that when this URL is accessed through the Open Wave Browser, the request will be a regular HTTP request including the protocol information. One more field of interest is the User Agent Field which will be ‘OPWV-SDK-WML’. This value for this field is very important as this value will be used for fetching the device information that is configured in the ‘devices.xml’ configuration file. Part of the request information is shown below.

[code]…
Host address: 127.0.0.1
URI: http://localhost:8080/JSF-WML-Hello/
GET /JSF-WML-Hello/ HTTP/1.1
Host: localhost:8080
User-Agent: OPWV-SDK-WML UP.Browser/7.0.2.3.119 (GUI)

MMP/2.0 Push/PO
…[/code]
Once this request is accepted by the application, the response will be in Wireless markup language as that is the markup language that is configured for this user agent.

[code lang=”xml”]URI: http://localhost:8080/JSF-WML-Hello/
HTTP/1.1 200 OK
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN"

"http://www.wapforum.org/DTD/wml13.dtd">
<wml>
<head>
<meta name="title" content="Hello JSF!"

/>
</head>

<card id="WMLCard" title="WML PAGE"><p><b>Hello

World</b><br />
<p>
<!–global message component for

showing warning or error messages–>

<p> Hello World
<p />
</card>
</wml> [/code]
Note that in the above response, the WML script is embedded in the response string.

Login Application

In this section, we will see how to implement the login support for an application when accessed through J2ME. In this example, we will see how to define managed beans for managing the state of the user inputs. Also we will see how to define the navigation rules when the application is accessed. Specifically we will see and analyze the navigation cases for a successful and a failure login.

Configuration files

The web application’s deployment descriptor won’t be getting covered in this section as the content of it will be the very same that we saw in the earlier section, same is the case for the mobile faces configuration file.

Login Bean Model

The model for the login bean is defined below. It essentially declares two things. The first thing is for collecting the user input from the UI, it defines the properties ‘username’ and ‘password’along with the getter and the setter methods. Also it provides a validation logic in the method ‘validateLogin()’ which validates the username and the password entered by the user.
[code lang=”java”]
package net.javabeat.articles.jsf.mobile.login;

public class LoginBean {

private String username;
private String password;

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String validateLogin() {

if (username != null && password !=

null) {
if (username.equals("admin") &&

password.equals("admin")){
return "success";
}
}
return "failure";
}
}[/code]
Note that for simplification, we didn’t validate the username and the password by hitting
the data layer. Instead the login credentials are hard-coded as ‘admin’ and ‘admin’ within the managed bean.

Index Page

The listing for the index page is shown below. As one can see it delegates the call to the login page. Note that this page will be handled by Faces Servlet as we have defined the corresponding mapping in the Web application’s deployment descriptor.

[code lang=”html”]
<jsp:forward page="/login.jsf" />
[/code]

Login Page

The login page for the application that is used for collecting username and password information from the user is given below. Note that this is a basic form containing username/password textfields with the login button, the listing for the same is given below.

[code lang=”html”]
<%@taglib prefix="f"

uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h"

uri="http://java.sun.com/jsf/html"%>
<%@taglib prefix="m"

uri="http://www.ericsson.com/sn/mobilefaces"%>
<f:view>
<m:doctype/>

<m:html>
<head>
<m:title content="Login!"/>
</head>

<m:body>
<h:form id="f">

<m:h3>Login</m:h3>
<p>
Username:
<h:inputText

id="username" value="#{loginBean.username}"

required="true" />
<br/>
Password:
<h:inputText

id="password" value="#{loginBean.password}"

required="true" />

<br/>
<h:commandButton

id="login" type="submit" value="Login"

action="#{loginBean.validateLogin}"/>

</h:form>
</m:body>
</m:html>
</f:view>[/code]
Note that when this application is accessed through a WML browser, the response that will be rendered will be WML script. Note that the developer doesn’t need to worry about the translation mechanism done for rendering as the framework takes complete care on it. The content of the WML script corresponding to the login form is given below.
[code lang=”xml”]
<?xml version="1.0"

encoding="UTF-8"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN"

"http://www.wapforum.org/DTD/wml13.dtd">
<wml>
<head>
<meta name="title" content="Login!" />
</head>

<card id="WMLCard" title="WML

PAGE"><p><b>Login</b><br />
<p>
Username:
<input id="fausername" name="fausername"

type="text" value="" />
<br/>
Password:
<input id="fapassword" name="fapassword"

type="text" value="" />

<br/>

<p>
<do type="accept" label="Login"

id="f:login" name="f:login">
<go method="post"

href="/JSF-WML-Login/login.jsf;jsessionid=f5de0e83eded70

42ee6c2d295dec">
<postfield

name="com.ericsson.sn.mfaces.FACES_VIEW_STATE" value=""

/>
<postfield name="f:login" value="submit"

/>
<postfield name="f:password"

value="$(fapassword)" />
<postfield name="f" value="f" />
<postfield name="f:username"

value="$(fausername)" />
</go></do>

</card>
</wml>[/code]
The screenshot for the above page is given below.

Faces Configuration file

We use the faces configuration file for defining the managed bean and the list of navigation rules in this example. Have a look at the listing of the configuration file.
[code lang=”xml”]
<?xml version=’1.0′

encoding=’UTF-8′?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd" version="1.2">

<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/success.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>failure</from-outcome>
<to-view-id>/failure.jsp</to-view-id>
</navigation-case>
</navigation-rule>

<managed-bean>
<description>Login Bean</description>
<managed-bean-name>loginBean</managed-bean-name>
<managed-bean-class>
net.javabeat.articles.jsf.mobile.login.LoginBean
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>

</faces-config>
[/code]
Note that the navigation rule for this application is defined through the element’navigation-rule’. Here we have defined if the outcome from the view ‘login.jsp’ is success, then the view definition file that has to be rendered is “success.jsp”. Similarly for the outcome “failure”, the view “failure.jsp” has to be mapped and displayed. Have a look at the declaration of the login managed bean which is done within the elements ‘managed-bean’.

Success Page

When the user enters the username and the password details, the method ‘validateLogin()’ will be invoked on the Login Bean object. This method will validate for the correctness of the username and the password and if they are correct will return the string “success”. It is mentioned that for the outcome “success”, the view definition file that is mapped is “success.jsf” and the content of the same is given below.
[code lang=”java”]
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@taglib prefix="m" uri="http://www.ericsson.com/sn/mobilefaces"%>
<f:view>
<m:doctype/>

<m:html>
<head>
<m:title content="Login

Success"/>
</head>

<m:body>
<m:h2>Congratulation! You login

is successful</m:h2>
<p><a

href="login.jsf"><b>Login</b></a>
</m:body>
</m:html>
</f:view>[/code]
Note that the content that will be returned to the WAP browser is shown below which will decode and display the view as shown in the screenshot to the user.
[code lang=”xml”]
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN" "http://www.wapforum.org/DTD/wml13.dtd">
<wml>
<head>
<meta name="title" content="Login

Success" />
</head>

<card id="WMLCard" title="WML

PAGE"><p><strong>Congratulation! You login is

successful</strong><br />
<p><a

href="login.jsf"><b>Login</b></a>
</card>
</wml>[/code]

Failure page

When the user entered username/password seems to be invalid – i.e. in which case the method validateLogin() returns the string “failure”, then the failure view will be displayed to the user. The content of this view file is shown below.

[code lang=”java”]
<%@taglib prefix="f"

uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h"

uri="http://java.sun.com/jsf/html"%>
<%@taglib prefix="m"

uri="http://www.ericsson.com/sn/mobilefaces"%>
<f:view>
<m:doctype/>

<m:html>
<head>
<m:title content="Login

Failure"/>
</head>

<m:body>
<m:h2>Sorry! Login credentials

are invalid.</m:h2>
<p><a href="login.jsf"><b>Try

again</b></a>
</m:body>
</m:html>
</f:view>[/code]
The corresponding WML document that will be parsed and displayed in the target device is also shown here along with the screenshot.

[code lang=”xml”]
<?xml version="1.0"

encoding="iso-8859-1"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN" "http://www.wapforum.org/DTD/wml13.dtd">
<wml>
<head>
<meta name="title" content="Login

Failure" />
</head>

<card id="WMLCard" title="WML

PAGE"><p><strong>Sorry! Login credentials are

invalid.</strong><br />
<p><a href="login.jsf"><b>Try

again</b></a>
</card>
</wml>[/code]

Conclusion

This article started with the concepts of Renderer kits through which rendering JSF applications on multiple types of devices having different views is possible. It then went on explaining Mobile Faces – a distribution that contains an implementation for WAP support. For a basic demonstration, an illustration was given for displaying a text hello in a WAP browser thereby familiarizing with Mobile JSF and OpenWave. Finally the article concluded with Login application that explained the usage of Managed beans and Navigation rules.

Filed Under: JSF Tagged With: J2ME

J2ME User Interface

October 20, 2007 by Krishna Srinivasan Leave a Comment

1) Introduction

User-interface requirements for small handheld devices are different from personal computers. Because comparatively the display size of handheld devices is smaller. That’s why, we cannot follow the personal computers user-interface programming guidelines for handheld devices. In J2ME,the CLDC itself does not define any GUI functionality. The official GUI classes for the J2ME are included in profiles such as the MIDP and are defined by the Java Community Process (JCP). The GUI classes in the MIDP are not based on the Abstract Window Toolkit (AWT). The limited CPU memory of handheld devices, cannot handle the AWT. The MIDP contains its own GUI guidelines. The MIDP GUI consists of high-level and low-level APIs, each with their own set of events. Here we are going to discuss about only High-level API’s.
Contents: (This one itself shows the Device Display Heirarchy)

also read:

  • Writing JSF Application for J2ME Clients
  • ViewPort Meta Tag
  • Display Object
    • Displayable Object
  • DISPLAYABLE : Screen Object
    • TextBox Object
    • Alert Object
    • List Object
    • Form Object
  • FORM : Item Object
    • ChoiceGroup Object
    • DateField Object
    • Guage Object
    • Image and ImageItem Object
    • StringItem Object
    • TextField Object

2) API’s

MIDP offers a high-level API objects for user interface development. This is used to build common user-interface components such as Form s, TextBox etc… This handles most component functionality, such as drawing each component on the screen.

2.1) Display Object

A MIDlet has one instance of a Display object. This object is used to obtain information about the current display and includes methods for requesting the objects being displayed. The Display object is essentially the manager of the device display.Display is represented by the javax.microedition.lcdui.Display class. The Display class is the one and only display manager that is instantiated for each active MIDlet and provides methods to retrieve information about the device’s display capabilities.A reference to the device’s display can be obtained by providing a MIDlet reference to the static getDisplay( ) method in the startApp( ) method of a MIDlet.

[code lang=”java”]
public Display getDisplay(MIDlet lMidlet);

public class firstMidlet extends MIDlet
{
firstMidlet( ) { }
int startApp( )
{ …..
return 0;}
} [/code]

Now we have a reference. Then we have to create GUI component. The two forms of the setCurrent() method with this reference as parameter are shown here.

[code lang=”java”]setCurrent(Displayable dispRef);
setCurrent(Alert aRef, Displayable dispRef);[/code]

2.1.1) Displayable Object
There is only one Display object per MIDlet, but many objects within a MIDlet may be displayable. A Displayable object is a component that is visible on a device. MIDP contains two subclasses of Displayable: Screen and Canvas.

[code lang=”java”]abstract public class Displayable
public abstract class Canvas extends Displayable
public abstract class Screen extends Displayable
[/code]

We can find out that, what is currently being displayed on the device. We can find the types of colors the display object supports.Here are the methods.

[code lang=”java”]public Displayable getCurrent( );

public void boolean isColor( ); //returns TRUE if it supports Color, FALSE if it Supports grayscale
public int numColors( ); //Returns number of colors it supports[/code]

2.2) DISPLAYABLE : Screen Object

User interacts with the device through Screen. Screen combines and organizes graphics objects and manages user input through the device. Screens are represented by the javax.microedition.lcdui.Screen object. Then by calling setCurrent( ) they will shown by the Display object.There can be several screens in an application, but only one screen at a time can be visible in a display. There are four types of screens, TextBox, List, Alert, and Form. Screen can have two characteristics: title and ticker.


The title is a string that appears above the screen contents. The following methods are used to set and retrieve the title of the screen.

[code lang=”java”]public void setTitle(String title);
public String getTitle( ); [/code]

The Ticker is a image that stays above the title. The Ticker class implements a tickertape. Starting and Stopping the Ticker doesn’t done using methods.The string associated with Ticker scrolls continuously, whose direction of scrolling and the speed of the scrolling depends on the MIDP implementation.The following are the list of methods used in the Ticker.

[code lang=”java”]public void setTicker(Ticker ticker); // To set the Ticker
public Ticker getTicker( ); // To get the Ticker

public Ticker(String string); // Ticker’s Constructor.

public String getString( ); //To get the sring Associated with he Ticker
public setString(String s);// To set the sring Associated with he Ticker

setTicker(new Ticker("HI HOW ARE YOU"));//To attach the Ticker to screen[/code]

2.2.1) TextBox
TextBox is a screen’s object, using which we can give input and modify the text. TextBox is used when the user needs to give the input for the application. Here is the TextBox’s Constructor.

[code lang=”java”]public TextBox(String title, String text, int maxSize, int constraints); [/code]

The text is used to get the text in the TextBox and maxSize is used to set the maximum size of the TextBox. Some integer constants are used to limit the text in the TextBox such as TextField.ANY , TextField.EMAILADDR ,TextField.NUMBER, TextField.PASSWD, TextField.PHONENUMBER, and TextField.URL. Here are some methods used with TextBox.

[code lang=”java”]public int getConstraints( ); // To get the Current Constraints associated with the TextBox
public void setConstraints(int c);// To set the Constraints for TextBox

public int getMaxSize( ); // To get the Maximum Size of TextBox
public void setMaxSize(int size); // To set the Maximum Size of TextBox

public String getString( ); // To get the Text in the TextBox
public void setString(String s); // To set the Text in the TextBox

public int size( ); // To Get the number of Characters in the TextBox

/* Text Manipulation Methods */

public void delete(int offset, int length); // To delete some text
public void insert(char[] texts, int offset, int length, int position); // To Insert text
public void replace(String str, int position); // To replace the text
public void setChars(char[] texts, int offset, int length); // To set the characters

public int getCaretPosition( ); // To get the Cursors position[/code]

2.2.2) Alert
Alert is a screen which contains text or image. It is used to show the errors and exceptions. A modal alert is a alert which need confirmation from user to close it.But the timed alert doesnt need the confirmation from user.It shows the error for certain amount of time and terminates.Here is the constructor for Alert:

[code lang=”java”]public Alert(String name);
public Alert(String name, String message, Image msgImage, AlertType errorType); [/code]

We can use a timeout value for displaying the Alert message, means how much time the Alert message displays. Initially we can set the timeout and later we can change it. If we want to know the current timeout value we can get it.Similarly we can set and get the Image and String values associated with the Alert.Here are the methods for the same.

[code lang=”java”]public int getDefaultTimeout( );// To get the current default timeout value
public int getTimeout( ); //To get the current timeout value
public void setTimeout(int t); //To set the timeout value
Alert alert = new Alert("Error Message"); // To create a new Alert
alert.setTimeout(5000); // Sets the timeout for 5000 milli seconds
alert.setTimeout(Alert.FOREVER); // To display the alert until user closes it.
public Image getImage( ); // To get the image associated with the Alert
public String getString( ); // To get the String associated with the Alert
public void setImage(Image "alert.png"); //To set the image associated with the Alert
public void setString(String "Spawning Error"); // To set the String associated with the Alert[/code]

The AlertType class has provided with five differet types of alerts: AlertType.ERROR, AlertType.ALARM, AlertType.CONFIRMATION, AlertType.WARNING, and AlertType.INFO. . Here are some methods to set and get the Alert Types.

[code lang=”java”]public AlertType getType( );
public void setType(AlertType AlertType.CONFIRMATION); [/code]

Similarly we can create specific types of alerts as timedAlert or modalAlert.And using the same methods we can set and get the timeouts for them.

[code lang=”java”]Alert timedAlert = new Alert ("Warning", "Clear It", null, AlertType.WARNING); // Creating
TimedAlert.setTimeout(5000); // to set the timeout for timedAlert
Display.setCurrent(timedAlert, timed); // To set the timedAlert as current alert

Alert modalAert = new Alert("Alarm", "Reminder", null, AlertType.ALARM);// Creating
modalAlert.setTimeout(alert.FOREVER); // modalAlert need manual dismissal
display.setCurrent(modalAlert, timed);// To set the modalAlert as current alert[/code]

2.2.3) List
List is a screen which is having some choices for selection. User has to select one of the choices explicitly. Its constructors are:

[code lang=”java”]public List(String name, int listType);
public List(String name, int listType, String[] stringElements, Image[] imageElements); [/code]

There are three types of list types, MULTIPLE , EXCLUSIVE, and IMPLICIT .

  • EXCLUSIVE type of list allows only one selection.
  • IMPLICIT type of list is a list where the choice is implicitly selected.
  • MULTIPLE type of list allows more than one selection of choices.

Here is an example

[code lang=”java”]List list = new List("select one or more", Choice.MULTIPLE); [/code]

We can append, insert, or replace choices in the list. For a choice the text associated to it is mandatory and image associated with it is optional. We can delete the index associated t a choice. We can get text and image associated to a choice. Here are the methods:

[code lang=”java”]public int append(String string, Image image); // To append into the list
public void insert(int choiceNo, String string, Image image); // To insert into the ist
public void set(int choiceNo, String string, Image image);//To replace the choice in the list

int open = list.append("OPEN", null); // open is index for the choice "OPEN"

public void delete(int index); // To delete an index

public String getString(int index); // To get the text associated to the choice with its index
public Image getImage(int index);//To get the image associated to the choice with its index

public boolean isSelected(int index); // To know which is selected in the list
public setSelectedIndex(int index, boolean bool); // To select the choice

public int getSelectedFlags(boolean[] selectedArray); // To set the selection state of the entire list
public void setSelectedFlags(boolean[] selectedArray); // To modify the one that has been passed in [/code]

2.2.4) Form
Forms used to combine multiple components into one screen. It is a screen that contains items. Its constructors are:

[code lang=”java”]public Form(String str);
public Form(String str, Item[] items); [/code]

It will arrange its components as a list. Like the choices within a list, items within a form can be edited using insert, append, and delete.Here are some examples.

[code lang=”java”]public int append(Image img); //appends an object that subclasses the Item object
public int append(Item item);
public int append(String str); //append a generic string
public void delete(int itemNum); //deletes the item at the given position
public Item get(int itemNum);//access any item in the form at its given position
public void insert(int itemNum, Item item);//inserts an item in the form
public int set(int itemNum, Item item);//setting the item referenced by itemNum
public int size( );//find the current number of items that are in the form [/code]

The GUI components that can be placed on a form are: ChoiceGroup, DateField, Gauge, ImageItem, StringItem, and TextField.

2.3) FORM : Item Object

The Item abstract class acts as the base class for all components that can be placed on a form. All Item objects have a label:

[code lang=”java”]public String getLabel( );
public void setLabel(String s); [/code]

2.3.1) ChoiceGroup
A ChoiceGroup object represents a list of selectable choices to be placed on a Form object. It implements the Choice interface. In this object single choice can be made, or it may allow multiple choices. It has two constructors:

[code lang=”java”]public ChoiceGroup(String label, int choiceType);
public ChoiceGroup(String label, int choiceType, String[] stringElements, Image[] imageElements);[/code]

The first constructor is used to create an empty choice group, specifying its label and type. Here two choices are available: EXCLUSIVE and MULTIPLE. The second constructor can be used to create a new choice group, specifying its title and type.We can insert, append, or replace choices in this.Each choice has an integer index that represents its position in the list. The first choice starts at 0 and extends to the current size of the list minus one. It has the following methods.

[code lang=”java”]public int append(String stringElement, Image imageElement);
public void insert(int index, String stringElement, Image imageElement);
public void set(int index, String stringElement, Image imageElement);[/code]

Here are some examples.

[code lang=”java”]int save = list.append("save", null);

public void delete(int index);//delete any index in the choice group
public String getString(int index);//retrieve the string element
public Image getImage(int index);//retrieve the image element

public int getSelectedIndex( );
public boolean isSelected(int index);

public setSelectedIndex(int index, boolean selected);//set the currently selected index
public int getSelectedFlags(boolean[] selectedArray); //set the selection state of the entire choice group
public void setSelectedFlags(boolean[] selectedArray);

ChoiceGroup choices = new ChoiceGroup("Method of payment",Choice.EXCLUSIVE);
choices.append("aaa", null); //adds several new choices(Do the same for all)
choices.delete(15);//delete the 15th choice. Similarly insert and append[/code]

Choice can be displayed using:

[code lang=”java”]setCurrent( ).
Form form = new Form("Select");
form.append(choices);
Display.setCurrent(form);[/code]

2.3.2) DateField
A DateField object is a component for representing date and time information. It can be configured to accept date or time information. It has the following constructors:

[code lang=”java”]public DateField(String label, int mode);
public DateField(String label, int mode, TimeZone timeZone); [/code]

The firstone is used to create a DateField object with the specified label and mode. It has some static fields: DateField.DATE, DateField.TIME, or DateField.DATE_TIME. The DateField.DATE input mode used to set date information, DateField.TIME for clock time information, and DateField.DATE_TIME for both. This one has the following methods.

[code lang=”java”]public Date getDate( )
public int getInputMode( )
public void setDate(Date date);
public void setInputMode(int mode);

public String toString( ); // output a string-based copy of the date or time

DateField date = new DateField("date", DateField.DATE); //creates a DateField object

/* display a date field */

Form form = new Form("Date Info");
form.append(date);
Display.setCurrent(form);

/* Initialize the date and time before displaying the component */

d = new DateField("Today: ", DateField.DATE);
d.setDate(new Date( ));
form = new Form("Date & Time");
form.append(d);
display.setCurrent(form);

/* Creating a DateField object where the time zone is GMT */

DateField date = new DateField("date", DateField.DATE,TimeZone.getTimeZone("GMT"));

/* Using the default time zone */

DateField date1 = new DateField("date", DateField.DATE);
DateField date2 = new DateField("date", DateField.DATE, TimeZone.getDefault( ));[/code]

2.3.3) Gauge
A Gauge object represents a bar graph display that can be used within a form. It has the following constructor:

[code lang=”java”]public Gauge(String label, boolean interactive, int maxValue, int initialValue);[/code]

This is used to create a new Gauge object with the given label, in interactive or non-interactive mode, with the given maximum and initial values. In interactive mode, we can modify the gauge’s current value; in non-interactive mode, we cannot change the value.

[code lang=”java”] public boolean isInteractive( );//Whether the gauge is currently in interactive mode or not
public int getMaxValue( ); //access the Max value
public int getValue( ); //access the current value
public void setMaxValue(int maxValue); //set the Max value
public void setValue(int value);

/* interactive gauge where the maximum value is 20 and the initial value is 0 */

Gauge gauge = new Gauge("graph", true, 20, 0);

/* placing guage on a Form component */

Form form = new Form("item");
form.append(gauge);

/* non-interactive gauge that reflects the progress bar */

Display display = Display.getDisplay(this);
Gauge progressbar = new Gauge("Progress", false, 20, 9);
Form form = new Form("Configuring App);
form.append(progressbar);[/code]

2.3.4)Image and ImageItem
An ImageItem object is an image component that contains a reference to an Image object. Images can either be immutable or mutable. Immutable images are generally created by loading image data.They cannot be modified after creation. Mutable images, are created in off-screen memory and can be modified. A mutable image can be created using static createImage( ) methods of the Image class.

[code lang=”java”]public static Image createImage(int width, int height);

/* Three static createImage( ) methods used to create immutable images */

public static Image createImage(Image image);
public static Image createImage(String name);
public static Image createImage(byte[] imageData, int imageOffset,int imageLength);

/* Creating an immutable image */

Image image = Image.createImage("image1.png");

/* Placing an Image in a Form object */

Form form = new Form("Form");
form.append(image);

/* Measuring the height, width, and mutable status of a image */

public int getHeight( );
public int getWidth( );
public boolean isMutable( );

/* Getting the Graphics object of an image */

public Graphics getGraphics( );

/* Creating an ImageItem object using the ImageItem constructor */

public ImageItem(String label, Image img, int layout, String altText);

/* Methods to access the properties of the ImageItem constructor */

public String getAltText( );
public Image getImage( );
public int getLayout( );
public void setAltText(String altText);
public void setImage(Image img);
public void setLayout(int layout);

/* Creating the ImageItem object using ImageItem constructor */

Image img = Image.createImage("/Example.png");
ImageItem imageItem = new ImageItem("Image", img, ImageItem.LAYOUT_CENTER, "img");
Form form = new Form("Example");
form.append(imageItem); [/code]

2.3.5) StringItem
A StringItem object is a text component item that contain a string, label, and contents. We cannot edit the string but we can edit the label and contents.Here is the constructor..

[code lang=”java”]public StringItem(String label, String contents);

/* Creating a StringItem object */

StringItem si = new StringItem("string", "contents");

public void setText(String s); // Set the StringItem contents
public void setLabel(String l);// Set the label of the StringItem
public String getText( );// Get the StringItem contents
public String getLabel( );//Get the label of the StringItem

/* Creating a StringItem object placing it within a Form object */

Display display = display.getDisplay(this);
StringItem si = new StringItem("String item:\n", "Hello World!");
Form form = new Form("Greetings");
form.append(si);
display.setCurrent(form);[/code]

2.3.6) TextField
TextField object is an editable text component.A TextField has a capacity, which is the number of characters that can be stored in the object. There must be a boundary on the maximum size,which we can get using getMaxSize( ). TextField is used when the MIDlet requires input from the user. A TextField has the constructor:

[code lang=”java”]public TextField(String label, String text, int maxSize, int constraints); [/code]


The constraints field is used to limit the user input like TextField.ANY, TextField.EMAILADDR, TextField.NUMBER, TextField.PASSWD, TextField.PHONENUMBER, and TextField.URL. Here we have some examples..

[code lang=”java”]public int getConstraints( ); //Retrieve the current constraints
public void setConstrants(int c);//Set the current constraints

public int getMaxSize( ); //Gets Maxsize
public void setMaxSize(int size);// Sets Maxsize

public String getString( ); //Retrieve the text in the TextField
public void setString(String s);//Set the text in the TextField

public int size( );//To get the number of characters in the TextField

/* delete, insert, and replace */

public void delete(int offset, int length);
public void insert(char[] data, int offset, int length, int position);
public void insert(String src, int position);
public void setChars(char[] data, int offset, int length);

public int getCaretPosition( ); //To Find the position of the caret or insertion beam

/* Typical sign in form */

Display display = Display.getDisplay(this);
TextField userName = new TextField("LoginID:", "", 10, TextField.ANY);
TextField password = new TextField("Password:", "", 10, TextField.PASSWORD);
Form form = new Form("Sign in");
form.append(userName);
form.append(password);
display.setCurrent(form);[/code]

3) Conclusion

Herewith we discussed about the Graphical user interface concepts in J2ME. Try the example programs with the help of the methods discussed above.These method names are very much standard and easy to remember, so one time practice is enough to become efficient in J2ME GUI Programming

Filed Under: Mobile Tagged With: J2ME

Introduction to J2ME

July 27, 2007 by Krishna Srinivasan Leave a Comment

1) Introduction

J2ME (Java 2 Micro Edition) is an advanced technology in Java, developed with the help of Java Community Process Program. J2ME is a reduced version of the Java API and Java Virtual Machine that is designed to operate within the limited resources available in the embedded computers and microcomputers.

also read:

  • Writing JSF Application for J2ME Clients
  • ViewPort Meta Tag

J2ME is targeted to developers of intelligent wireless devices and small computing devices who need to incorporate cross-platform functionality in their products. A key benefit of using J2ME is compatibility with all Java-enabled devices. Motorola, Nokia, Panasonic all have Java-enabled devices.A J2ME application is a balance between local and server-side processing.
The Java Community Process Program used a two approaches to addressing the needs of small computing devices.

  • Configurations:It is the Java run-time environment and core classes that operate on each device. A configuration defines the Java Virtual Machine for a particular small computing device. There are two configurations.
    • CLDC for handheld devices:The CLDC (Connected Limited Device Configuration) is designed for 16-bit or 32-bit small computing devices with limited memory. These devices usually have between 160KB and 512KB of available memory. Usually these are powered by battery. They use small-bandwidth network wireless connection. These devices uses a stripped-down version of the JVM the KJava Virtual Machine (KVM). These devices include pagers, personal digital assistants, cell phones, dedicated terminals, and handheld consumer device.
    • CDC for plug-in devices:CDC(Connected Device Configuration) devices use a 32-bit architecture, have at least 2 MB of memory available, and implement a complete functional JVM. CDC devices include digital set-top boxes, home appliances, navigation systems, point-of-sale terminals, and smart phones.
  • Profiles:It is defined for categories of small computing devices. A profile consists of classes that enable developers to implement features found on a related group of small computing devices.List of J2ME Profiles:
    • Profiles Used with CLDC:
      • Mobile Information Device Profile(MIDP)
      • PDA Profile(PDAP)
    • Profiles Used with CDC:
      • Foundation Profile
      • Game Profile
      • Personal Profile
      • Personal Basis Profile
      • RMI Profile.

2)J2ME Architecture

There are 5 layers in J2ME Architecture.Those are:

  • MIDP (TopMost Layer): Which contains Java APIs for user network connections, persistence storage, and the user interface. It also has access to CLDC libraries and MIDP libraries.
  • J2ME API’s(Profiles): Which consists of the minimum set of application programming interfaces for the small computing device
  • Configurations: Which handles interactions between the profile and the JVM.
  • JVM
  • Operating System(Bottom Layer).

1,2 and 3 are software Layers.

3) Midlets.

A MIDlet is a J2ME application which operate on an MIDP. A MIDlet is defined with at least a single class that is derived from the javax.microedition.midlet.MIDlet abstract class. Common programming is grouping related MIDlets into a MIDlet suite, which is contained within the same package and implemented simultaneously. All MIDlets within a MIDlet suite are considered a group and must be installed and uninstalled as a group. MIDlets from the same MIDlet suite run the same class. Benefit of the relationship among MIDlet suite members is that they share the same data.
A MIDlet is an event-based application. All routines executed in the MIDlet are invoked in response to an event reported to the MIDlet by the application manager. The initial event that occurs is when the MIDlet is started and the application manager invokes the startApp() method. The startApp() method in a typical MIDlet contains a statement that displays a screen of data and prompts the user to enter a selection from among one or more options. The nature and number of options is, MIDlet and screen dependent. A Command object is used to present a user with a selection of options to choose from when a screen is displayed. Each screen must have a CommandListener. A CommandListener monitors user events with a screen and causes the appropriate code to execute based on the current event.
Here we dicuss about Application Manager Responsibilities which is running on the device which is provided by the Device manufacturer:

  • Installing, executing, and removing a MIDLet Suite.
  • Giving access to classes of the JVM and CLDC for Each member of the MIDlet suite.
  • Makes the Java archive (JAR) file and the Java application descriptor (JAD) file available to members of the MIDlet suite.

3.1) JAR Files

3.1.1)Something About Manifest File:

  • Nine attributes are defined in this file.The first six attributes are necessary.
  • The file’s extension is changed to .mf when the MIDlet is prepared for deployment.
  • All entries are name:value pairs.
  • Each pair must be terminated with a carriage return.
  • Whitespace between the colon and the attribute value is ignored.

Here are Necessary Attributes of a Manifest File :

  • MIDlet-Name: MIDlet suite name.
  • MIDlet-Version: MIDlet version number.
  • MIDlet-Vendor: Name of the vendor who supplied the MIDlet.
  • MIDlet-n: Attribute per MIDlet. Values are MIDlet name, optional icon, and MIDlet class name.
  • MicroEdition-Profile: Identifies the J2ME profile that is necessary to run the MIDlet.
  • MicroEdition-Configuration: Identifies the J2ME configuration that is necessary to run the MIDlet.

Optional Attributes are

  • MIDlet-Icon: Icon associated with MIDlet, must be in PNG image format.
  • MIDlet-Description: Description of MIDlet.
  • MIDlet-Info-URL: URL containing more information about the MIDlet.

3.2) JAD Files

JAD Files are used to pass parameters to a MIDlet without modifying the JAR file . Also used to provide the application manager with additional content information about the JAR file to determine whether the MIDlet suite can be implemented on the device. There are five necessary attributes for a JAD file:

3.2.1)Something About JAD File

  • Files must have the .jad extension.
  • The values of the MIDlet-Name, MIDlet-Version, and MIDlet-Vendor attributes in the JAD file must match the same attributes in the manifest .
  • All entries are name:value pairs.

Necessary Attributes are

  • MIDlet-Name: MIDlet suite name.
  • MIDlet-Version: MIDlet version number.
  • MIDlet-Vendor: Name of the vendor who supplied the MIDlet.
  • MIDlet-n: Location of the JAR file.
  • MIDlet-Jar-URL: Attribute per MIDlet. Values are MIDlet name, optional icon, and MIDlet class name.

Optional attributes available are

  • MIDlet-Jar-Size: Size of the JAR file in bytes.
  • MIDlet-Data-Size: Minimum size (in bytes) for persistent data storage.
  • MIDlet-Description: Description of MIDlet.
  • MIDlet-Delete-Confirm: Confirmation required before removing the MIDlet suite.
  • MIDlet-Install-Notify: Send installation status to given URL.

3.3) Programs

A MIDlet is a class that extends the MIDlet class and is the interface between application statements and the run-time environment , which is controlled by the application manager . A MIDlet class must contain three abstract methods that are called by the application manager to manage the life cycle of the MIDlet. These abstract methods are.

  • startApp(): called by the application manager when the MIDlet is started and contains statements that are executed each time the application begins execution. Public and have no return value nor parameter list.
  • pauseApp(): called before the application manager temporarily stops the MIDlet. The application manager restarts the MIDlet by recalling the startApp() method. Public and have no return value nor parameter list.
  • destroyApp(): called prior to the termination of the MIDlet by the application manager. Public method without a return value. It has a boolean parameter that is set to true if the termination of the MIDlet is unconditional, and false if the MIDlet can throw a MIDletStateChangeException.

The Basic Midlet Shell.

[code lang=”java”] public class BasicMIDletShell extends MIDlet
{
public void startApp(){ }
public void pauseApp(){ }
public void destroyApp( boolean unconditional){ }
}[/code]

MIDP API classes are used by the MIDlet to interact with the user and handle data management. User interactions are managed by user interface MIDP API classes. These APIs prompt the user to respond with an appropriate command. The command causes the MIDlet to execute one of three routines:

  • Perform a computation.
  • Make a network request.
  • Display another screen.

The data-handling MIDP API classes enable the developer to perform four kinds of data routines:

  • Write and read persistent data.
  • Store data in data types.
  • Receive data from and send data to a network.
  • Interact with the small computing device’s input/output features.

3.4) Differences Between Core Java and Java for J2ME

Major Differences are :

  • Floating-point math is missing in J2ME. MIDlet cannot use any floating-point data types or calculations.
  • Absence of finalize() method in J2ME.
  • Reduced number of error-handling exceptions in J2ME.
  • JVM for small computing devices requires a custom class loader that is supplied by the device manufacturer and cannot be replaced or modified.
  • We cannot group threads. All threads are handled at the object level.
  • The class file verification is replaced with two processes called Preverificaton and Validation. Preverification occurs prior to loading the MIDLet’s and Validation occurs after loading the MIDLet.

4)Simple Example Program

This section shows a simple application. The MIDlet will display the message “ Hi This is My First Program” on the screen. Clicking the Exit button will terminate the MIDlet. The application consists of two classes: the MIDlet subclass called FirstOne and the Canvas subclass called FirstCanvas.

[code lang=”java”]
// **********FirstOne.java************

Package FirstOne;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class FirstOne extends MIDlet implements CommandListener
{
// The canvas is the region of the screen that has been allotted to the game.

FirstCanvas myCanvas;
private Command exitCommand = new Command("Exit", Command.EXIT, 99);
private Command changeCommand = new Command("changeMessage ", Command.SCREEN, 1);

// Initialize the canvas and the commands.

public FirstOne()
{
myCanvas = new FirstCanvas();
myCanvas.addCommand(exitCommand);
myCanvas.addCommand(changeCommand);

// Set one command listener to listen to all of the commands on the canvas

myCanvas.setCommandListener(this);
}

public void startApp() throws MIDletStateChangeException
{
// display my canvas on the screen:
Display.getDisplay(this).setCurrent(myCanvas);
myCanvas.repaint();
}

// If the MIDlet was using resources, it should release them in this method.

public void destroyApp(boolean unconditional)
throws MIDletStateChangeException { }

//MIDlet enters a paused state. The MIDlet should release shared resources.

public void pauseApp() { }

//Respond to a command. Either reset or exit.

public void commandAction(Command c, Displayable s)
{
if(c == changeCommand)
{
myCanvas.changeFirst();
}
else if(c == exitCommand)
{
try {
destroyApp(false);
notifyDestroyed();
} catch (MIDletStateChangeException ex){ }
}
}
}

// *************FirstCanvas.java.***************

package FirstOne;
import javax.microedition.lcdui.*;
//This class represents the region of the screen that has been allotted.

public class FirstCanvas extends Canvas
{
boolean firstDisp = true;

//Change the display message.

void changeMsg()
{
firstDisp = !firstDisp;
repaint();
}

//clear the screen and display the " Hi This is My First Program " message.

public void paint(Graphics g)
{

// get the dimensions of the screen:
int width = getWidth ();
int height = getHeight();

// clear the screen. Setting Screen Color to white:
g.setColor(0xffffff);
g.fillRect(0, 0, width, height);

// display the " Hi This is My First Program " message if appropriate:.
if(firstDisp)
{
Font font = g.getFont();
int fontHeight = font.getHeight();
int fontWidth = font.stringWidth("Hi This is My First Program ");
// set the text color
g.setColor(255, 255, 0);
g.setFont(font);

// write the string in the center of the screen
g.drawString("Hi This is My First Program ", (width – fontWidth)/2,
(height – fontHeight)/2,g.TOP|g.LEFT);
}
}
}[/code]

5) Limitations with J2ME

Some ofthe limitations of J2ME compared with Core JAVA

  • Some J2SE applications require classes that are not available in J2ME.
  • Java applications won’t run in the J2ME environment without requiring modification to the code.
  • Devices that use the CDC configuration use the full Java Virtual Machine implementation, while devices that use the CLDC configuration use the Kjava Virtual Machine implementation.
  • MIDlets are controlled by application management software (AMS). So we cant invoke a MIDLET like a J2SE Application.

6)Conclusion

Herewith we have an introduction to Java 2 Micro Edition. This example is very simle example. It can be executed using editors like NetBeans IDE or J2ME Wireless Toolkit(KToolBar). Using API’s like JSR 135 etc.. try to create more programs and try them in these tools. I will get back to you with more articles on J2ME.Refer this site for more information on starting with J2ME.

Filed Under: Mobile Tagged With: J2ME

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved