You are on page 1of 17

PMRC-June 2011

1-a Ans. 1-b Ans. Explain methods in servlets life cycle. [5 marks] See Jun 2010 paper solution Q2-a. List and explain advantages of MIDP. [5 marks] Portability The advantage of using Java over using other tools for small device application development is portability. You could write device applications with C or C++, but the result would be specific to a single platform. An application written using the MIDP APIs will be directly portable to any MIDP device.. Security MIDP applications offer one important security promise: they can never escape from the confines of the JVM. This means that, barring bugs, a MIDP application will never be able to write to device memory that doesnt belong to the JVM. A MIDP application will never m ess up another application on the same device or the device OS itself. In MIDP 2.0, MIDlet suites can be cryptographically signed, and then verified on the device, which gives users some security about executing downloaded code. Other benefits Rich User Interface Capabilities: MIDP applications provide the foundation for highly graphical and intuitive applications. The graphical user interface is optimized for the small display size, varied input methods, and other native features of modern mobile devices. MIDP provides intuitive navigation and data entry by taking full advantage of phone keypads, extra buttons such as arrow keys, touch screens, and small QWERTY keyboards. MIDP applications are installed and run locally, can operate in both networked and unconnected modes, and can store and manage persistent local data securely. Extensive Connectivity: MIDP enables developers to exploit the native data network and messaging capabilities of mobile information devices. It supports leading connectivity standards, including HTTP, HTTPS, datagrams, sockets, server sockets, and serial port. MIDP also supports the Short Message Service and Cell Broadcast Service capabilities of GSM and CDMA networks, through the Wireless Messaging API (WMA) optional package. Multimedia and Game Functionality: MIDP is ideal for building portable games and multimedia applications. A low-level user-interface API complements the high-level UI API, giving developers greater control of graphics and input when they need it. A game API adds game-specific functionality, such as sprites and tiled layers, which take advantage of devices' native graphics capabilities. Built-in audio provides support for tones, tone sequences, and WAV files. In addition, developers can use the Mobile Media API (MMAPI) optional package to add video and other rich multimedia content to MIDP applications. Over-the-Air-Provisioning: A major benefit of MIDP is its capability to deploy and update applications dynamically and securely, over the air. End-to-End Security: MIDP provides a robust security model that complies with open standards and protects the network, applications, and mobile information devices. HTTPS support enables applications to use existing standards such as SSL and WTLS to send and receive encrypted data. 1-c Compare CLDC 1.0 and CLDC 1.1. [5 Marks] See Jun 2010 paper solution Q5-c. Explain protocol stack of Bluetooth. [5 Marks] Bluetooth is short-ranged radio technology that enables communications for devices physically located close to one another. A Bluetooth implementation contains both hardware and software components (and software in ROM, also known as firmware), as illustrated in Figure. A network consisting of devices connected via Bluetooth is often called a Personal Area Network (or PAN for short). The software portion of a Bluetooth stack enables data to be interchanged between locally connected devices in a variety of ways.


The Bluetooth stack is made up of many layers, as shown in Figure. The HCI is usually the layer separating hardware from software and is implemented partially in software and hardware/firmware. The layers below the HCI are usually implemented in hardware and the layers above the HCI are usually implemented in software.

Layer Java API for Bluetooth Service Discovery Protocol (SDP) RFCOMM L2CAP HCI Link manager Protocol Link Controller Radio Hardware

Description Bluetooth profiles guide developers on how applications should use the protocol stack Used for service discovery on remote Bluetooth devices Provides an RS-232 like serial interface Multiplexes data from higher layers and converts between different packet sizes Handles communication between the host and the Bluetooth module Controls and configures links to other Devices Controls physical links, frequency hopping and assembling packets Modulates and demodulates data for transmission and reception on air

2-a Ans.

Explain architecture of JavaEE5. [10 Marks] The Java EE application model defines architecture for implementing services as multitier applications that deliver the scalability, accessibility, and manageability needed by enterprise-level applications. This model partitions the work needed to implement a multitier service into the following parts: 1. The business and presentation logic to be implemented by the developer 2. The standard system services provided by the Java EE platform The developer can rely on the platform to provide solutions for the hard systems-level problems of developing a multitier service. Distributed Multitiered Applications The Java EE platform uses a distributed multitiered application model for enterprise applications. Application logic is divided into components according to function, and the application components that make up a Java EE application are installed on various machines, depending on the tier in the multitiered Java EE environment to which the application component belongs. Figure shows Java EE architecture divided into the tiers described in the following list. Client-tier- components run on the client machine. Web-tier- components run on the Java EE server. Business-tier- components run on the Java EE server. Enterprise information system (EIS)-tier software runs on the EIS server.

