1 / 96

Chapter 12: Java-Based Wireless Applications Development and J2ME

Chapter 12: Java-Based Wireless Applications Development and J2ME.

siusan
Download Presentation

Chapter 12: Java-Based Wireless Applications Development and J2ME

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 12: Java-Based Wireless Applications Development and J2ME Outline12.1 Introduction12.2 WelcomeServlet Overview12.3 TipTestServlet Overview 12.3.1 Internet Explorer Request 12.3.2 WAP Request 12.3.3 Pixo i-mode Request 12.3.4 J2ME Client Request12.4 Java 2 Micro Edition 12.4.1 Connected Limited Device Configuration (CLDC) 12.4.2 Mobile Information Device Profile (MIDP) 12.4.3 TipTestMIDlet Overview12.5 Installation Instructions12.6 Internet and World Wide Web Resources

  2. 12.1 Introduction • “Tip-Test” case study • Multiple choice game • Three-tier architecture • Information tier • Database (tips.sql) • Middle tier • Servlets (TipTestServlet and WelcomeServlet) • Client tier • Internet Explorer • WAP • i-mode • Java 2 Micro Edition

  3. 12.1 Introduction (cont.) Fig. 12.1 Three-tier architecture for Tip Test.

  4. 12.1 Introduction (cont.)

  5. 12.2 WelcomeServlet Overview • WelcomeServlet • Redirects client requests to static pages • Static pages are “welcome screens” for clients • Display game instructions

  6. WelcomeServlet redirects client requests to static pages that display game instructions Method doGet handles get requests User-Agent header helps to determine which client type sent get requests Send “welcome screen” to the client determined by the User-Agent header 1 // WelcomeServlet.java 2 // Delivers appropriate "Welcome" screen to client 3 package com.deitel.advjhtp1.wireless; 4 5 // Java core package 6 import java.io.*; 7 8 // Java extension packages 9 import javax.servlet.*; 10 import javax.servlet.http.*; 11 12 public class WelcomeServlet extends HttpServlet { 13 14 // respond to get request 15 protected void doGet( HttpServletRequest request, 16 HttpServletResponse response ) 17 throws ServletException, IOException 18 { 19 // determine User-Agent header 20 String userAgent = request.getHeader( "User-Agent" ); 21 22 // send welcome screen to appropriate client 23 if ( userAgent.indexOf ( 24 ClientUserAgentHeaders.IE ) != -1 ) 25 sendIEClientResponse( request, response ); 26 27 else if ( userAgent.indexOf( // WAP 28 ClientUserAgentHeaders.WAP ) != -1 ) 29 sendWAPClientResponse( request, response ); 30 31 else if ( userAgent.indexOf( // i-mode 32 ClientUserAgentHeaders.IMODE ) != -1 ) 33 sendIModeClientResponse( request, response ); 34 Fig.12.3 ClassWelcomeServletsends an introductory screen that provides game directions to a client (part 1).Line 12Line 15Line 20Lines 23-33

  7. Programmer-defined method redirect redirects the client request to a static Web page 35 else if ( userAgent.indexOf( // J2ME 36 ClientUserAgentHeaders.J2ME ) != -1 ) 37 sendJ2MEClientResponse( request, response ); 38 39 } // end method doGet 40 41 // send welcome screen to IE client 42 private void sendIEClientResponse( 43 HttpServletRequest request, HttpServletResponse response ) 44 throws IOException, ServletException 45 { 46 redirect( "text/html", "/XHTML/index.html", request, 47 response ); 48 } 49 50 // send welcome screen to Nokia WAP client 51 private void sendWAPClientResponse( 52 HttpServletRequest request, HttpServletResponse response ) 53 throws IOException, ServletException 54 { 55 redirect( "text/vnd.wap.wml", "/WAP/index.wml", request, 56 response ); 57 } 58 59 // send welcome screen to i-mode client 60 private void sendIModeClientResponse( 61 HttpServletRequest request, HttpServletResponse response ) 62 throws IOException, ServletException 63 { 64 redirect( "text/html", "/iMode/index.html", request, 65 response ); 66 } 67 Fig.12.3 ClassWelcomeServletsends an introductory screen that provides game directions to a client (part 2).Lines 42-66

  8. J2ME client receives ASCII text from servlet Read welcome screen from file into byte stream, then send byte stream to J2ME client 68 // send welcome screen to J2ME client 69 private void sendJ2MEClientResponse( 70 HttpServletRequest request, HttpServletResponse response ) 71 throws IOException 72 { 73 // send J2ME client text data 74 response.setContentType( "text/plain" ); 75 PrintWriter out = response.getWriter(); 76 77 // open file to send J2ME client 78 BufferedReader bufferedReader = 79 new BufferedReader( new FileReader( 80 getServletContext().getRealPath( 81 "j2me/index.txt" ) ) ); 82 83 String inputString = bufferedReader.readLine(); 84 85 // send each line in file to J2ME client 86 while ( inputString != null ) { 87 out.println( inputString ); 88 inputString = bufferedReader.readLine(); 89 } 90 91 out.close(); // done sending data 92 93 } // end method sendJ2MEClientResponse 94 95 // redirects client request to another page 96 private void redirect( String contentType, String redirectPage, 97 HttpServletRequest request, HttpServletResponse response ) 98 throws IOException, ServletException 99 { Fig.12.3 ClassWelcomeServletsends an introductory screen that provides game directions to a client (part 3).Line 74Lines 78-88

  9. For the other client types, use RequestDispatcher object to redirect request to static page (this approach does not work with J2ME client) 100 // set new content type 101 response.setContentType( contentType ); 102 RequestDispatcher dispatcher = 103 getServletContext().getRequestDispatcher( 104 redirectPage ); 105 106 // forward user to redirectPage 107 dispatcher.forward( request, response ); 108 } 109 } Fig.12.3 ClassWelcomeServletsends an introductory screen that provides game directions to a client (part 4).Lines 101-107

  10. List of all clients’ User-Agent headers, which act as “identifiers” for each client type 1 // ClientUserAgentHeaders.java 2 // Contains all User-Agent header for clients 3 package com.deitel.advjhtp1.wirless; 4 5 public interface ClientUserAgentHeaders { 6 7 // User-Agent header for Internet Explorer browser 8 public static final String IE = "MSIE"; 9 10 // User-Agent header for WAP browser 11 public static final String WAP = "UP"; 12 13 // User-Agent header for i-mode browser 14 public static final String IMODE = "Pixo"; 15 16 // User-Agent header for J2ME device 17 public static final String J2ME = "MIDP-1.0"; 18 } Fig.12.4 Interface ClientUserAgent-Headerscontains unique User-Agent header substrings for all clients.Lines 8-17

  11. 12.2 WelcomeServlet Overview (cont.) Fig. 12.5 WelcomeServlet output (index.html) for XHTML client.

  12. 12.2 WelcomeServlet Overview (cont.) Fig. 12.6 WelcomeServlet output (index.wml) for WAP client. (Image of UP.SDK courtesy Openwave Systems Inc. Openwave, the Openwave logo, and UP.SDK are trademarks of Openwave Systems Inc. All rights reserved.)

  13. 12.2 WelcomeServlet Overview (cont.) Fig. 12.7 WelcomeServlet output (index.html) for i-mode client. (Courtesy of Pixo, Inc.)

  14. 12.2 WelcomeServlet Overview (cont.) Fig. 12.8 WelcomeServlet output (index.txt) for J2ME client. (Courtesy of Sun Microsystems, Inc.)

  15. 12.3 TipTestServlet Overview • TipTestServlet • Generates Tip-Test questions and answers • Uses XML • Sends questions and answers to clients

  16. TipTestServlet generates and sends questions and answers to each client Method init is invoked when the client makes a request to TipTestServlet, but the servlet has not received a previous request 1 // TipTestServlet.java 2 // TipTestServlet sends Tip Test to clients. 3 package com.deitel.advjhtp1.wireless; 4 5 // Java core packages 6 import java.io.*; 7 import java.sql.*; 8 import java.util.*; 9 10 // Java extension packages 11 import javax.servlet.*; 12 import javax.servlet.http.*; 13 import javax.xml.parsers.*; 14 import javax.xml.transform.*; 15 import javax.xml.transform.dom.*; 16 import javax.xml.transform.stream.*; 17 18 // import third-party packages 19 import org.w3c.dom.*; 20 import org.xml.sax.SAXException; 21 22 public class TipTestServlet extends HttpServlet { 23 24 private Connection connection; // database connection 25 26 private DocumentBuilderFactory factory; 27 private TransformerFactory transformerFactory; 28 29 // initialize servlet 30 public void init() throws ServletException 31 { 32 // load database driver and instantiate XML factories 33 try { 34 Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 1).Line 22Line 30

  17. Use parameters in deployment descriptor to specify database; this approach enables us to change the database, without having to recompile TipTestServlet Create objects used for XML-document processing 35 // get JDBC driver from servlet container 36 String jdbcDriver = 37 getServletConfig().getInitParameter( 38 "JDBC_DRIVER" ); 39 40 Class.forName( jdbcDriver ); // load JDBC driver 41 42 // get database URL from servlet container 43 String databaseUrl = 44 getServletConfig().getInitParameter( 45 "DATABASE_URL" ); 46 47 connection = DriverManager.getConnection( databaseUrl ); 48 49 // create a Factory to build XML Documents 50 factory = DocumentBuilderFactory.newInstance(); 51 52 // create new TransformerFactory 53 transformerFactory = TransformerFactory.newInstance(); 54 55 } // end try 56 57 // handle exception database driver class does not exist 58 catch ( ClassNotFoundException classNotFoundException ) { 59 classNotFoundException.printStackTrace(); 60 } 61 62 // handle exception in making Connection 63 catch ( SQLException sqlException ) { 64 sqlException.printStackTrace(); 65 } 66 67 } // end method init 68 Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 2).Lines 36-45Lines 50-53

  18. Method doGet handles get requests (i.e., when the client requests a question) Generate the Tip-Test question from database contents, then send that question to the client Ensure that the client’s browser does not cache a previous Tip-Test question 69 // respond to get requests 70 protected void doGet( HttpServletRequest request, 71 HttpServletResponse response ) 72 throws ServletException, IOException 73 { 74 // get Statement from database, then send Tip-Test Question 75 try { 76 77 // SQL query to database 78 Statement statement = connection.createStatement(); 79 80 // get database information using SQL query 81 ResultSet resultSet = 82 statement.executeQuery( "SELECT * FROM tipInfo" ); 83 84 // parse and send ResultSet to client 85 if ( resultSet != null ) { 86 87 // ensure that client does not cache questions 88 response.setHeader( "Cache-Control", 89 "no-cache, must-revalidate" ); 90 response.setHeader( "Pragma", "no-cache" ); 91 92 sendTipTestQuestion( request, response, resultSet ); 93 } 94 95 statement.close(); // close Statement 96 } 97 98 // handle exception in exectuting Statement 99 catch ( SQLException sqlException ) { 100 sqlException.printStackTrace(); 101 } 102 103 } // end method doGet Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 3).Line 70Lines 81-92Lines 88-90

  19. Method doPost handles post requests (i.e., when the client sends its answer to the server) If Internet Explorer client sent post request, set content type to HTML and send the correct answer 104 105 // respond to post requests 106 protected void doPost( HttpServletRequest request, 107 HttpServletResponse response ) 108 throws ServletException, IOException 109 { 110 // send ResultSet to appropriate client 111 try { 112 113 // determine User-Agent header 114 String userAgent = request.getHeader( "User-Agent" ); 115 116 // if Internet Explorer is requesting client 117 if ( userAgent.indexOf( 118 ClientUserAgentHeaders.IE ) != -1 ) { 119 120 Document document = 121 createXMLTipTestAnswer( request ); 122 123 // set appropriate Content-Type for client 124 response.setContentType( "text/html" ); 125 126 // send XML content to client after XSLT 127 applyXSLT( "XHTML/XHTMLTipAnswer.xsl", document, 128 response ); 129 } 130 131 // if WAP client is requesting client 132 else if ( userAgent.indexOf( 133 ClientUserAgentHeaders.WAP ) != -1 ) { 134 135 Document document = 136 createXMLTipTestAnswer( request ); 137 Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 4).Line 106Lines 117-128

  20. If WAP client sent post request, set content type to WML and send the correct answer If i-mode client sent post request, set content type to cHTML (compact HTML) and send the correct answer If J2ME client sent post request, invoke private method sendJ2MEAnswer, which sends the correct answer 138 // set appropriate Content-Type for client 139 response.setContentType( "text/vnd.wap.wml" ); 140 141 // send XML content to client after XSLT 142 applyXSLT( "WAP/WAPTipAnswer.xsl", document, 143 response ); 144 } 145 146 // if i-mode client is requesting client 147 else if ( userAgent.indexOf( 148 ClientUserAgentHeaders.IMODE ) != -1 ) { 149 150 Document document = 151 createXMLTipTestAnswer( request ); 152 153 // set appropriate Content-Type for client 154 response.setContentType( "text/html" ); 155 156 // send XML content to client after XSLT 157 applyXSLT( "iMode/IMODETipAnswer.xsl", document, 158 response ); 159 } 160 161 // if J2ME client is requesting client 162 else if ( userAgent.indexOf( 163 ClientUserAgentHeaders.J2ME ) != -1 ) 164 sendJ2MEAnswer( request, response ); 165 166 } // end try 167 168 // handle exception if Document is null 169 catch ( NullPointerException nullPointerException ) { 170 nullPointerException.printStackTrace(); 171 } 172 Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 5).Lines 139-143Lines 147-158Lines 162-164

  21. Invoked for each get request If Internet Explorer client sent get request, generate Tip-Test question, set content type to HTML and send the question to the client 173 } // end method doPost 174 175 // send Tip-Test data to client 176 private void sendTipTestQuestion( 177 HttpServletRequest request, HttpServletResponse response, 178 ResultSet resultSet ) throws IOException 179 { 180 // send ResultSet to appropriate client 181 try { 182 183 // determine User-Agent header 184 String userAgent = request.getHeader( "User-Agent" ); 185 186 // if Internet Explorer is requesting client 187 if ( userAgent.indexOf( 188 ClientUserAgentHeaders.IE ) != -1 ) { 189 190 Document document = 191 createXMLTipTestQuestion( resultSet, request, 192 request.getContextPath() + "/XHTML/images/", 193 ".gif" ); 194 195 // set appropriate Content-Type for client 196 response.setContentType( "text/html" ); 197 applyXSLT( "XHTML/XHTMLTipQuestion.xsl", document, 198 response ); 199 } 200 201 // if WAP client is requesting client 202 else if ( userAgent.indexOf( 203 ClientUserAgentHeaders.WAP ) != -1 ) { 204 Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 6).Line 176Lines 187-198

  22. If WAP client sent get request, generate Tip-Test question, set content type to WML and send the question to the client If i-mode client sent get request, generate Tip-Test question, set content type to cHTML and send the question to the client If J2ME client sent get request, invoke private method sendJ2MEClient-Response, which sends the correct answer 205 Document document = 206 createXMLTipTestQuestion( resultSet, request, 207 request.getContextPath() + "/WAP/images/", 208 ".wbmp" ); 209 210 // set appropriate Content-Type for client 211 response.setContentType( "text/vnd.wap.wml" ); 212 applyXSLT( "WAP/WAPTipQuestion.xsl", document, 213 response ); 214 } 215 216 // if i-mode client is requesting client 217 else if ( userAgent.indexOf( 218 ClientUserAgentHeaders.IMODE ) != -1 ) { 219 220 Document document = 221 createXMLTipTestQuestion( resultSet, request, 222 request.getContextPath() + "/iMode/images/", 223 ".gif" ); 224 225 // set appropriate Content-Type for client 226 response.setContentType( "text/html" ); 227 applyXSLT( "iMode/IMODETipQuestion.xsl", document, 228 response ); 229 } 230 231 // if J2ME client is requesting client 232 else if ( userAgent.indexOf( 233 ClientUserAgentHeaders.J2ME ) != -1 ) 234 sendJ2MEClientResponse( resultSet, request, 235 response ); 236 237 } // end try 238 Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 7).Lines 205-213Lines 217-228Lines 232-235

  23. Generate Tip-Test question as XML document Store database contents in two-dimensional String array Determine correct answer (represented as index in row of database) Store correct answer in HttpSession (for future session) 239 // handle exception if Document is null 240 catch ( NullPointerException nullPointerException ) { 241 nullPointerException.printStackTrace(); 242 } 243 244 } // end method sendTipTestQuestion 245 246 // send Tip Test to Internet Explorer client 247 private Document createXMLTipTestQuestion( 248 ResultSet resultSet, HttpServletRequest request, 249 String imagePrefix, String imageSuffix ) 250 throws IOException 251 { 252 // convert ResultSet to two-dimensional String array 253 String resultTable[][] = getResultTable( resultSet ); 254 255 // create random-number generator 256 Random random = new Random( System.currentTimeMillis() ); 257 258 // create 4 random tips 259 int randomRow[] = getRandomIndices( random ); 260 261 // randomly determine correct index from 4 random indices 262 int correctAnswer = Math.abs( random.nextInt() ) % 263 randomRow.length; 264 265 int correctRow = randomRow[ correctAnswer ]; 266 267 // open new session 268 HttpSession session = request.getSession(); 269 270 // store correct answer in session 271 session.setAttribute( "correctAnswer", 272 new Integer( correctAnswer ) ); Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 8).Line 247Line 253Lines 262-265Line 271-272

  24. Store name, description and image name of correct answer in HttpSession Generate Tip-Test question as XML document Store image name in XML document 273 274 // store correct tip name 275 session.setAttribute( "correctTipName", new String( 276 resultTable[ correctRow ][ 1 ] ) ); 277 278 // store correct tip description 279 session.setAttribute( "correctTipDescription", new String( 280 resultTable[ correctRow ][ 2 ] ) ); 281 282 // determine image to send client 283 String imageName = imagePrefix + 284 resultTable[ correctRow ][ 3 ] + imageSuffix; 285 286 // create XML document based on randomly determined info 287 try { 288 289 // create document 290 DocumentBuilder builder = factory.newDocumentBuilder(); 291 Document document = builder.newDocument(); 292 293 // create question root Element 294 Element root = document.createElement( "question" ); 295 document.appendChild( root ); 296 297 // append Element image, which references image name 298 Element image = document.createElement( "image" ); 299 image.appendChild( 300 document.createTextNode( imageName ) ); 301 root.appendChild( image ); 302 303 // create choices Element to hold 4 choice Elements 304 Element choices = document.createElement( "choices" ); 305 Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 9).Lines 275-284Lines 290-291Lines 298-301

  25. Store four possible answers in XML document Mark one of the answers as “correct” Return XML document, which represents Tip-Test question 306 // append 4 choice Elements that represent user choices 307 for ( int i = 0; i < randomRow.length; i++ ) 308 { 309 // determine choice Elements from resultTable 310 Element choice = document.createElement( "choice" ); 311 choice.appendChild( document.createTextNode( 312 resultTable[ randomRow[ i ] ][ 4 ] ) ); 313 314 // set choice Element as correct or incorrect 315 Attr attribute = 316 document.createAttribute( "correct" ); 317 318 if ( i == correctAnswer ) 319 attribute.setValue( "true" ); 320 else 321 attribute.setValue( "false" ); 322 323 // append choice Element to choices Element 324 choice.setAttributeNode( attribute ); 325 choices.appendChild( choice ); 326 } 327 328 root.appendChild( choices ); 329 330 return document; 331 332 } // end try 333 334 // handle exception building Document 335 catch ( ParserConfigurationException parserException ) { 336 parserException.printStackTrace(); 337 } 338 339 return null; 340 Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 10).Lines 310-312Lines 318-321Line 330

  26. Generate Tip-Test question for J2ME client (we do not use XML, because J2ME clients cannot parse XML documents without using proprietary software) Store database contents in two-dimensional String array Determine correct answer (represented as index in row of database) Store correct answer in HttpSession (for future session) 341 } // end method createXMLTipTestQuestion 342 343 // send tip test to J2ME client 344 private void sendJ2MEClientResponse( ResultSet resultSet, 345 HttpServletRequest request, 346 HttpServletResponse response ) throws IOException 347 { 348 // convert ResultSet to two-dimensional String array 349 String resultTable[][] = getResultTable( resultSet ); 350 351 // create random-number generator 352 Random random = new Random( System.currentTimeMillis() ); 353 354 // create 4 random tips 355 int randomRow[] = getRandomIndices( random ); 356 357 // randomly determine correct index from 4 random indices 358 int correctAnswer = Math.abs( random.nextInt() ) % 359 randomRow.length; 360 361 int correctRow = randomRow[ correctAnswer ]; 362 363 // open old session 364 HttpSession session = request.getSession(); 365 366 // store correct answer in session 367 session.setAttribute( "correctAnswer", 368 new Integer( correctAnswer ) ); 369 370 // store correct tip name in session 371 session.setAttribute( "correctTipName", new String( 372 resultTable[ correctRow ][ 1 ] ) ); 373 Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 11).Line 344Line 349Lines 358-361Lines 367-372

  27. Use a stream to send image name and four possible answers to J2ME client Utility method that converts a database ResultSet to a two-dimensional String array (arrays offer faster lookup) 374 // store correct tip description in session 375 session.setAttribute( "correctTipDescription", new String( 376 resultTable[ correctRow ][ 2 ] ) ); 377 378 // send J2ME client image name 379 String imageName = "/j2me/images/" + 380 resultTable[ correctRow ][ 3 ] + ".png"; 381 382 response.setContentType( "text/plain" ); 383 PrintWriter out = response.getWriter(); 384 out.println( imageName ); 385 386 // send J2ME client test 387 for ( int i = 0; i < randomRow.length; i++ ) 388 out.println( resultTable[ randomRow[ i ] ][ 4 ] ); 389 390 } // end method sendJ2MEClientResponse 391 392 // convert ResultSet to two-dimensional String array 393 private String[][] getResultTable( ResultSet resultSet ) 394 { 395 // create table of Strings to store ResultSet 396 String resultTable[][] = new String[ 7 ][ 5 ]; 397 398 for ( int i = 0; i < 7; i++ ) { 399 400 for ( int j = 0; j < 5; j++ ) 401 resultTable[ i ][ j ] = ""; 402 } 403 404 // store all columns in table 405 try { 406 Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 12).Lines 383-388Line 393

  28. Utility method that returns an array of four randomly generated ints; each int represents an index to a row in the database 407 // for each row in resultSet 408 for ( int row = 0; resultSet.next(); row++ ) { 409 410 // for each column in resultSet 411 for ( int column = 0; column < 5; column++ ) { 412 413 // store resultSet element in resultTable 414 resultTable[ row ][ column ] += 415 resultSet.getObject( column + 1 ); 416 } 417 } 418 } 419 420 // handle exception if servlet cannot get ResultSet Object 421 catch ( SQLException sqlException ) { 422 sqlException.printStackTrace(); 423 return null; 424 } 425 426 return resultTable; 427 428 } // end method getResultTable 429 430 // get 4 randomly generated indices from resultTable 431 private int[] getRandomIndices( Random random ) 432 { 433 // create list containing row indices for resultTable 434 int list[] = newint[ 7 ]; 435 436 for ( int i = 0; i < list.length; i++ ) 437 list[ i ] = i; 438 439 int randomRow[] = newint[ 4 ]; 440 Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 13).Line 431

  29. Utility method that returns at random an index to a row in the database Apply XSLT to XML document (i.e., convert Tip-Test question or answer XML document to one that a browser can display) 441 // select 4 randomly generated indices from list 442 for ( int i = 0; i < randomRow.length; i++ ) 443 randomRow[ i ] = getRandomRow( list, random ); 444 445 return randomRow; // return these indices 446 447 } // end method getRandomIndices 448 449 // get random element from list, then nullify element 450 private int getRandomRow( int list[], Random random ) 451 { 452 // get random element from list 453 int randomRow = Math.abs( random.nextInt() ) % list.length; 454 455 while ( list[ randomRow ] < 0 ) 456 randomRow = Math.abs( random.nextInt() ) % list.length; 457 458 list[ randomRow ] = -1; // nullify element 459 460 return randomRow; 461 462 } // end method getRandomRow 463 464 // apply XSLT style sheet to XML document 465 private void applyXSLT( String xslFile, 466 Document xmlDocument, HttpServletResponse response ) 467 throws IOException 468 { 469 // apply XSLT 470 try { 471 472 // open InputStream for XSL document 473 InputStream xslStream = 474 getServletContext().getResourceAsStream( xslFile ); 475 Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 14).Line 450Line 465

  30. Transform DOM tree (XML document) to StreamResult Generate Tip-Test answer and game results as XML document 476 // create StreamSource for XSLT document 477 Source xslSource = new StreamSource( xslStream ); 478 479 // create DOMSource for source XML document 480 Source xmlSource = new DOMSource( xmlDocument ); 481 482 // get PrintWriter for writing data to client 483 PrintWriter output = response.getWriter(); 484 485 // create StreamResult for transformation result 486 Result result = new StreamResult( output ); 487 488 // create Transformer for XSL transformation 489 Transformer transformer = 490 transformerFactory.newTransformer( xslSource ); 491 492 // transform and deliver content to client 493 transformer.transform( xmlSource, result ); 494 495 } // end try 496 497 // handle exception transforming content 498 catch ( TransformerException exception ) { 499 exception.printStackTrace(); 500 } 501 502 } // end method applyXSLT 503 504 // create XML Document that stores Tip Test answer 505 private Document createXMLTipTestAnswer( 506 HttpServletRequest request ) throws IOException 507 { 508 // get session 509 HttpSession session = request.getSession(); 510 Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 15).Line 493Line 505

  31. Use HttpSession to obtain correct answer from previous session Determine whether user answered correctly Generate Tip-Test answer and results as XML document 511 // match correct answer with session answer 512 Integer integer = 513 ( Integer ) session.getAttribute( "correctAnswer" ); 514 int correctAnswer = integer.intValue(); 515 516 // give client correct tip name and description 517 String correctTipName = 518 ( String ) session.getAttribute( "correctTipName" ); 519 520 String correctTipDescription = 521 ( String ) session.getAttribute( 522 "correctTipDescription" ); 523 524 // get user selection 525 int selection = Integer.parseInt( 526 request.getParameter( "userAnswer" ) ); 527 528 String answer; 529 530 // determine if user answer is correct 531 if ( correctAnswer == selection ) 532 answer = "Correct"; 533 else 534 answer = "Incorrect"; 535 536 // get link to TipTestServlet 537 String servletName = request.getContextPath() + "/" + 538 getServletConfig().getServletName(); 539 540 // create XML document based on randomly determined info 541 try { 542 543 // create document 544 DocumentBuilder builder = factory.newDocumentBuilder(); 545 Document document = builder.newDocument(); Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 16).Lines 512-522Lines 531-534Lines 544-545

  32. Store correct answer in XML document Store link to servlet in XML document, so client can “reconnect” 546 547 // create question root Element 548 Element root = document.createElement( "answer" ); 549 document.appendChild( root ); 550 551 // append Element that informs client of correct answer 552 Element correct = document.createElement( "correct" ); 553 correct.appendChild( 554 document.createTextNode( answer ) ); 555 root.appendChild( correct ); 556 557 // append Element that describes tip name 558 Element name = 559 document.createElement( "correctTipName" ); 560 name.appendChild( 561 document.createTextNode( correctTipName ) ); 562 root.appendChild( name ); 563 564 // append Element that describes tip description 565 Element description = 566 document.createElement( "correctTipDescription" ); 567 description.appendChild( 568 document.createTextNode( correctTipDescription ) ); 569 root.appendChild( description ); 570 571 // append Element that links to TipTestServlet 572 Element servletLink = 573 document.createElement( "servletName" ); 574 servletLink.appendChild( 575 document.createTextNode( servletName ) ); 576 root.appendChild( servletLink ); 577 578 return document; 579 580 } // end try Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 17).Lines 552-569Lines 572-576

  33. Generate Tip-Test answer and results for J2ME client Use HttpSession to obtain correct answer from previous session 581 582 // handle exception building Document 583 catch ( ParserConfigurationException parserException ) { 584 parserException.printStackTrace(); 585 } 586 587 return null; 588 589 } // end method createXMLTipTestAnswer 590 591 // send answer to J2ME client 592 private void sendJ2MEAnswer( HttpServletRequest request, 593 HttpServletResponse response ) throws IOException 594 { 595 // get client test response 596 BufferedReader in = request.getReader(); 597 int selection = Integer.parseInt( in.readLine().trim() ); 598 599 // send J2ME client text data 600 response.setContentType( "text/plain" ); 601 PrintWriter out = response.getWriter(); 602 603 // inform client whether client is correct or incorrect 604 HttpSession session = request.getSession(); 605 606 // match correct answer with session answer 607 Integer integer = 608 ( Integer ) session.getAttribute( "correctAnswer" ); 609 int correctAnswer = integer.intValue(); 610 611 // send correct tip name and description 612 String correctTipName = 613 ( String ) session.getAttribute( "correctTipName" ); 614 Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 18).Line 592Lines 607-613

  34. Determine whether user answered correctly Use a stream to send correct answer to J2ME client Close database connection when servlet container destroys TipTestServlet 615 String correctTipDescription = 616 ( String ) session.getAttribute( 617 "correctTipDescription" ); 618 619 // determine whether answer is correct 620 if ( selection == correctAnswer ) 621 out.println( "Correct" ); 622 else 623 out.println( "Incorrect" ); 624 625 // give client correct tip name and description 626 out.println( correctTipName ); 627 out.println( correctTipDescription ); 628 629 } // end method sendJ2MEAnswer 630 631 // invoked when servlet is destroyed 632 public void destroy() 633 { 634 // close database connection 635 try { 636 connection.close(); 637 } 638 639 // handle if connection cannot be closed 640 catch ( SQLException sqlException ) { 641 sqlException.printStackTrace(); 642 } 643 644 } // end method destroy 645 } Fig.12.9 TipTestServlethandles game logic and sends Tip Test to clients (part 19).Line 620-623Lines 626-627Line 636

  35. 12.3.1 Internet Explorer Request • Internet Explorer receives and displays XHTML • Tip-Test question • Tip-Test answer and results

  36. Style sheet for displaying Tip-Test question on Internet Explorer client Display tip image 1 <?xml version="1.0"?> 2 3 <!-- XHTMLTipQuestion.xsl --> 4 <!-- XHTML stylesheet --> 5 6 <xsl:stylesheet version ="1.0" 7 xmlns:xsl ="http://www.w3.org/1999/XSL/Transform"> 8 9 <xsl:output method ="xml"omit-xml-declaration ="no" 10 doctype-system ="DTD/xhtml1-strict.dtd" 11 doctype-public ="-//W3C//DTD XHTML 1.0 Strict//EN"/> 12 13 <!-- specify the root of the XML document --> 14 <!-- that references this stylesheet --> 15 <xsl:template match ="question"> 16 <html xmlns="http://www.w3.org/1999/xhtml"> 17 18 <head> 19 <title>Tip Test</title> 20 </head> 21 22 <body> 23 24 <p> 25 26 <!-- display image --> 27 <img name ="image"alt ="Tip Image" 28 src ="{image}"> 29 </img> 30 31 </p> 32 33 <p> 34 What is the name of the icon shown? 35 </p> Fig. 12.10 XHTMLTipQuestion.xsltransforms XML Tip-Test question to XHTML document (part 1).Line 3Lines 27-29

  37. Display four possible answers 36 37 <p> 38 39 <!-- create a form with four checkboxes --> 40 <form method ="post" 41 action ="/advjhtp1/tiptest"> 42 43 <!-- build a table for the options --> 44 <table> 45 <tr> 46 <td> 47 <input type = "radio" 48 name = "userAnswer"value ="0"> 49 </input> 50 <xsl:value-of select = 51 "choices/choice[1]"/> 52 </td> 53 54 <td> 55 <input type ="radio" 56 name = "userAnswer"value ="1"> 57 </input> 58 <xsl:value-of select = 59 "choices/choice[2]"/> 60 </td> 61 </tr> 62 63 <tr> 64 <td> 65 <input type ="radio" 66 name ="userAnswer"value = "2"> 67 </input> 68 <xsl:value-of select = 69 "choices/choice[3]"/> 70 </td> Fig. 12.10 XHTMLTipQuestion.xsltransforms XML Tip-Test question to XHTML document (part 2).Lines 47-69

  38. Display four possible answers (cont.) Button for submitting answer 71 72 <td> 73 <input type ="radio" 74 name = "userAnswer"value = "3"> 75 </input> 76 <xsl:value-of select = 77 "choices/choice[4]"/> 78 </td> 79 </tr> 80 </table> 81 82 <input type ="submit"value ="Submit"/> 83 </form> 84 </p> 85 86 </body> 87 </html> 88 </xsl:template> 89 </xsl:stylesheet> Fig. 12.10 XHTMLTipQuestion.xsltransforms XML Tip-Test question to XHTML document (part 3).Lines 73-75Line 82

  39. 12.3.1 Internet Explorer Request (cont.) Fig. 12.11 Internet Explorer Tip-Test question output screen.

  40. Style sheet for displaying correct Tip-Test answer and game results on Internet Explorer client Inform user whether user guessed correct answer 1 <?xml version="1.0"?> 2 3 <!-- XHTMLTipAnswer.xsl --> 4 <!-- XHTML stylesheet --> 5 6 <xsl:stylesheet version = "1.0" 7 xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"> 8 9 <xsl:output method = "xml" omit-xml-declaration = "no" 10 doctype-system = "DTD/xhtml1-strict.dtd" 11 doctype-public = "-//W3C//DTD XHTML 1.0 Strict//EN"/> 12 13 <!-- specify the root of the XML document --> 14 <!-- that references this stylesheet --> 15 <xsl:template match = "answer"> 16 <html xmlns="http://www.w3.org/1999/xhtml"> 17 18 <head> 19 <title>Tip Test Answer</title> 20 </head> 21 22 <body> 23 24 <p> 25 <h1> 26 <xsl:value-of select = "correct"/> 27 </h1> 28 </p> 29 30 <p> 31 <h2>Tip Name</h2> 32 </p> 33 Fig. 12.12 XHTMLTipAnswer. xsltransforms XML Tip-Test answer to XHTML document (part 1).Line 3Line 26

  41. Display correct tip name and description Provide link to TipTestServlet, so user can play again 34 <p> 35 <h3> 36 <xsl:value-of select = "correctTipName"/> 37 </h3> 38 </p> 39 40 <p> 41 <h2>Tip Description</h2> 42 </p> 43 44 <p> 45 <h3> 46 <xsl:value-of 47 select = "correctTipDescription"/> 48 </h3> 49 </p> 50 51 <p> 52 <h2> 53 <a href="{servletName}">Next Tip</a> 54 </h2> 55 </p> 56 57 </body> 58 </html> 59 </xsl:template> 60 </xsl:stylesheet> Fig. 12.12 XHTMLTipAnswer. xsltransforms XML Tip-Test answer to XHTML document (part 2).Lines 35-48Line 53

  42. 12.3.1 Internet Explorer Request (cont.) Fig. 12.13 Internet Explorer Tip-Test answer output screen.

  43. 12.3.2 WAP Request • WAP client receives and displays WML • Tip-Test question • Tip-Test answer and results

  44. Style sheet for displaying Tip-Test question on WAP client Each displayable screen on WAP client is called a “card” Display tip image Button for submitting answer 1 <?xml version="1.0"?> 2 3 <!-- WAPTipQuestion.xsl --> 4 <!-- WAP stylesheet --> 5 6 <xsl:stylesheet 7 xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 8 version="1.0"> 9 10 <xsl:output method = "xml" omit-xml-declaration = "no" 11 doctype-system = "http://www.wapforum.org/DTD/wml_1.1.xml" 12 doctype-public = "-//WAPFORUM//DTD WML 1.1//EN"/> 13 14 <!-- specify the root of the XML document --> 15 <!-- that references this stylesheet --> 16 <xsl:template match = "question"> 17 18 <wml> 19 <card id = "card1" title = "Tip Test"> 20 21 <do type = "accept" label = "OK"> 22 <go href = "#card2"/> 23 </do> 24 25 <p> 26 <img src = "{image}" height = "55" width = "55" 27 alt = "Tip Image"/> 28 </p> 29 30 </card> 31 32 <card id = "card2" title = "Tip Test"> 33 <do type = "accept" label = "Submit"> 34 <go method = "post" href = "/advjhtp1/tiptest"> Fig. 12.14 WAPTipQuestion. xsltransforms XML Tip-Test question to WML document (part 1).Line 3Line 19Lines 26-27Line 33

  45. Display four possible answers 35 <postfield name = "userAnswer" 36 value = "$(question)"/> 37 </go> 38 </do> 39 40 <p> 41 The tip shown on the previous screen is called: 42 </p> 43 44 <p> 45 <select name = "question" 46 iname = "iquestion" ivalue = "1"> 47 48 <option value = "0"><xsl:value-of 49 select = "choices/choice[1]"/></option> 50 51 <option value = "1"><xsl:value-of 52 select = "choices/choice[2]"/></option> 53 54 <option value = "2"><xsl:value-of 55 select = "choices/choice[3]"/></option> 56 57 <option value = "3"><xsl:value-of 58 select = "choices/choice[4]"/></option> 59 </select> 60 </p> 61 </card> 62 </wml> 63 </xsl:template> 64 </xsl:stylesheet> Fig. 12.14 WAPTipQuestion. xsltransforms XML Tip-Test question to WML document (part 2).Line 48-58

  46. 12.3.2 WAP Request (cont.) Fig. 12.15 Openwave UP simulator Tip-Test question screen. (Image of UP.SDK courtesy Openwave Systems Inc. Openwave, the Openwave logo, and UP.SDK are trademarks of Openwave Systems Inc. All rights reserved.)

  47. Style sheet for displaying correct Tip-Test answer and game results on WAP client Provide link to TipTestServlet, so user can play again Inform user whether user guessed correct answer 1 <?xml version="1.0"?> 2 3 <!-- WAPTipAnswer.xsl --> 4 <!-- WAP stylesheet --> 5 6 <xsl:stylesheet 7 xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 8 version="1.0"> 9 10 <xsl:output method = "xml" omit-xml-declaration = "no" 11 doctype-system = "http://www.wapforum.org/DTD/wml_1.1.xml" 12 doctype-public = "-//WAPFORUM//DTD WML 1.1//EN"/> 13 14 <!-- specify the root of the XML document --> 15 <!-- that references this stylesheet --> 16 <xsl:template match = "answer"> 17 18 <wml> 19 20 <card id = "card1" title = "Tip Test Answer"> 21 22 <do type = "accept" label = "OK"> 23 <go method = "get" 24 href = "/advjhtp1/tiptest"> 25 </go> 26 </do> 27 28 <p> 29 <xsl:value-of select = "correct"/> 30 </p> 31 32 <p> 33 Tip Name 34 </p> 35 Fig. 12.16 WAPTipAnswer.xsltransforms XML Tip-Test answer to WML document (part 1).Line 3Lines 23-25Line 29

  48. Display correct tip name and description 36 <p> 37 <xsl:value-of select = "correctTipName"/> 38 </p> 39 40 <p> 41 Tip Description 42 </p> 43 44 <p> 45 <xsl:value-of select = "correctTipDescription"/> 46 </p> 47 48 </card> 49 50 </wml> 51 </xsl:template> 52 </xsl:stylesheet> Fig. 12.16 WAPTipAnswer.xsltransforms XML Tip-Test answer to WML document (part 2).Lines 37-45

  49. 12.3.2 WAP Request (cont.) Fig. 12.17 Openwave UP simulator Tip-Test answer screen. (Image of UP.SDK courtesy Openwave Systems Inc. Openwave, the Openwave logo, and UP.SDK are trademarks of OpenwaveSystems Inc. All rights reserved.)

  50. 12.3.3 Pixo i-mode Request • i-mode client receives and displays cHTML • Tip-Test question • Tip-Test answer and results

More Related