3 Solution Jun11

Embed Size (px)

Citation preview

  • 7/27/2019 3 Solution Jun11

    1/17

    PMRC-June 20111-a Explain methods in servlets life cycle. [5 marks]

    Ans. See Jun 2010 paper solution Q2-a.

    1-b List and explain advantages of MIDP. [5 marks]

    Ans. PortabilityThe 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 bespecific to a single platform. An application written using the MIDP APIs will be directlyportable to any MIDP device..

    Security

    MIDP applications offer one important security promise: they can never escape from theconfines 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 messup 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 highlygraphical and intuitive applications. The graphical user interface is optimized for the smalldisplay size, varied input methods, and other native features of modern mobile devices.

    MIDP provides intuitive navigation and data entry by taking full advantage of phonekeypads, extra buttons such as arrow keys, touch screens, and small QWERTY keyboards.MIDP applications are installed and run locally, can operate in both networked andunconnected modes, and can store and manage persistent local data securely.

    Extensive Connectivity: MIDP enables developers to exploit the native data network andmessaging capabilities of mobile information devices. It supports leading connectivitystandards, including HTTP, HTTPS, datagrams, sockets, server sockets, and serial port. MIDP

    also supports the Short Message Service and Cell Broadcast Service capabilities of GSM andCDMA 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 addsgame-specific functionality, such as sprites and tiled layers, which take advantage of

    devices' native graphics capabilities. Built-in audio provides support for tones, tonesequences, 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 updateapplications 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. HTTPSsupport enables applications to use existing standards such as SSL and WTLS to send andreceive encrypted data.

    1-c Compare CLDC 1.0 and CLDC 1.1. [5 Marks]

    See Jun 2010 paper solution Q5-c.

    1-d Explain protocol stack of Bluetooth. [5 Marks]

    Bluetooth is short-ranged radio technology that enables communications for devicesphysically located close to one another. A Bluetooth implementation contains both hardwareand 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 AreaNetwork (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.

  • 7/27/2019 3 Solution Jun11

    2/17

    The Bluetooth stack is made up of many layers, as shown in Figure. The HCI is usually thelayer separating hardware from software and is implemented partially in software and

    hardware/firmware. The layers below the HCI are usually implemented in hardware and thelayers above the HCI are usually implemented in software.

    Layer Description

    Java API for Bluetooth Bluetooth profiles guide developers onhow applications should use the protocol

    stack

    Service Discovery Protocol (SDP) Used for service discovery on remoteBluetooth devices

    RFCOMM Provides an RS-232 like serial interface

    L2CAP Multiplexes data from higher layers andconverts between different packet sizes

    HCI Handles communication between the hostand the Bluetooth module

    Link manager Protocol Controls and configures links to otherDevices

    Link Controller Controls physical links, frequencyhopping and assembling packets

    Radio Hardware Modulates and demodulates data for

    transmission and reception on air

  • 7/27/2019 3 Solution Jun11

    3/17

    2-a Explain architecture of JavaEE5. [10 Marks]

    Ans. The Java EE application model defines architecture for implementing services as multitierapplications that deliver the scalability, accessibility, and manageability needed byenterprise-level applications. This model partitions the work needed to implement a multitierservice into the following parts:

    1. The business and presentation logic to be implemented by the developer2. The standard system services provided by the Java EE platform

    The developer can rely on the platform to provide solutions for the hard systems-levelproblems of developing a multitier service.

    Distributed Multitiered Applications

    The Java EE platform uses a distributed multitiered application model for enterpriseapplications. Application logic is divided into components according to function, and the

    application components that make up a Java EE application are installed on variousmachines, depending on the tier in the multitiered Java EE environment to which theapplication 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 EEmultitiered applications are generally considered to be three-tiered applications because they

    are distributed over three locations: client machines, the Java EE server machine, and thedatabase or legacy machines at the back end. Three-tiered applications that run in this wayextend the standard two-tiered client-and-server model by placing a multi-threadedapplication 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 classesand files and that communicates with other components.

    The Java EE specification defines the following Java EE components.

  • 7/27/2019 3 Solution Jun11

    4/17

    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 componentsthat 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 andstandard Java classes is that Java EE components are assembled into a Java EEapplication, 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 Runs on

    Application clients and applets Client

    Servlet, JSP, JSF Server

    EJB Server

    Java EE Clients

    A Java EE client is usually either:a web client oran application client.

    Web Clients

    A web clientconsists of two parts:

    1. Dynamic web pages containing various types of markup language (HTML, XML, andsoon), which are generated by web components running in the web tier

    2. A web browser, which renders the pages received from the serverA 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 thinclient, such heavyweight operations are off-loaded to enterprise beans executing on the JavaEE server, where they can leverage the security, speed, services, and reliability of Java EEserver-side technologies.

    Application Clients

    An application client runs on a client machine and provides a way for users to handle tasksthat require a richer user interface than can be provided by a markup language. Anapplication 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, ifapplication 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 inlanguages other than Java can interact with Java EE servers, enabling the Java EE platformto 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 Javaprogramming language, an applet is a small client application that executes in the Javavirtual machine installed in the web browser. However, client systems will likely need theJava Plug-in and possibly a security policy file for the applet to successfully execute in theweb browser.

    Web Tire

    Java EE web components are either servlets or web pages created using JavaServer Facestechnology and/or JSP technology (JSP pages). Servlets are Java programming languageclasses that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creatingstatic content. JavaServer Faces technology builds on servlets and JSP technology andprovides a user interface component framework for web applications.

  • 7/27/2019 3 Solution Jun11

    5/17

    Static HTML pages and applets are bundled with web components during applicationassembly 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 notconsidered 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 thebusiness tier or the web tier.

    Enterprise Information System Tier

    The enterprise information system tier handles EIS software and includes enterpriseinfrastructure systems, such as enterprise resource planning (ERP), mainframe transaction

    processing, database systems, and other legacy information systems. For example, Java EEapplication components might need access to enterprise information systems for database

    connectivity.

    2-b Explain the following terms: [10 Marks]

    i) Obfuscator

    Ans. 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 theMIDlet. The methods of this class allow the AMS to create, start, pause, and destroy aMIDlet.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 thusenhances the functionality of the Web server. Servlets are objects that generate dynamiccontent after processing the requests originated from a Web browser. Servlets are usuallydesigned 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, and3. 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. Thisinterface defines the init() method to match the initialization phase of a Servlet life-cycle.

  • 7/27/2019 3 Solution Jun11

    6/17

    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 and2. javax.servlet.ServletResponse object.

    Destruction destroy() method

    It represents the removal of the Servlet from the Container.

    iv) Application descriptor

    Ans. 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 decidewhether or not to load a MIDlet suite. Because an application descriptor is a file separatefrom 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, notjust one MIDlet.

    2. MIDlet-Version: This describes the version of the MIDlet suite. Its a number youpick 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 andstate 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 JavaEE platform APIs.

    Java EE containers can be categorized as follows:1. The Web Container2. The EJB Container3. The Application Client Container4. Applet Container

    The Web Container

    Manages the execution of web pages, servlets, JSP pages for Java EE applications. Webcomponents 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

  • 7/27/2019 3 Solution Jun11

    7/17

    container run on the client.

    Applet Container

    Manages the execution of applets. Consists of a web browser and Java Plug-in running onthe client together.

    3-a Write short note on :- [10 Marks]i. Strutsii. Hibernate

    Ans. See Dec 2010 paper solution Q7-a.

    3-b Write an MIDP application for low level event handling using Canvas class.[10 Marks]

    Ans. 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 KeyCanvas.java: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 KeyCanvasMidlet.java:import javax.microedition.midlet.*;

    import javax.microedition.lcdui.*;

  • 7/27/2019 3 Solution Jun11

    8/17

    public class KeyCanvasMidletextends MIDletimplements CommandListener {

    Display display; // The display for this MIDletCommand 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 Explain Model-1 and Model-2 Architecture. [10 Marks]

    Ans. 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 andfunctionalities provided by the application. Applications using the Model-1 architecturecontain 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 andpresentation 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 HTTPresponses back to the client. A JSP page not only contains display elements, but alsoretrieves HTTP parameters, calls the business logic, and handles the HTTP session.

  • 7/27/2019 3 Solution Jun11

    9/17

    The Model-1 architecture is page-centric and only suitable for small Web applications. Webapplications 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 Webapplications 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 maycase changes in other pages, leading to unpredictable results.

    Involve the developer at both the page development and the business logicimplementation stages. There is no provision for the division of labor between thepage 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 theinput, and ensure security.

    Increases the maintenance effort required per page as a series of JSP pages areincluded in this type of architecture.

    Model-2 ArchitectureThe 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 theServlet. 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. Inthis 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 isaccessed and updated. Model is generally implemented by using JavaBeans.

    View Renders the contents of a model. The View component accesses enterprisedata 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 requestsfrom client, determines the business logic to be performed, and delegates theresponsibility for producing the next phase of the user interface to an appropriateView 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 anapplication. 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.

  • 7/27/2019 3 Solution Jun11

    10/17

    Offers great flexibility to the presentation logic, which can be modified withoutaffecting the business logic.

    Allows each software component to perform a different task, making it easy to designan application by simply embedding these components in the application.

    4-b Write short note on :- [10 Marks]

    i. Image class.

    Ans. See Jun 2010 paper solution Q3-b.

    ii. Alert class.

    Ans. See Dec 2010 paper solution Q4-d.

    5-a Define profile. Explain J2ME profiles. [10 Marks]

    Ans. 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 Provides full AWT support, applet support, and limited bean support.

    Includes all of the Personal Basis Profile APIsPersonal Basis

    Profile

    Provides a limited GUI without full AWT compatibility. Includes all of

    the Foundation Profile APIs.

    Foundation Profile 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

    a) The Foundation Profile

    Foundation Profile is a set of Java APIs that support resource-constrained devices without astandards-based GUI system. Combined with the CDC, Foundation Profile provides acomplete J2ME application environment for consumer products and embedded devices.

    Characteristics:

    Based on J2SE APIsTuned for limited resource environmentsNo GUI support

    Example product scenarios:Network PrintersRouters

    Residential GatewaysEnterprise-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-basedgraphical 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 TelevisionAutomotive

  • 7/27/2019 3 Solution Jun11

    11/17

    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-constraineddevices with a graphical user interface toolkit based on AWT. When combined with theConnected Device Configuration, Personal Profile provides a complete J2ME applicationenvironment 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 compatibilitySupport for the applet application programming modelAll of the application support APIs included in the Personal Basis Profile

    Example product scenarios:High-end PDAsEmbedded 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 developmentenvironment 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 J2SEAbstract 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 astandard 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 astandardized 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 therequirements of the CLDC)A minimum of 128KB of RAM for the Java runtime heapA minimum of 8KB of nonvolatile writable memory for persistent data

    A screen of at least 9654 pixelsSome capacity for input, either by keypad, keyboard, or touch screenTwo-way network connection, possibly intermittent

    Example product scenarios:Cellular phones

  • 7/27/2019 3 Solution Jun11

    12/17

    Two-way pagersWireless-enabled personal digital assistants (PDAs)

    Version:MIDP 1.0 (JSR 37)MIDP 2.0 (JSR 118)

    5-b Create a web page which searches a book by book title and author name using JSP.[10 Marks]

    Ans. Will be updated soon.

    6-a What is MIDlet suite? Explain MIDlet suite security. [10 Marks]

    Ans. MIDlets are deployed in MIDlet suites. A MIDlet suite is a collection of MIDlets with someextra 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 SecurityWireless application security is important to almost everyone involved in the wirelessindustry:

    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 wantcontrol over the network usage of their applications, as network usage often costsmoney.Application developers do not want their applications to be compromised by otherapplications.

    Permissions

    Permissions provide MIDlets with explicit security architecture. MIDlets must have

  • 7/27/2019 3 Solution Jun11

    13/17

    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 orfunctionality.

    Defining permissions:

    Permissions are defined using permission names. Permission names use the same prefix andclass 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 ofjavax.microedition.io.Connector.socket . 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 willbe 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 granted2. 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 givenpermission.

    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 beconsulted

    2. The rules for how a MIDlet suite can get into this protection domainFor example: A very simple protection domain, SimplePD, might contain:

    1. The permission: javax.microedition.io.Connector.http 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 downloadedfrom www.xyz.com, then the AMS on the device would know to place the MIDlet suitein the SimplePD protection domain. At runtime, any MIDlet that tries to make an

    HTTP connection will be granted the permission. Attempts to make other connectiontypes will be denied.

    Untrusted domain:MIDlet suites whose contents and origin cannot be verified are placed in a kind of defaultprotection domain, the untrusted domain. The only restriction placed on the untrusteddomain 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 fora MIDlet suite.2. Session means that the user must grant or deny permission once per invocation of a

  • 7/27/2019 3 Solution Jun11

    14/17

    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, youwould have a line in your descriptor file like this:MIDlet-Permissions: javax.microedition.io.Connector.http

    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 Write an MIDlet application that creates an interactive gauge. [10 Marks]

    Ans. import javax.microedition.midlet.*;import javax.microedition.lcdui.*;

    public class GaugeMidletextends MIDletimplements 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 Explain structure of web application. [10 Marks]

    Ans. See Jun 2010 paper solution Q1-a.

    7-b Explain various classes in Game API. [10 Marks]

    Ans. The Game API builds on the Canvas and Graphics classes. The entire game API is

  • 7/27/2019 3 Solution Jun11

    15/17

    composed of five classes in the javax.microedition.lcdui.game package.1. GameCanvas2. Layer3. LayerManager4. Sprite5. TiledLayer

    One class, GameCanvas, provides methods for animation and key polling. The other fourclasses 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 becombined to create a complete scene. You might, for example, have a background ofmountains, 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. Sprite2. 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 toback. 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

  • 7/27/2019 3 Solution Jun11

    16/17

    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 isdivided 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 thetile 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 intoequally 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 theLayerManager 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 methodchanges 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_NONETRANS_ROT90

  • 7/27/2019 3 Solution Jun11

    17/17

    TRANS_ROT180TRANS_ROT270TRANS_MIRRORTRANS_MIRROR_ROT90TRANS_MIRROR_ROT180TRANS_MIRROR_ROT270