Figure: Java EE Architecture Although a Java EE application can consist of the three or four tiers shown in Figure, Java EE multitiered applications are generally considered to be three-tiered applications because they are distributed over three locations: client machines, the Java EE server machine, and the database or legacy machines at the back end. Three-tiered applications that run in this way extend the standard two-tiered client-and-server model by placing a multi-threaded application server between the client application and back-end storage. Java EE Components Java EE applications are made up of components. A Java EE component is a self-contained functional software unit that is assembled into a Java EE application with its related classes and files and that communicates with other components. The Java EE specification defines the following Java EE components.

Application clients and applets are components that run on the client. Java Servlet, JavaServer Faces, and JavaServer Pages (JSP) technology components are web components that run on the server. Enterprise JavaBeans (EJB) components (enterprise beans) are business components that run on the server. Java EE components are written in the Java programming language and are compiled in the same way as any program in the language. The difference between Java EE components and standard Java classes is that Java EE components are assembled into a Java EE application, are verified to be well formed and in compliance with the Java EE specification, and are deployed to production, where they are run and managed by the Java EE server. Component Application clients and applets Servlet, JSP, JSF EJB Java EE Clients A Java EE client is usually either: a web client or an application client. Web Clients A web client consists of two parts: 1. Dynamic web pages containing various types of markup language (HTML, XML, and soon), which are generated by web components running in the web tier 2. A web browser, which renders the pages received from the server A web client is sometimes called a thin client. Thin clients usually do not query databases, execute complex business rules, or connect to legacy applications. When you use a thin client, such heavyweight operations are off-loaded to enterprise beans executing on the Java EE server, where they can leverage the security, speed, services, and reliability of Java EE server-side technologies. Application Clients An application client runs on a client machine and provides a way for users to handle tasks that require a richer user interface than can be provided by a markup language. An application client typically has a graphical user interface (GUI) created from the Swing or the Abstract Window Toolkit (AWT) API, but a command-line interface is certainly possible. Application clients directly access enterprise beans running in the business tier. However, if application requirements warrant it, an application client can open an HTTP connection to establish communication with a servlet running in the web tier. Application clients written in languages other than Java can interact with Java EE servers, enabling the Java EE platform to interoperate with legacy systems, clients, and non-Java languages. Applets A web page received from the web tier can include an embedded applet. Written in the Java programming language, an applet is a small client application that executes in the Java virtual machine installed in the web browser. However, client systems will likely need the Java Plug-in and possibly a security policy file for the applet to successfully execute in the web browser. Web Tire Java EE web components are either servlets or web pages created using JavaServer Faces technology and/or JSP technology (JSP pages). Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are textbased documents that execute as servlets but allow a more natural approach to creating static content. JavaServer Faces technology builds on servlets and JSP technology and provides a user interface component framework for web applications. Runs on Client Server Server

Static HTML pages and applets are bundled with web components during application assembly but are not considered web components by the Java EE specification. Server-side utility classes can also be bundled with web components and, like HTML pages, are not considered web components. As shown in Figure, the web tier, like the client tier, might include a JavaBeans component to manage the user input and send that input to enterprise beans running in the business tier for processing. Business Tier Business code, which is logic that solves or meets the needs of a particular business domain, such as banking, retail, or finance, is handled by enterprise beans running in either the business tier or the web tier. Enterprise Information System Tier The enterprise information system tier handles EIS software and includes enterprise infrastructure systems, such as enterprise resource planning (ERP), mainframe transaction processing, database systems, and other legacy information systems. For example, Java EE application components might need access to enterprise information systems for database connectivity. 2-b Ans. Explain the following terms: [10 Marks] i) Obfuscator See Jun 2010 paper solution Q5-a. ii) MIDlet A MIDlet is a Mobile Information Device Profile (MIDP) application. MIDP applications are represented by instances of the javax.microedition.midlet.MIDlet class. The application must extend this class to allow the application management software (AMS) to control the MIDlet. The methods of this class allow the AMS to create, start, pause, and destroy a MIDlet. protected abstract void startApp() throws MIDletStateChangeException Signals the MIDlet that it has entered the Active state. protected abstract void pauseApp() Signals the MIDlet to enter the Paused state. protected abstract void destroyApp(boolean unconditional) throws MIDletStateChangeException Signals the MIDlet to terminate and enter the Destroyed state. iii) Servlet A Servlet is a simple Java class, which is dynamically loaded on a Web server and thus enhances the functionality of the Web server. Servlets are objects that generate dynamic content after processing the requests originated from a Web browser. Servlets are usually designed to process HTTP requests, such as GET, and POST. For writing the Servlets, the javax.servlet and javax.servlet.http packages provide interfaces and classes. Servlets follow a three-phase life namely: 1. Initialization, 2. Service, and 3. Destruction. Initialization init() method It represents the creation and initialization of resources the Servlet may need in response to service requests. All Servlets must implement the javax.servlet.Servlet interface. This interface defines the init() method to match the initialization phase of a Servlet life-cycle.

