Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 52
Текст из файла (страница 52)
The request includes the name the user entered into theapplication settings and the response includes the user’s unique ID andany claimants, of which there are none in this instance.276MIDP 2.0 CASE STUDIES<etsync><req lastSyncId="0" userId="0"><userupdate name="Yossarian" /></req></etsync><?xml version="1.0" encoding="UTF-8" standalone="yes"?><etsync><resp sid="424"><mainuser name="Yossarian" id="2"></mainuser></resp></etsync>The next exchange retrieves the expenses that already exist for theuser.
Note how the last sync ID remains 0 for the request to ensure thatall expenses are exchanged:<etsync><req lastSyncId="0" userId="2"></req></etsync><?xml version="1.0" encoding="UTF-8" standalone="yes"?><etsync><resp sid="425"><expense><owner>2</owner><state>4</state><type>0</type><receiptdate>2003-06-09+00:00</receiptdate><amount>1299</amount><currency>£ </currency><vatpercentage>1750</vatpercentage><project>3</project><dept>2</dept><createdate>2003-06-11T19:52:46.000+00:00</createdate><lastsyncid>367</lastsyncid><ownernotes>one</ownernotes><bhnotes></bhnotes></expense><expense><owner>2</owner><state>2</state><type>2</type><receiptdate>2003-06-16+00:00</receiptdate><amount>2197</amount><currency>$ </currency><vatpercentage>1750</vatpercentage><project>0</project><dept>0</dept><createdate>2003-06-16T08:55:21.000+00:00</createdate><lastsyncid>381</lastsyncid><ownernotes></ownernotes><bhnotes></bhnotes></expense></resp></etsync>THE EXPENSE APPLICATION277The final XML request shows a new expense claim being submitted tothe server:<etsync><req lastSyncId="436" userId="2"><expense><owner>2</owner><state>2</state><type>0</type><receiptdate>2003-12-09</receiptdate><amount>1299</amount><currency>£</currency><vatpercentage>1750</vatpercentage><project>0</project><dept>0</dept><createdate>2003-12-09T11:22:20</createdate><lastsyncid>437</lastsyncid><ownernotes>hello world</ownernotes><bhnotes></bhnotes></expense></req></etsync>A discussion of how the requests are processed on the server takesplace in the next section.5.2.7 Implementation of the Web Server ComponentsApache Tomcat is used to provide the server functionality for the expenseapplication.
Java Server Pages (JSP) are used in conjunction with JavaBeans to provide a view of existing expenses. A servlet is used forthe synchronization process. This section gives an overview of the webapplication.Figures 5.9 and 5.10 are examples of the main web pages for theexpense application. The first image shows all the expenses in the systemfor a single user, the second shows the full details of an expense item.The web application uses a relational database management system(RDBMS) to store the expenses and user information. The schema forthe database has just three tables. A homegrown library is used tosimplify the database code, allowing a simple mapping of a databasetable to a Java class.
See the source code on the support website atwww.symbian.com/books for more information.The most complex part of the server is the synchronization servlet. AllXML parsing uses the Java API for XML Binding (JAXB). JAXB was used tocreate a class hierarchy from the XML schema: if the schema changes theclasses can be automatically regenerated as part of the build process toensure that they always correctly map to the XML stream.When the servlet receives a synchronization request, JAXB is used tounmarshal the information into an object hierarchy that is used to process278MIDP 2.0 CASE STUDIESFigure 5.9Expenses list for a user.Figure 5.10 Expense item details.the request.
A response is built by creating an object hierarchy fromclasses generated by JAXB. Once processing is complete, the responsehierarchy is marshaled into an XML stream and sent back to the device.The synchronization servlet does not handle any XML directly.JAXB is available from Sun as part of the Java Web Services Toolkit.THE EXPENSE APPLICATION5.2.8279Building the MIDletThis next section details the build and run scripts that were used duringthe development. The scripts are modified versions of batch files that areincluded with Sun’s Wireless Toolkit.5.2.8.1 Build ScriptThe build script performs the following operations:1. It builds the Java source into class files.2.
It packages the classes into a Java archive (JAR).3. It reduces the application size using obfuscation.4. It pre-verifies the application ready for deployment.5. It updates the Java application descriptor (JAD) file with the correctapplication JAR file size.Building the Class FilesSun’s Java Development Kit (JDK) is used to build the class files from theJava source files. The javac command line is fairly standard apart froman additional parameter to specify that the J2ME libraries should be usedto provide the bootstrap classes:javac -bootclasspath %WTK_HOME%\lib/midpapi.zip -d build\classes-classpath build\classes src/java/org/xmlpull/v1/*.javasrc/java/org/kxml2/io/*.java src/java/midlet/utils/*.javasrc/java/midlet/model/*.java src/java/midlet/view/*.javasrc/java/midlet/uitools/*.java src/java/midlet/sync/*.javaPackaging into a Java ArchiveAn application JAR file is created from the classes.
The obfuscationprocess requires separate input and output JAR files. For this reason anintermediate filename of ExpenseTrackerTemp.jar is used for theinitial packaging operation.jar cmf src\meta\MANIFEST.MF build\ExpenseTrackerTemp.jar-C build\classes .ObfuscatingObfuscation must be performed prior to pre-verification. If pre-verificationis performed first, the obfuscation process invalidates the pre-verificationchecksums and the MIDlet will not run.Sun’s Wireless Toolkit ships with the Proguard obfuscation library (seehttp://proguard.sourceforge.net). To use Proguard, a configuration file280MIDP 2.0 CASE STUDIESmust be created that contains the options for the obfuscation process.The file is passed to Proguard as a command line parameter, as follows.If obfuscation is not required, the command should be commented out ofthe build script.java -jar lib\proguard.jar @proguard.txtThe contents of the configuration file, proguard.txt, follow:-libraryjars /wtk20/lib/midpapi.zip-injars build/ExpenseTrackerTemp.jar-outjar build/ExpenseTracker.jar-keep public class * extends javax.microedition.midlet.MIDletPre-verifying the ApplicationThe standard Java runtime performs verification of classes prior to launching a Java application, to ensure that class files are well-formed and donot contain any malicious code.
MIDP specifies that a MIDlet shouldbe pre-verified prior to deployment, allowing the MIDP implementationon the wireless device to be reduced in size. Sun’s Wireless Toolkit issupplied with a tool to perform pre-verification; the following commandline shows this operation in the build script:%WTK_HOME%\bin\preverify -classpath%WTK_HOME%\lib\midpapi.zip;build\tmpclasses build\ExpenseTracker.jarUpdating the JAD FileThe final step in creating a deployable MIDlet is to update the JAD filewith the size of the application JAR. The JAD file contains configurationinformation that a device requires for installing, managing and running aMIDlet, such as the MIDlet’s main class and vendor information.
A smallJava program was created to embed the size into a template file and writeout the expense application’s JAD. The command in the build script isas follows:java -cp . SizeEncoder build\ExpenseTracker.jarThe JAD template file is as follows (the $size$ token is replaced withthe size of the JAR file when the template is used):MIDlet-1: Expenses,,midlet.view.ExpenseMidletMIDlet-Jar-Size: $size$MIDlet-Jar-URL: ExpenseTracker.jarMIDlet-Name: ExpensesTHE EXPENSE APPLICATION281MIDlet-Vendor: Symbian ISMIDlet-Version: 1.0MicroEdition-Configuration: CLDC-1.0MicroEdition-Profile: MIDP-2.05.2.8.2 Run ScriptThe run script has only one line of real interest: the line that launches theexpense MIDlet in Sun’s emulator.
There are a number of useful parameters available when using the emulator; for example, – Xheapsize setsthe maximum heap size and allows a MIDlet to be tested in differentmemory conditions. The emulator skin can be set using the – Xdeviceparameter; the skin name should mirror the directory name of the skin inthe Wireless Toolkit’s wtklib directory. In the following example, theSony Ericsson P900 skin would be used.
Default values are used for anyparameters not set on the command line but they can be changed usingthe Preferences application in the toolkit.%WTK_HOME%\bin\emulator -classpath build\ExpenseTracker.jar Xdescriptor:build\ExpenseTracker.jad -Xheapsize:192k Xdevice:SonyEricsson_P900Sun’s emulator makes output from the System.out and System.errstreams visible on the console when running a MIDlet, providing a goodsource of debugging information. On the device this output is not generally available. Fortunately, the behavior of the device is usually consistentwith the emulator.
Several bugs found on a device when developing theexpense application were reproducible using the emulator.To run an application on a wireless device, the MIDlet must first beinstalled. The documentation for each device must be consulted for thecorrect installation instructions.5.2.9 SummaryWe have demonstrated how an expense claim application can be writtenand have shown some of the techniques that are essential to the successof MIDlets.As the number of devices that ship with MIDP 2.0 increases, it willbecome a compelling platform. The inclusion of key features such ascustom items and enhanced networking now means that MIDP is readyfor the creation of enterprise applications in addition to the games thatare currently common.Full source code for this application can be downloaded from www.symbian.com/books.282MIDP 2.0 CASE STUDIES5.3 The Demo Racer GameIn this case study we will look at a sample application using the GameAPI.
The Demo Racer MIDlet demonstrates how the Game API can beused to build rich gaming content (see Figure 5.11).This sample application illustrates the use of LayerManager to manage a complex composite scene of layers (a TiledLayer background andSprites) and also demonstrates the use of collision detection betweenthe sprites (the car with the puddle and the car with the start–finish line).A UML class diagram of the application is shown in Figure 5.12.We will discuss the application class by class, starting with the layersthat make up the scene.Figure 5.115.3.1The Demo Racer MIDlet running on a Nokia 6600.The Background Classpackage demoracer;import javax.microedition.lcdui.game.*;import javax.microedition.lcdui.*;public class Background extends TiledLayerstatic final int WIDTH = 5;static final int HEIGHT = 5;static final int TILE_WIDTH = 60;{THE DEMO RACER GAME283static final int TILE_HEIGHT = 47;static int xMove = -2;static int yMove = 0;public Background(int columns, int rows, Image image, int tileWidth,int tileHeight) {super(columns, rows, image, tileWidth, tileHeight);// the array which is the tile map for the tiledlayerint[] map = {4,4,4,4,4,5,5,5,5,5,3,3,3,3,3,1,2,1,2,1,3,3,3,3,3};// insert the tiles into the tiled layer using the setCell() methodfor (int i = 0; i < map.length; i++) {int column = i % WIDTH;int row = (i - column) / WIDTH;setCell(column, row, map[i]);}}public void tick(){move(xMove,yMove);if (this.getX() == (this.getCellWidth() * -2)) {setPosition(0, 0);}}}javax.microedition.lcdui.game.GameCanvasRacerMidletjavax.microedition.lcdui.game.Layerjavax.microedition.lcdui.game.TiledLayerBackgroundjavax.microedition.lcdui.game.SpritePuddleCarRacerCanvasRacerLayerManagerFigure 5.12UML class diagram of the Demo Racer MIDlet.StartFinish284MIDP 2.0 CASE STUDIESFigure 5.13 The image used to build up the background layer.Figure 5.14 The background layer.The constructor takes the image shown in Figure 5.13, consisting offive tiles, each of 60 × 47 pixels.This is then used to construct the background layer (Figure 5.14),which consists of a grid of 5 × 5 cells.For each application redraw cycle, the tick() method is called tomove the position of the TiledLayer two pixels to the left (i.e.