Главная » Просмотр файлов » Programming Java 2 Micro Edition for Symbian OS 2004

Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 52

Файл №779882 Programming Java 2 Micro Edition for Symbian OS 2004 (Symbian Books) 52 страницаProgramming Java 2 Micro Edition for Symbian OS 2004 (779882) страница 522018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 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.

Характеристики

Тип файла
PDF-файл
Размер
5,73 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6309
Авторов
на СтудИзбе
313
Средний доход
с одного платного файла
Обучение Подробнее