As soon as a container loads a Servlet, it invokes the init() method prior to servicing any requests. Service service() mehtod It represents all interactions along with requests until the Servlet is destroyed and is solely responsible for generating the response to that request. The service() method of a Servlet is invoked once as per the request. The Servlet specification defines the service() method to take two parameters, which are: 1. javax.serviet.ServletRequest and 2. javax.servlet.ServletResponse object. Destruction destroy() method It represents the removal of the Servlet from the Container. iv) Application descriptor Application descriptor, which is a simple text file. This is a file with a .jad extension that describes the MIDlet suite JAR. The application descriptor contains information that helps a device and/or the users decide whether or not to load a MIDlet suite. Because an application descriptor is a file separate from the MIDlet suite JAR, it is easy for a device to load and examine the file before downloading the MIDlet suite. The application descriptor must contain following attribures: 1. MIDlet-Name: This attribute actually refers to the name of the entire MIDlet suite, not just one MIDlet. 2. MIDlet-Version: This describes the version of the MIDlet suite. Its a number you pick yourself in the form major.minor.micro 3. MIDlet-Vendor: This is your name or the name of your company. 4. MIDlet-Jar-URL: This is the URL where the MIDlet suite JAR can be found. 5. MIDlet-Jar-Size: This is the size, in bytes, of the MIDlet suite JAR. The application descriptor can optionally contain the MIDlet-Description, MIDlet-Icon, MIDlet-Info-URL, and MIDlet-Data-Size attributes. v) Containers Containers are the interface between a component and the low-level platform-specific functionality that supports the component. Containers provide services like transaction and state management, multithreading, resource pooling, and other complex low-level details. The container also manages non-configurable services, such as enterprise bean and servlet life cycles, database connection resource pooling, data persistence, and access to the Java EE platform APIs. Java EE containers can be categorized as follows: 1. The Web Container 2. The EJB Container 3. The Application Client Container 4. Applet Container The Web Container Manages the execution of web pages, servlets, JSP pages for Java EE applications. Web components and their container run on the Java EE server. The EJB Container Manages the execution of enterprise beans for Java EE applications. Enterprise beans and their container run on the Java EE server. The Application Client Container Manages the execution of application client components. Application clients and their


container run on the client. Applet Container Manages the execution of applets. Consists of a web browser and Java Plug-in running on the client together. 3-a Ans. 3-b Ans. Write short note on :- [10 Marks] i. Struts ii. Hibernate See Dec 2010 paper solution Q7-a. Write an MIDP application for low level event handling using Canvas class. [10 Marks] The following example listens for key presses in the keyPressed() method. It converts the key code to a game action and displays the game action on the screen. Code for import javax.microedition.lcdui.*; public class KeyCanvas extends Canvas { Font mFont; String mMessage = "[Press keys]"; public KeyCanvas() { mFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_PLAIN, Font.SIZE_MEDIUM); } public void paint(Graphics g) { int w = getWidth(); int h = getHeight(); // Clear the Canvas. g.setGrayScale(255); g.fillRect(0, 0, w - 1, h - 1); g.setGrayScale(0); g.drawRect(0, 0, w - 1, h - 1); g.setFont(mFont); int x = w / 2; int y = h / 2; g.drawString(mMessage, x, y, Graphics.BASELINE | Graphics.HCENTER); } protected void keyPressed(int keyCode) { int gameAction = getGameAction(keyCode); switch(gameAction) { case UP: mMessage = "UP"; break; case DOWN: mMessage = "DOWN"; break; case LEFT: mMessage = "LEFT"; break; case RIGHT: mMessage = "RIGHT"; break; case FIRE: mMessage = "FIRE"; break; case GAME_A: mMessage = "GAME_A"; break; case GAME_B: mMessage = "GAME_B"; break; case GAME_C: mMessage = "GAME_C"; break; case GAME_D: mMessage = "GAME_D"; break; default: mMessage = ""; break; } repaint(); } } Code for import javax.microedition.midlet.*; import javax.microedition.lcdui.*;

public class KeyCanvasMidlet extends MIDlet implements CommandListener { Display display; // The display for this MIDlet Command exitCommand; // The exit command KeyCanvas keyCanvas; public KeyCanvasMidlet() { keyCanvas = new KeyCanvas(); exitCommand = new Command("Exit", Command.EXIT, 0); keyCanvas.addCommand(exitCommand); keyCanvas.setCommandListener(this); } public void startApp() { if(display == null) display = Display.getDisplay(this); display.setCurrent(keyCanvas); } public void commandAction(Command c, Displayable s) { if (c == exitCommand) { notifyDestroyed(); } } public void pauseApp() { } public void destroyApp(boolean unconditional) { } } 4-a Ans. Explain Model-1 and Model-2 Architecture. [10 Marks] Model-1 Architecture The Model-1 architecture was the first development model used to develop Web applications. This model uses JSP to design applications, which is responsible for activities and functionalities provided by the application. Applications using the Model-1 architecture contain a number of JSP pages, with each page providing different functionality and view to different users.

Figure: Model-1 Architecture In the Model-1 architecture, Web applications are developed by mixing the business and presentation logic. In this model, JSP pages receive HTTP requests, which are then transferred to the data layer by JavaBeans. After the requests are serviced, JSPs send HTTP responses back to the client. A JSP page not only contains display elements, but also retrieves HTTP parameters, calls the business logic, and handles the HTTP session.

The Model-1 architecture is page-centric and only suitable for small Web applications. Web applications implementing this type of architecture have series of JSP pages, where a user navigates from one page to another. The Model-1 architecture is not suitable for large Web applications because of some limitations. Despite its simple structure and easy to learn features, the Model-1 architecture was not successful for designing large projects because of the following limitations: Applications are inflexible and difficult to maintain. A single change in one page may case changes in other pages, leading to unpredictable results. Involve the developer at both the page development and the business logic implementation stages. There is no provision for the division of labor between the page designer and the business logic developer. Increases the complexity of a program with the increase ib the size of the JSP page; therefore, it is difficult to trace the flow of control and debug the program. Requires the responsibility of each page to handle the Web application, verify the input, and ensure security. Increases the maintenance effort required per page as a series of JSP pages are included in this type of architecture. Model-2 Architecture The drawbacks in the Model-1 architecture led to the introduction of a new model, called Model-2. Initially, JSPs were introduced as an alternative to Sevlets, as JSP is more powerful than the Servlet. Developers soon realized that JSPs and Servlets can be used together to develop a Web application. Servlets handle the control flow while JSPs handle the HTML page creation. The approach of using JSPs and Servlets together evolved as the Model-2 architecture. In this type of design model, the presentation logic is separated from the business logic.

Figure: Model-2 Architecture Model-2 architecture is based on the MVC design model. The Model-2 architecture (or MVC) contains the following components: Model Represents enterprise data and business rules that specify how data is accessed and updated. Model is generally implemented by using JavaBeans. View Renders the contents of a model. The View component accesses enterprise data through the Model component and specifies how that data should be presented. The View component is designed by using JSP. Controller Receives HTTP requests. The Controller component receives requests from client, determines the business logic to be performed, and delegates the responsibility for producing the next phase of the user interface to an appropriate View component. The Controller has complete control over each View, implying that any change in the Model component is immediately reflected in all the Views of an application. The Controller component is implemented by Servlets. Advantages: Allows use of reusable software components to design the business logic. Therefore, these components can be used in the business logic of other applications.

Offers great flexibility to the presentation logic, which can be modified without affecting the business logic. Allows each software component to perform a different task, making it easy to design an application by simply embedding these components in the application. 4-b Ans. Write short note on :- [10 Marks] i. Image class. See Jun 2010 paper solution Q3-b. ii. Alert class. See Dec 2010 paper solution Q4-d. Define profile. Explain J2ME profiles. [10 Marks] A profile is layered on top of a configuration, specifies the APIs and specifications necessary to develop applications for a specific family of devices. Personal Profile Personal Basis Profile Foundation Profile Provides full AWT support, applet support, and limited bean support. Includes all of the Personal Basis Profile APIs Provides a limited GUI without full AWT compatibility. Includes all of the Foundation Profile APIs. Provides basic application-support classes such as network support & I/O support. It does not include any support for graphics or GUI services. Profiles based on CDC

Ans. 5-a Ans.

a) The Foundation Profile Foundation Profile is a set of Java APIs that support resource-constrained devices without a standards-based GUI system. Combined with the CDC, Foundation Profile provides a complete J2ME application environment for consumer products and embedded devices. Characteristics: Based on J2SE APIs Tuned for limited resource environments No GUI support Example product scenarios: Network Printers Routers Residential Gateways Enterprise-Class Server Applications Version: Foundation Profile 1.0 (JSR-46) Foundation Profile 1.1 (JSR-219) b) Personal Basis Profile Personal Basis Profile is suitable for product design scenarios that require a standards-based graphical user interface (GUI) without full AWT compatibility. Characteristics: A GUI framework for building lightweight component toolkits. All of the application support APIs included in the Foundation Profile. Example product scenarios: Interactive Television Automotive

Fixed-purpose consumer devices (e.g. camcorders) Version: Personal Basis Profile 1.0 (JSR-129) Personal Basis Profile 1.1 (JSR-217) c) Personal Profile Personal Profile is a superset of Personal Basis Profile that supports resource-constrained devices with a graphical user interface toolkit based on AWT. When combined with the Connected Device Configuration, Personal Profile provides a complete J2ME application environment for consumer products and embedded devices. Personal Profile is suitable for product design scenarios that require full AWT compatibility and applet support. Characteristics: Full AWT compatibility Support for the applet application programming model All of the application support APIs included in the Personal Basis Profile Example product scenarios: High-end PDAs Embedded Web browsers Version: Personal Profile 1.0 (JSR-62) Profiles based on CLDC: a) Personal Digital Assistant Profile (PDAP) The PDA Profile (PDAP), which is built on CLDC, is designed for application development environment for PDAs. Characteristics: Minimum of 512KB combined ROM and RAM (and a maximum of 16MB). It includes an application model based on MIDlets but uses a subset of the J2SE Abstract Windowing Toolkit (AWT) for graphic user interface. Version: Personal Digital Assistance Profile 1.0 (JSR-75) b) Mobile Information Device Profile (MIDP) The Mobile Information Device Profile (MIDP) when combined with the CLDC provides a standard Java runtime environment for today's most popular mobile information devices, such as cell phones and mainstream personal digital assistants (PDAs). CLDC and MIDP provide the core application functionality required by mobile applications, in the form of a standardized Java runtime environment and a rich set of Java APIs. Characteristics: A minimum of 256KB of ROM for the MIDP implementation (this is in addition to the requirements of the CLDC) A minimum of 128KB of RAM for the Java runtime heap A minimum of 8KB of nonvolatile writable memory for persistent data A screen of at least 9654 pixels Some capacity for input, either by keypad, keyboard, or touch screen Two-way network connection, possibly intermittent Example product scenarios: Cellular phones

Two-way pagers Wireless-enabled personal digital assistants (PDAs) Version: MIDP 1.0 (JSR 37) MIDP 2.0 (JSR 118)

5-b Ans. 6-a Ans.

Create a web page which searches a book by book title and author name using JSP. [10 Marks] Will be updated soon. What is MIDlet suite? Explain MIDlet suite security. [10 Marks] MIDlets are deployed in MIDlet suites. A MIDlet suite is a collection of MIDlets with some extra information. There are two files involved. 1. One is an application descriptor, which is a simple text file. 2. The other is a JAR (java archive) file that contains the class files and resource files (images and other files) that make up your MIDlet suite. Like any JAR file, a MIDlet suites JAR file has a manifest file.

Figure: Structure of a MIDlet suite MIDlet Suite Security Wireless application security is important to almost everyone involved in the wireless industry: Carriers want to be sure that viruses do not bring down their customers devices or their networks. Device manufacturers dont want customer-installed software crashing their devices. Users want to be able to run downloaded code without threatening the stability of their device or the safety of their personal information. Additionally, they may want control over the network usage of their applications, as network usage often costs money. Application developers do not want their applications to be compromised by other applications. Permissions Permissions provide MIDlets with explicit security architecture.

MIDlets must have

permission to perform sensitive operations (like accessing network API). The only parts of the API that are protected by permissions are the network connections. Optional APIs are free to define additional permissions to protect sensitive data or functionality. Defining permissions: Permissions are defined using permission names. Permission names use the same prefix and class or interface name as the API that they protect. Example: Suppose that you write a MIDlet that needs to make a socket connection. This MIDlet would need the permission of The MIDlet itself needs no knowledge of permissions. It simply attempts the connection, which either succeeds or throws a java.lang.SecurityException. Method to check if permission is granted or not: There is a method in the MIDlet class that programmers can use to check if a permission will be granted or denied: public final int checkPermission(String permission) Parameters: String permission: permission name to check if denied, allowed, or unknown. Returns: 1. 1 if the permission is granted 2. 0 if the permission is denied. 3. -1 indicates that the implementation cannot determine whether the permission will be granted or denied, which might be the case if the user will be asked about the given permission. Protection Domains MIDlet suites belong to protection domains that determine which permissions are granted, which are denied, and which ones must be deferred to the users judgment. A protection domain is kind of like a secret club. It comprises two parts: 1. The set of permissions that are allowed and those for which the user must be consulted 2. The rules for how a MIDlet suite can get into this protection domain For example: A very simple protection domain, SimplePD, might contain: 1. The permission: 2. The rules for membership in SimplePD could be something as simple as verifying the origin IP address of the MIDlet suite. For example, if the MIDlet suite is downloaded from, then the AMS on the device would know to place the MIDlet suite in the SimplePD protection domain. At runtime, any MIDlet that tries to make an HTTP connection will be granted the permission. Attempts to make other connection types will be denied. Untrusted domain: MIDlet suites whose contents and origin cannot be verified are placed in a kind of default protection domain, the untrusted domain. The only restriction placed on the untrusted domain is that, given explicit confirmation from the user, it must allow MIDlets access to HTTP and HTTPS connections. Permission Types The protection domain contains: 1. The permissions that will be granted to MIDlets (allowed permissions) 2. The permissions for which the user must be consulted (user permissions) User permissions: There are several varieties of user permissions. 1. Blanket means that the user is only required to grant or deny the permission once for a MIDlet suite. 2. Session means that the user must grant or deny permission once per invocation of a

MIDlet suite. 3. Oneshot indicates that the user must be consulted each time the necessary permission is needed. If your MIDlet suite needs certain permissions, use the MIDlet-Permissions attribute. For example, if your MIDlet suite needs to make HTTP connections to function correctly, you would have a line in your descriptor file like this: MIDlet-Permissions: Multiple permission types are placed on the same line, separated by commas. Optional permissions: If your MIDlet suite does not need certain permissions to function, but it may use them for enhanced functionality, these permissions can be placed in the MIDlet-Permissions-Opt attribute. 6-b Ans. Write an MIDlet application that creates an interactive gauge. [10 Marks] import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class GaugeMidlet extends MIDlet implements CommandListener { Display display; Form gaugeForm; Command exitCommand; Gauge interactiveGauge; public GaugeMidlet() { gaugeForm = new Form("Gauges"); interactiveGauge = new Gauge("Interactive", true, 5, 2); gaugeForm.append(interactiveGauge); exitCommand = new Command("Exit", Command.EXIT, 0); gaugeForm.addCommand(exitCommand); gaugeForm.setCommandListener(this); } public void startApp() { if (display == null) display = Display.getDisplay(this); display.setCurrent(gaugeForm); } public void commandAction(Command c, Displayable s) { if (c == exitCommand) notifyDestroyed(); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } } 7-a Ans. 7-b Ans. Explain structure of web application. [10 Marks] See Jun 2010 paper solution Q1-a. Explain various classes in Game API. [10 Marks] The Game API builds on the Canvas and Graphics classes. The entire game API is

composed of five classes in the package. 1. GameCanvas 2. Layer 3. LayerManager 4. Sprite 5. TiledLayer One class, GameCanvas, provides methods for animation and key polling. The other four classes deal with layers, which can be used to compose scenes from several different elements. GameCanvas class GameCanvas extends javax.microedition.lcdui.Canvas with methods for animation and key state polling. To use GameCanvas, you subclass it. To draw on the screen, you use the Graphics returned from getGraphics(). When you want updates to appear on the screen, call flushGraphics(), which does not return until the screen is updated. For more specific updates, use the method flushGraphics(int x, int y, int width, int height), which only updates a region of the screen. The rest of the Game API is devoted to layers. Layers are graphic elements that can be combined to create a complete scene. You might, for example, have a background of mountains, another background of city buildings, and several smaller items in the foreground: people, spaceships, cars, whatever. Layer class Layer class represents a layer. Layer is abstract, with two concrete subclasses: 1. Sprite 2. TiledLayer Layer has a location, a size, and can be visible or invisible. The location and size are accessed and modified with the following methods: public final int getX() public final int getY() public final int getWidth() public final int getHeight() public void setPosition(int x, int y) Layer also offers a handy method for moving relative to the current position. Pass pixel offsets to the following method to adjust the position of the layer: public void move(int dx, int dy) The layers visibility is accessed using getVisible() and setVisible(). The last method in Layer is paint(), which is declared abstract. Subclasses override this method to define their appearance. LayerManager Class LayerManagers job is keeping an ordered list of layers. To create a LayerManager, just call its no-argument constructor. Layers have an index, which indicates their position front to back. A position of 0 is on top, closest to the user, while larger indices are farther away, towards the bottom. Layers may be added to the bottom of the list using this method: public void append(Layer l) You can add a layer at a specific location using insert(): public void insert(Layer l, int index) You can find the number of layers in the LayerManager by calling getSize(). If youd like to retrieve the layer at a certain position, pass the index to the getLayerAt() method. Finally, you can remove a layer by passing the Layer object to the remove() method. LayerManager includes the concept of a view window, which is the rectangular portion of the

scene that will be drawn. You can set the view window using the following method, where the x and y coordinates are relative to the origin of the LayerManager. public void setViewWindow(int x, int y, int width, int height) To actually draw the scene represented by the LayerManagers layers, call the paint() method: public void paint(Graphics g, int x, int y) TiledLayer Class A tiled layer is made from a palette of tiles. The tiles come from a single image that is divided into equal-sized pieces. Tiles are numbered starting at one. The tiled layer itself is a grid of cells, where each cell is occupied by one tile. To create a TiledLayer, supply the number of columns and rows, the source image, and the tile dimensions to the constructor: public TiledLayer(int columns, int rows, Image image, int tileWidth, int tileHeight) The number of columns and rows in a TiledLayer can be retrieved with getColumns() and getRows(). To retrieve the tile dimensions, use getCellWidth() and getCellHeight(). A TiledLayer is empty when you first create it. To assign a tile to a cell, use this method: public void setCell(int col, int row, int tileIndex) All the cells in the TiledLayer are initially filled with tile index 0, which indicates a blank tile. You can retrieve the tile index of a particular cell by passing its column and row number to getCell(). If you would like to assign the same tile to a range of cells, use the fillCells() method: public void fillCells(int col, int row, int numCols, int numRows, int tileIndex) Sprite Class While a TiledLayer uses a palette of tiles to fill a large area, a Sprite uses a palette of tiles to animate a layer that is the same size as a single tile. In Sprite, tiles are called frames instead. As with a TiledLayer, a Sprite is created from a source image that is divided into equally sized frames. public Sprite(Image image, int frameWidth, int frameHeight) Theres also a special caseif the image contains just one frame, it will not be animated: public Sprite(Image image) Sprite cannot be created from separate frame images; the frames must be packed into a single source image. If you want to change the source image after the Sprite is created, use setImage(): public void setImage(Image img, int frameWidth, int frameHeight) The total number of frames contained in the Sprite is returned from getRawFrameCount(). Like any other Layer, Sprites are rendered when the paint() method is called. Usually the Sprite will belong to a LayerManager, in which case it is rendered automatically when the LayerManager is rendered. Sprite animation is all about frame sequences. When a Sprite is created, it has a default frame sequence that includes every frame in the source image. The following method changes the current frame sequence: public void setFrameSequence(int[] sequence) To move forward and backward in the sequence, use nextFrame() and prevFrame(). Sprite includes support for transformations so that you can use the API to generate additional frames that are simple transformations of existing frames. The following method applies a transformation to a Sprite: public void setTransform(int transform) The transform argument can be any of the constant values defined in the Sprite class: TRANS_NONE TRANS_ROT90