WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and...

438
ibm.com/redbooks IBM Workplace Client Technology Micro Edition Version 5.7.1: Application Development and Case Study Juan R. Rodriguez Jeffrey Martin Sidath D. Perera David Reich Gianfranco Rutigliano Guillermo Villavicencio Joel Wickham Develop applications using WebSphere Studio Device Developer Extend enterprise applications to mobile devices Learn about SMF as an implementation of OSGi

Transcript of WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and...

Page 1: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

ibm.com/redbooks

IBM Workplace Client Technology Micro Edition Version 5.7.1: Application Developmentand Case Study

Juan R. RodriguezJeffrey Martin

Sidath D. PereraDavid Reich

Gianfranco RutiglianoGuillermo Villavicencio

Joel Wickham

Develop applications using WebSphere Studio Device Developer

Extend enterprise applications to mobile devices

Learn about SMF as an implementation of OSGi

Front cover

Page 2: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.
Page 3: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

IBM Workplace Client Technology Micro Edition Version 5.7.1: Application Development and Case Study

June 2005

International Technical Support Organization

SG24-6496-00

Page 4: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

© Copyright International Business Machines Corporation 2005. All rights reserved.Note to U.S. Government Users Restricted Rights -- Use, duplication or disclosure restricted by GSA ADPSchedule Contract with IBM Corp.

First Edition (June 2005)

This edition applies to Version 5, Release 7, Modification 1 of IBM Workplace Client Technology Micro Edition.

Note: Before using this information and the product it supports, read the information in “Notices” on page ix.

Page 5: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Contents

Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ixTrademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . x

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiThe team that wrote this redbook. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiiBecome a published author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiiiComments welcome. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiv

Chapter 1. Introduction to Workplace Client Technologies. . . . . . . . . . . . . 11.1 Workplace Client Technology Micro Edition. . . . . . . . . . . . . . . . . . . . . . 21.2 Terminology. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.2.1 Workplace Client Technology Micro Edition (WCTME). . . . . . . . . . . . 41.2.2 WebSphere Everyplace Micro Environment . . . . . . . . . . . . . . . . . . . . 41.2.3 WebSphere Everyplace Custom Environment . . . . . . . . . . . . . . . . . . 41.2.4 J9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.2.5 Eclipse. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.2.6 Rich Client Platform (RCP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.2.7 Standard Widget Toolkit (SWT) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.2.8 WebSphere Studio Device Developer. . . . . . . . . . . . . . . . . . . . . . . . . 61.2.9 Java 2 Micro Edition (J2ME) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.2.10 Service Management Framework (SMF) . . . . . . . . . . . . . . . . . . . . . 7

1.3 Technology overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71.4 How the parts fit together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91.5 WCTME or WCTRE? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.6 Tooling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

Chapter 2. . . . . . . . . . . . . . . . . . . . . . . The Case Study: ITSO Car Rentals172.1 Business overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

2.1.1 Data requirements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182.1.2 Information infrastructure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192.1.3 Design decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

2.2 Running the sample application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252.2.1 The sample application panels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252.2.2 The sample application flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282.2.3 Files created by the application on the device . . . . . . . . . . . . . . . . . 302.2.4 Application properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312.2.5 Application services and technologies . . . . . . . . . . . . . . . . . . . . . . . 33

2.3 Running the sample application with live servers . . . . . . . . . . . . . . . . . . . 352.3.1 Using the demonstration application with multiple devices . . . . . . . . 38

© Copyright IBM Corp. 2005. All rights reserved. iii

Page 6: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

2.4 Building the sample application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

Chapter 3. Service Management Framework Runtime. . . . . . . . . . . . . . . . 413.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

3.1.1 What is OSGi and the OSGi service platform? . . . . . . . . . . . . . . . . . 423.1.2 What is SMF? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433.1.3 Core Bundles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463.1.4 SMF Specific Bundles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463.1.5 Bundles provided by Extension Services . . . . . . . . . . . . . . . . . . . . . 463.1.6 Bundles created in this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

3.2 Documentation and Web Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483.3 Example exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

3.3.1 Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503.3.2 Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503.3.3 Creating a tester bundle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633.3.4 Customer Bundle creation review . . . . . . . . . . . . . . . . . . . . . . . . . . . 673.3.5 Testing the Customer Bundle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 673.3.6 Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

3.4 Starting the SMF Bundle Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703.5 Starting the SMF Runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733.6 Stopping the SMF Bundle Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753.7 Stopping the SMF Runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 763.8 Submitting bundles to the SMF bundle server . . . . . . . . . . . . . . . . . . . . . 773.9 Installing bundles into the SMF Runtime. . . . . . . . . . . . . . . . . . . . . . . . . . 793.10 Removing bundles from the SMF bundle server . . . . . . . . . . . . . . . . . . . 803.11 Uninstalling bundles from the SMF Runtime . . . . . . . . . . . . . . . . . . . . . . 81

Chapter 4. Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 834.1 Database support overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

4.1.1 DB2 Everyplace Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 854.1.2 DB2 Everyplace ISync Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 854.1.3 IBM Cloudscape Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 854.1.4 IBM Cloudscape ISync Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

4.2 DB2 Everyplace versus Cloudscape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 864.3 Documentation and Web Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

4.3.1 DB2e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 864.3.2 Cloudscape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

4.4 Example database exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 874.4.1 Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 884.4.2 Configuring a development system for DB2e and DB2e Sync . . . . . 894.4.3 Extending the Tester bundle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1054.4.4 Database bundle review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1064.4.5 Testing the database bundle. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

iv WCTME: Application Development and Case Study

Page 7: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

4.4.6 Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108

Chapter 5. Messaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1095.1 Overview of MQe. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

5.1.1 Documentation and Web Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1105.1.2 Definition of terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1115.1.3 Message flow in MQe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1125.1.4 Building MQe Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1155.1.5 Processing MQe messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

5.2 Using MQe in the example application . . . . . . . . . . . . . . . . . . . . . . . . . . 1165.3 Example messaging exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

5.3.1 Messaging exercise description . . . . . . . . . . . . . . . . . . . . . . . . . . . 1175.3.2 Perform the exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1175.3.3 Creating the MQeAdmin Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1275.3.4 Extending the Tester Bundle. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1415.3.5 Example messaging review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1435.3.6 Testing the MQe bundle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

5.4 Creating the MQe Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1445.4.1 Running the MQe Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1525.4.2 Message troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153

Chapter 6. Web Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1556.1 Service-Oriented Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1566.2 Web services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1576.3 Web Services in WCTME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1606.4 Web Services sample scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161

6.4.1 Web Services sample description . . . . . . . . . . . . . . . . . . . . . . . . . . 1616.4.2 Procedure for creating a Web Service . . . . . . . . . . . . . . . . . . . . . . 162

6.5 Creating the FlightInfoWebServiceClient Bundle . . . . . . . . . . . . . . . . . . 1736.5.1 Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1746.5.2 Extending the Web Services Tester bundle . . . . . . . . . . . . . . . . . . 1806.5.3 Messaging Web Service review . . . . . . . . . . . . . . . . . . . . . . . . . . . 1816.5.4 Testing the Web Service and Web Service client bundles . . . . . . . 1816.5.5 Web Services troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182

Chapter 7. HTTP services, servlets and Java server pages . . . . . . . . . . 1837.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184

7.1.1 Servlets and JSPs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1847.1.2 Web applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1847.1.3 Web applications in WCTME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184

7.2 Using HTTP Services in WCTME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1857.2.1 Building a Web application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1857.2.2 Converting a Web application to an SMF bundle . . . . . . . . . . . . . . 1867.2.3 Using SMF services from a Web application . . . . . . . . . . . . . . . . . 186

Contents v

Page 8: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

7.3 Sample Web application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1877.3.1 Web application description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1877.3.2 Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187

7.4 Converting from a J2EE Web application to a bundle. . . . . . . . . . . . . . . 2007.4.1 Completing the sample application . . . . . . . . . . . . . . . . . . . . . . . . . 2057.4.2 Extending the Tester bundle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2257.4.3 Web application review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225

7.5 Running the completed Web application. . . . . . . . . . . . . . . . . . . . . . . . . 2267.6 Troubleshooting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226

Chapter 8. WCTME application configuration for a target platform . . . . 2298.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230

8.1.1 Configuring the Java Class Library (JCL) . . . . . . . . . . . . . . . . . . . . 2308.1.2 Configuring the bundle application using the SMF . . . . . . . . . . . . . 2308.1.3 Adding system application services . . . . . . . . . . . . . . . . . . . . . . . . 230

8.2 Customizing the Java Class Library (JCL) and application services. . . . 2318.3 Including system services in your project . . . . . . . . . . . . . . . . . . . . . . . . 231

8.3.1 Using the properties tab to change platform profilesand application services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236

8.4 Using the Manifest file to configure the application . . . . . . . . . . . . . . . . . 2368.5 Extension Services and J2ME profiles differences . . . . . . . . . . . . . . . . . 2378.6 Platform builder troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238

Chapter 9. Deploying a WCTME Application . . . . . . . . . . . . . . . . . . . . . . 2399.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2409.2 Exporting your application from WebSphere Studio . . . . . . . . . . . . . . . . 241

9.2.1 Exporting application bundles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2419.2.2 Exporting Web application bundles. . . . . . . . . . . . . . . . . . . . . . . . . 2449.2.3 Exporting bundles from the SMF Bundle Server. . . . . . . . . . . . . . . 247

9.3 Creating a platform builder project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2489.3.1 Rebuilding the platform after changes . . . . . . . . . . . . . . . . . . . . . . 2619.3.2 Adding custom files to the platform build . . . . . . . . . . . . . . . . . . . . 264

9.4 Running the platform build . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2669.5 Deploying the sample application to a Pocket PC. . . . . . . . . . . . . . . . . . 267

Chapter 10. DB2e synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27110.1 IBM DB2 Everyplace overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27210.2 DB2 Everyplace in WCTME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272

10.2.1 DB2 Everyplace Sync Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27310.2.2 DB2 Everyplace SDK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273

10.3 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27310.4 Types of subscription . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275

10.4.1 JDBC subscription. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27510.4.2 DataPropagator subscription. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276

vi WCTME: Application Development and Case Study

Page 9: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

10.4.3 Upload subscription. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27710.5 Filtering data from data sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27810.6 Synchronization with remote DB2 databases . . . . . . . . . . . . . . . . . . . . 27910.7 Debug and tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279

10.7.1 Application server logs files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27910.7.2 Enable tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27910.7.3 Trace files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28010.7.4 DB2 Everyplace control database. . . . . . . . . . . . . . . . . . . . . . . . . 280

10.8 DB2 Everyplace sample scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28010.8.1 First steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28110.8.2 Server configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28310.8.3 Programming database synchronization using WCTME. . . . . . . . 30410.8.4 Synchronization review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315

10.9 Hints and tips. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315

Chapter 11. Device management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31711.1 Device management overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31811.2 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319

11.2.1 Device Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31911.2.2 OSGi Agent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32011.2.3 Device Manager database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32011.2.4 Device Management portlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32111.2.5 Device Manager Console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321

11.3 OGSGi device sample scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32111.3.1 Software distribution for OSGi bundles . . . . . . . . . . . . . . . . . . . . . 32211.3.2 Software removal for OSGi bundles . . . . . . . . . . . . . . . . . . . . . . . 33111.3.3 Connecting the Device Manager server and

WebSphere Studio Device Developer . . . . . . . . . . . . . . . . . . . . . . 33411.4 Device Manager sample scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335

11.4.1 Interim Fix 1 and IFix instructions . . . . . . . . . . . . . . . . . . . . . . . . . 33511.4.2 Device Manager scenario description . . . . . . . . . . . . . . . . . . . . . . 33611.4.3 Device Manager bundle procedure . . . . . . . . . . . . . . . . . . . . . . . . 33611.4.4 Update the sample application to use the new service . . . . . . . . . 34211.4.5 Device manager bundle review. . . . . . . . . . . . . . . . . . . . . . . . . . . 34311.4.6 Running the sample application with device

management bundle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34411.4.7 Device Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344

11.5 Troubleshooting with Device Manager . . . . . . . . . . . . . . . . . . . . . . . . . 345

Appendix A. Installing WCTME V5.7.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . 347WCTME Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348

Installation prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348Preinstallation procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349

Contents vii

Page 10: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Machine installations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349WebSphere Studio Site Developer installation . . . . . . . . . . . . . . . . . . . . . 349WebSphere Studio Device Developer installation. . . . . . . . . . . . . . . . . . . 352WebSphere Studio Device Developer plug-in installation. . . . . . . . . . . . . 354Verify installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358Reviewing the installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359

Appendix B. Using MIDlet applications to access Web Services . . . . . . 361Create the Web Services MIDlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362Edit the Web Services MIDlet. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365Launch and test the Web Services MIDlet . . . . . . . . . . . . . . . . . . . . . . . . . . . 368

Appendix C. Sample server-side Web Service . . . . . . . . . . . . . . . . . . . . . 375Create a Web project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376

Reviewing the imported Java class file . . . . . . . . . . . . . . . . . . . . . . . . . . . 380Create a Web service. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381Deploy a Web service in WebSphere Application Server . . . . . . . . . . . . . . . 391

Appendix D. Additional materials and how to obtain them . . . . . . . . . . . 403Locating the Web material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404Using the Web material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404

System requirements for downloading the Web material . . . . . . . . . . . . . 404How to use the Web material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404

Web material overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404Procedure for using the Web material. . . . . . . . . . . . . . . . . . . . . . . . . . . . 406

Related publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411IBM Redbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411Other publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411Online resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411How to get IBM Redbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412Help from IBM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413

viii WCTME: Application Development and Case Study

Page 11: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Notices

This information was developed for products and services offered in the U.S.A.

IBM may not offer the products, services, or features discussed in this document in other countries. Consult your local IBM representative for information on the products and services currently available in your area. Any reference to an IBM product, program, or service is not intended to state or imply that only that IBM product, program, or service may be used. Any functionally equivalent product, program, or service that does not infringe any IBM intellectual property right may be used instead. However, it is the user's responsibility to evaluate and verify the operation of any non-IBM product, program, or service.

IBM may have patents or pending patent applications covering subject matter described in this document. The furnishing of this document does not give you any license to these patents. You can send license inquiries, in writing, to: IBM Director of Licensing, IBM Corporation, North Castle Drive Armonk, NY 10504-1785 U.S.A.

The following paragraph does not apply to the United Kingdom or any other country where such provisions are inconsistent with local law: INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES THIS PUBLICATION "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Some states do not allow disclaimer of express or implied warranties in certain transactions, therefore, this statement may not apply to you.

This information could include technical inaccuracies or typographical errors. Changes are periodically made to the information herein; these changes will be incorporated in new editions of the publication. IBM may make improvements and/or changes in the product(s) and/or the program(s) described in this publication at any time without notice.

Any references in this information to non-IBM Web sites are provided for convenience only and do not in any manner serve as an endorsement of those Web sites. The materials at those Web sites are not part of the materials for this IBM product and use of those Web sites is at your own risk.

IBM may use or distribute any of the information you supply in any way it believes appropriate without incurring any obligation to you.

Information concerning non-IBM products was obtained from the suppliers of those products, their published announcements or other publicly available sources. IBM has not tested those products and cannot confirm the accuracy of performance, compatibility or any other claims related to non-IBM products. Questions on the capabilities of non-IBM products should be addressed to the suppliers of those products.

This information contains examples of data and reports used in daily business operations. To illustrate them as completely as possible, the examples include the names of individuals, companies, brands, and products. All of these names are fictitious and any similarity to the names and addresses used by an actual business enterprise is entirely coincidental.

COPYRIGHT LICENSE: This information contains sample application programs in source language, which illustrates programming techniques on various operating platforms. You may copy, modify, and distribute these sample programs in any form without payment to IBM, for the purposes of developing, using, marketing or distributing application programs conforming to the application programming interface for the operating platform for which the sample programs are written. These examples have not been thoroughly tested under all conditions. IBM, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. You may copy, modify, and distribute these sample programs in any form without payment to IBM for the purposes of developing, using, marketing, or distributing application programs conforming to IBM's application programming interfaces.

© Copyright IBM Corp. 2005. All rights reserved. ix

Page 12: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

TrademarksThe following terms are trademarks of the International Business Machines Corporation in the United States, other countries, or both:

Cloudscape™DataPropagator™DB2 Universal Database™DB2®Eserver®Eserver®ibm.com®ETE™Everyplace®

IBM®ibm.com®MVS™Notes®Perform™Rational®Redbooks (logo)™Redbooks (logo) ™

Redbooks™SOM®Tivoli®TME®WebSphere®Workplace Client Technology™Workplace™

The following terms are trademarks of other companies:

Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.

Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both.

Intel, Intel Inside (logos), MMX, and Pentium are trademarks of Intel Corporation in the United States, other countries, or both.

Linux is a trademark of Linus Torvalds in the United States, other countries, or both.

Other company, product, and service names may be trademarks or service marks of others.

x WCTME: Application Development and Case Study

Page 13: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Preface

This IBM® Redbook covers the end-to-end story for pervasive solutions and provides the implementation guidelines necessary for architects and application developers. Workplace™ Client Technology™ Micro Edition (WCTME) is an integrated platform for the extension of existing enterprise applications to server-managed client devices such as desktop and mobile computers, personal digital assistants (PDAs), and other mobile and pervasive devices. The integrated package combines tools such as WebSphere® Studio Device Developer and Micro Environment Toolkit for WebSphere Studio; run-time software such as WebSphere Everyplace® Micro Environment, Service Management Framework, and WebSphere Everyplace Custom Environment; and middleware such as DB2e, MQe and Web Services for building, testing, and deploying server-managed client software to pervasive devices.

This redbook provides an implementation of pervasive client functions and their interaction with corresponding servers. It also includes information about the use of tools for development and deployment of an end-to-end pervasive solution, including integration considerations and application scenarios between enterprise pervasive clients, pervasive middleware and corresponding server based applications. You will find information about using tools for implementation of functions that are essential in a pervasive solution for the whole architecture such as fundamentals of programming models, capabilities provided by WCTME tooling and runtime, tooling structure and flow, wizards and code generation, platform configuration and deployment.

You will also find information about the tools, runtimes, and APIs that are needed to build, test, deploy, and maintain server-managed client software as well as client-side, services-oriented framework that can be used by network and system administrators to deploy, maintain, update, and even remove software from end-user machines, without the need for end-user intervention. This will allow you to extend many enterprise business processes to server-managed PDAs, mobile computers and desktop systems.

This book includes a business scenario chosen as a case study. You will find the elements of the business processes being put into place, and understand what technologies were chosen to solve the different parts of the implementation.

A basic knowledge of Java™ programming, Java technologies and Java open standards such as OSGi is assumed.

© Copyright IBM Corp. 2005. All rights reserved. xi

Page 14: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

The team that wrote this redbookThis redbook was produced by a team of specialists from around the world working at the International Technical Support Organization, Raleigh Center.

Juan Rodriguez is a Consulting IT professional at the IBM ITSO Center, Raleigh. He has an M.S. degree in Computer Science from Iowa State University. He writes extensively and teaches IBM classes worldwide on Web technologies, and information security. Before joining the IBM ITSO, he worked at the IBM laboratory in Research Triangle Park, North Carolina as a designer and developer of networking products.

Jeffrey Martin is an Advisory Software Engineer with IBM in Austin, Texas. He graduated from the University of Florida with a B.S. in Computer and Informational Sciences and joined IBM in 1988. He is a certified Java Programmer and has more than 10 years’ experience creating custom, mobile and wireless software solutions.

Sidath D. Perera is an IT Architect for the IBM WebSphere Software Group. Along with evangelizing WebSphere Technology to IBM's Software partners, he helps them architect their applications on WebSphere middleware. He has also spent more than 10 years using various platforms to develop application software. He has a B.S. degree in Computer Science.

David Reich is a Senior Software Engineer and Tools Architect in Pervasive Computing. His current responsibilities include design and architecture for WebSphere Studio Device Developer, as well as the cross segment team for overall Pervasive Computing tools. He holds a number of patents in the United States and abroad and has been a prolific writer and speaker. Mr. Reich has B.S. and M.S. degrees in Computer Science from the State University of New York at Albany.

Gianfranco Rutigliano holds a degree in Systems Engineering from the University of Lima, Peru and has been a member of IBM Global Services for four years. He has strong experience designing and implementing pervasive and Java-based Web solutions. He is currently a Software Architect for Avatar e-Business Solutions, an IBM Business Partner and has participated in several ITSO residencies for pervasive computing and WebSphere technologies.

xii WCTME: Application Development and Case Study

Page 15: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Guillermo Villavicencio holds a degree in Informatics Engineering from the Pontifical Catholic University of Peru and works as a Software Architect for Avatar e-Business Solutions, an IBM Business Partner. He has been the architect for several e-business projects including wireless and Portal solutions. His current area of expertise is centered around Web technologies and pervasive computing.

Joel Wickham has an M.S. degree in Computer Science from Union College in Schenectady, New York. He previously worked for the IBM Poughkeepsie Programming Lab as a Software Engineer, and as an instructor teaching MVS™, PL/X, C and Smalltalk. He is currently an independent contractor teaching Java, WebSphere Client Technology Micro Edition and WebSphere Studio Device Developer workshops for the IBM Dallas Technical Support Center. He is a Sun Certified Java Programmer, Sun Certified Java Developer and a Certified Technical Instructor.

Special thanks to the following people who wrote the appendixes in this redbook:

Amit AgharaIBM Boca Raton, Florida, USA

Lucas ChaneyIBM Innovation Center, IBM Developer Relations, Austin, Texas, USA

Thanks to the following people for their contributions to this project:

Scott Bennett, Michael Burkhart, Jennifer Fogell, Brian Lillie, Pamela Tobias,IBM Austin, Texas, USA

Michael Rheinheimer, Daniel M SchumacherIBM Austin, Texas, USA

Denice SharpeIBM RTP, North Carolina USA

Charlie ReidIBM United Kingdom, Warwick, UK

Become a published authorJoin us for a two- to six-week residency program! Help write an IBM Redbook dealing with specific products or solutions, while getting hands-on experience

Preface xiii

Page 16: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

with leading-edge technologies. You'll team with IBM technical professionals, Business Partners and/or customers.

Your efforts will help increase product acceptance and customer satisfaction. As a bonus, you'll develop a network of contacts in IBM development labs, and increase your productivity and marketability.

Find out more about the residency program, browse the residency index, and apply online at:

ibm.com/redbooks/residencies.html

Comments welcomeYour comments are important to us!

We want our Redbooks™ to be as helpful as possible. Send us your comments about this or other Redbooks in one of the following ways:

� Use the online Contact us review redbook form found at:

ibm.com/redbooks

� Send your comments in an email to:

[email protected]

� Mail your comments to:

IBM Corporation, International Technical Support OrganizationDept. HZ8 Building 662P.O. Box 12195Research Triangle Park, NC 27709-2195

xiv WCTME: Application Development and Case Study

Page 17: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Chapter 1. Introduction to Workplace Client Technologies

This chapter introduces you to the Workplace Client Technologies fundamental topics, terminology, strategy and architecture. It is assumed that you have a working knowledge of Java, J2ME, various enterprise services such as Web Services, messaging and database, and also a base knowledge of the Eclipse tooling framework and WebSphere Studio Device Developer, IBM’s development toolset for J2ME/WCTME applications.

1

© Copyright IBM Corp. 2005. All rights reserved. 1

Page 18: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

1.1 Workplace Client Technology Micro EditionWorkplace Client Technology Micro Edition (WCTME) is an integrated platform for the extension of existing enterprise applications to server-managed client devices such as desktop computers, mobile systems, personal digital assistants, (PDAs), and other mobile and pervasive devices. The integrated package combines the tools WebSphere® Studio Device Developer and Micro Environment Toolkit for WebSphere Studio, run times (WebSphere Everyplace Micro Environment, Service Management Framework (SMF), and WebSphere Everyplace Custom Environment), and middleware (DB2e, MQe, Web Services) for building, testing, and deploying server-managed client software to pervasive devices.

Over the years, computing models have moved from the server-based or mainframe model to the original networked model (PC-LAN) with shared files. This stage devolved back to a server-centric or distributed application, PC-based model to reduce cost-of-ownership. Now, we are back again to a desktop, or device-centric model. It seems to cycle every few years. The only thing consistent in all of this is change is that the industry has not been able to find a good medium to maintain the autonomy and performance of localized applications with the cost benefits that come with server-managed environments.

IBM® Workplace Client Technology (WCT) is the best of both worlds.

In essence, WCTME is the foundation platform for the WCT family of offerings from IBM and provides a robust platform that supports devices from cell phones, PDAs and other devices to tablet, mobile and even desktop systems. Regardless of whether the computer is always, occasionally, or seldom connected, the WCTME model enables you to extend your applications and programming models using industry standards and without rewriting to all of these devices.

The WCTME platform is built as a combination of a Rich Client Platform (RCP) based on the Eclipse model (originally devised for tools, and moved to be a more generic application platform) as well as a browser-based model. Eclipse is an award-winning, open source platform for the construction of powerful software development tools and rich desktop applications.

The underlying premises of the WCTME platform are:

1. A device is not just a gizmo like a PDA or cell phone. A device is anything from lower-powered devices up to a tablet, mobile or desktop PC. Whenever you see the term device in this book, it can mean a PDA, cell phone, desktop, or mobile computer in any state of connectivity.

2. The application model does not change from what is currently used but, rather, it is modified to make the assumption that the device is not necessarily

2 WCTME: Application Development and Case Study

Page 19: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

always connected. While this is certainly the case for small devices, and even mobile computers, it could also be the case for a desktop. The application model today is to bring the rich UI presentation and complexity of Java™ 2 Enterprise Edition (J2EE) and Web container to lower-end and intermittently connected devices without rewriting or rearchitecting the applications.

To accomplish this feat, some data and application processing is moved from the server to the client. This is done for the times when the device is disconnected. The user can execute transactions or just view data while the device is offline. In some cases, it is done just for enhanced performance. Depending on how the application is structured, it can process locally, against the server, or some combination thereof, depending on the programmer decisions and the state of connectivity when the user executes transactions. What makes this different from traditional, distributed applications is that the underlying platform facilitates the deployment and maintenance of the code on the devices, and that connectivity and transaction processing can be managed dynamically without user intervention. No longer does a programmer have to be concerned with state of connectivity, and facilities and APIs are available to insulate the application from needing to account for the state of connectivity. The technologies that make up the entire stack, including DB2e, Cloudscape™, MQe, SMF Bundles and others afford programmers the choices necessary to create applications tailored to the users and their states, not just to what the technology mandates.

WCTME enables programmers to partition applications to run sometimes on the server, sometimes on the device, and sometimes on both, with the choice of presentation (rich UI or browser, also called Web Container), data synchronization (automatic or user-initiated), application deployment and maintenance (with no user action required). In addition to the run times that make all of this magic possible is an integrated set of tools to make the application architecture and creation tasks easier, leaving the developers the time to write efficient logic and snappy user interfaces.

This book guides you through a sample application scenario introducing you to the different programming techniques to accomplish different tasks, as well as the tools that make programming to these facilities as easy as possible. You will not only see how the stack works, but get concrete examples of the code required and some of the decision points to select the appropriate technologies for different tasks. Bear in mind that some of the choices the writing team made in this example are not necessarily the same ones you would make for a production environment, but were chosen to provide you with the broadest exposure to the technologies available to you.

Not only does the WCTME architecture provide for the scaling of applications and movement of parts to the server or client, but it also uses an open standard

Chapter 1. Introduction to Workplace Client Technologies 3

Page 20: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

framework (OSGi(TM) SMF) for deployment and management of these application components or bundles.

WCTME is the next phase in application technology for lower total cost of ownership, providing users with the flexibility to operate in any state of connectivity, and programmers with an extended J2EE application model, down to the device, using standards-based technology. This can be done with little or no impact on existing application code or infrastructure, but rather with just a modification, or an evolution to the next level of user interaction.

This book gives you the technological understanding of how this is possible, and how you can take advantage of this technology in the programs you write or devices you build. Using a real-world scenario you will be shown what you need to understand the technology and develop solutions using it.

1.2 TerminologyThis section will familiarize you with not only the terminology, but how these parts fit together and lay the framework for the rest of the book.

1.2.1 Workplace Client Technology Micro Edition (WCTME)WCTME provides an integrated platform for extending enterprise applications to server-managed client devices such as desktop computers, mobile computers, Personal Digital assistants (PDAs), and other mobile and pervasive devices. The integrated package combines the tools of WebSphere Studio Device Developer and Micro Environment Toolkit for WebSphere Studio, with the run times WebSphere Everyplace Micro Environment, Service Management Framework, and WebSphere Everyplace Custom Environment, and middleware such as DB2e, MQe, and Web Services for building, testing, and deploying server-managed client software to pervasive devices.

1.2.2 WebSphere Everyplace Micro EnvironmentWebSphere Everyplace Micro Environment is an IBM implementation of the J2ME specification that complies with the various licensing and functional guidelines to obtain the Java(TM) and Java Powered Logos.

1.2.3 WebSphere Everyplace Custom EnvironmentSimilar to WebSphere Everyplace Micro Environment, WebSphere Everyplace Custom Environment provides a more custom set of libraries and functions to enable customers and partners to create more tailored versions of the Java run

4 WCTME: Application Development and Case Study

Page 21: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

times specific to their platforms, without necessarily needing to comply with established standards to get the Java logos.

1.2.4 J9J9 is IBM's independent implementation of the Java Virtual Machine. The combination of J9 with the configurations and profiles create the run times. The configurations and profiles are Java class libraries.

1.2.5 EclipseEclipse is an open-source development framework, or workbench, and set of widgets (SWT) designed for tools developers to leverage code reuse, a consistent user interface, and a plug-in architecture for developing new packages. While Eclipse was originally designed for tools developers, it has evolved to become a more general purpose application platform with its Rich Client Platform (RCP). See 1.2.6, “Rich Client Platform (RCP)” for details on the RCP. More information about Eclipse can be found at this Web site:

http://www.eclipse.org

1.2.6 Rich Client Platform (RCP)If you remove the tooling and IDE-specific functions from the Eclipse platform, what remains is the RCP. This RCP provides the core plug-in environment along with a set of functions such as update manager, help subsystem and so on, into which application programmers can plug-in their own code to create an integrated application execution environment. An embedded version of the RCP (eRCP) is being developed for smaller devices. More information about RCP can be found at this Web site:

http://www.eclipse.org

1.2.7 Standard Widget Toolkit (SWT)Analogous to AWT or Swing, SWT is a set of controls, panels, and other widgets that are the building blocks of a user interface. The SWT provides a rich set of controls and is open source, along with the rest of Eclipse. Just like the RCP, an embedded version of the SWT (eSWT) is being developed for smaller devices. More information about SWT can be found at this Web site:

http://www.eclipse.org

Chapter 1. Introduction to Workplace Client Technologies 5

Page 22: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

1.2.8 WebSphere Studio Device DeveloperWebSphere Studio Device Developer is an award-winning IDE from IBM for J2ME that extends Eclipse for the development of Java and C/C++ applications that run on pervasive devices, and forms the core of the WCTME tool chain.

1.2.9 Java 2 Micro Edition (J2ME)J2ME is a Java platform for consumer and embedded devices. Like the enterprise (J2EE) and desktop (J2SE) platforms, J2ME is a set of standard Java APIs that delivers the power and benefits of Java technology tailored for consumer and embedded devices including a flexible user interface, robust security model, broad range of built-in network protocols, and support for networked and disconnected applications.

J2ME configurationsJE2Me configurations are a virtual machine (VM) and a minimal set of class libraries that provide the base functionality for a particular range of devices that share similar characteristics, such as network connectivity and memory footprint. Currently, there are two J2ME configurations: the Connected Limited Device Configuration (CLDC), and the Connected Device Configuration (CDC).

J2ME profiles Profiles are Higher-level APIs that, combined with device configurations, provide a complete run-time environment targeted at specific device categories. Profiles further define the application life-cycle model, the user interface, and access to device-specific properties.

Mobile Information Device Profile (MIDP)The MIDP offers the core application functionality user interface, network connectivity, local data storage, and application management required by mobile phones and entry-level PDAs. Combined with CLDC, MIDP provides a complete Java Runtime Environment.

Foundation Profile (FP) CDC profiles are layered so that profiles can be added as needed to provide application functionality for different types of devices. The FP is the lowest level profile for CDC. It provides a network-capable implementation of CDC that can be used for deeply embedded implementations without a user interface. It can also be combined with Personal Basis Profile (PBP) and Personal Profile (PP or PPro) for devices that require a graphical user interface (GUI). It is also possible to write SWT applications on top of Foundation Profile to create a rich user interface on top of the foundation.

6 WCTME: Application Development and Case Study

Page 23: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Personal Profile (PP)The PP is a CDC profile aimed at devices that require full GUI or Internet applet support. It includes the full Java Abstract Window Toolkit (AWT) libraries and offers Web fidelity, easily running Web-based applets designed for use in a desktop environment. PP and PBP are layered on top of CDC and FP.

1.2.10 Service Management Framework (SMF)SMF is an implementation of the Open Services Gateway initiative (OSGi) Service Platform specification. SMF is currently at OSGi release 3. The Framework acts as a layer that enables operators to deploy multiple applications on a single Java Virtual Machine (JVM). In addition it provides a framework for application life cycle, including delivery to the device as well as dynamic starting and stopping of the applications. Application developers partition applications into services and other resources. Services and resources are packaged into bundles. Bundles are files that serve as the delivery unit for applications and have manifests with special headers that enable the sharing of classes and services at the package level. Bundles can be started and stopped dynamically, allowing systems to be updated without extended service or downtime. In many cases, these updates can be performed over the air (OTA) without any user intervention, interaction, or even awareness!

Additionally, the Eclipse framework has incorporated SMF into its underpinnings, so ultimately, all of the plug-ins that run in Eclipse run as bundles, and can be dynamically loaded, unloaded, started and stopped. This adds an additional element of flexibility and choice to the application developer, as well as a more robust platform underneath.

1.3 Technology overviewIt is important to take a moment to go over a little of the history to understand the present. In the embedded Java (J2ME) space, there are a series of configurations and profiles that define which sets and subsets of Java class libraries (along with other new classes and methods specific for the embedded world) should be available to different classes of devices. This book assumes a basic knowledge of Java and J2ME and references J2ME subjects. Refer to Appendix , “Related publications” on page 411 if you would like pointers to J2ME resources.

There is no specification that says that a cell phone with x amount of memory should be an MIDP device, or that a PDA should run only CDC applications, but the specifications do loosely map to classes of devices with different user interfaces, processor, and memory capacities. These decisions belong to the

Chapter 1. Introduction to Workplace Client Technologies 7

Page 24: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

device and platform makers and you, the programmer. Along with this come the interesting question of how to get the applications onto these devices. After all, they are limited in size, very mobile, only sometimes connected. Even if a preload image is used for initial system loading, how would updates and patches take place?

The OSGi Alliance has defined a standard for management and deployment of applications. IBM has created an implementation of this standard called Service Management Framework (SMF). SMF is a set of run times enabling applications to be server-managed, and deployed to the client devices regardless of device size (as long as it can handle the SMF platform code, which also requires CDC Foundation) without any specific user or administrator action. OSGi provides the architecture to enable JVM reuse, applications, and application components to be dynamically deployed to a device, then started and stopped without tearing down and restarting the JVM. To learn more about OSGi, see the following Web site:

http://www.osgi.org

SMF, and its tooling componentry enable a developer to break applications into manageable, deployable, scalable components, called bundles. Combined with other run times such as DB2e, MQe, synchronization technologies and others, SMF enables you to strategically break down applications into these bundles, allowing them to scale such that in a disconnected state, application users can query inventories, process orders or forms, queue transactions, update databases, and work in an offline state as though they were connected, with the exact same user interface. This is done by keeping the programming model the same, breaking the applications into bundles and deploying them with SMF to cell phones, desktops, and everything in between.

What gets deployed where is a function of how the application is designed, its function and structure, and the Device Management Server, which implements the definitions and designs when the application architects tell it how the application bundles are to be deployed to which classes of device.

8 WCTME: Application Development and Case Study

Page 25: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 1-1 Platform structure

Figure 1-1 shows the generic structure of the runtime stack. You can see the underlying operating system platform, whether it be Windows®, Linux®, PalmOS or any cell phone or other device operating system. On top of that run the JVM and the SMF platform. This enables the application loading and execution environment. On top of the JVM and SMF platform are the services the application might need such as DB2e, MQe and other application services or components. These can be written as high-level services, or even delivered as bundles themselves. This is the basic execution environment, and it is on this that the overall application presentation and execution is based. In 1.4, “How the parts fit together”, you will see how all of the platform components, services, and applications form the user environment.

1.4 How the parts fit togetherWhen an application is developed for WCTME, it is a Java application, and currently, this application is a J2ME application. Note: Rich UI applications in this model are Java applications, but this does not preclude you from writing Web applications and putting the J2EE artifacts such as beans and JSPs into the bundles and presenting the application to the user in a browser on the device. While WCTME was originally designed for small devices such as PDAs and cell phones, the platform is converging with, and moving to the desktop as well. As the technology and product set evolves, you will inevitably experience some growing pains. However, those pains should be limited to the naming and combinatorics of which parts go where, and not the applications themselves. Specifically, WCTME, as the name implies, is targeted at small, Micro Edition devices. However, the same SMF platform and Eclipse RCP technology runs on

Driver Driver

JVM

OSGi

Driver

OSGi

Operating System

Bundle (application)

Fram

ewor

k

Chapter 1. Introduction to Workplace Client Technologies 9

Page 26: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

desktops as well, enabling you to run the same applications on these differently classed of devices. This gives rise to the inevitable question of how all these parts come together and on what platforms. It also should get you thinking about how to present the application to the user. In particular, while the application platform is consistent (RCP and SWT), and the delivery mechanism and the connectedness logic is the same, J2ME and J2SE devices have very different capabilities for presentation. As a result, start looking at whether you want to deliver a particular application as a Web browser (Web container) application, or if you desire a richer user interface, which also forces you into other design decisions based on device capabilities.

Figure 1-2 on page 11 shows how the stack fits together. At the lower levels are the core of any computing device: the hardware, device drivers, and core operating system. On top of that sits the Java Virtual Machine (JVM). This JVM is really a combination of the JVM and run times for the device, where run times refers to the J2ME configuration and profile combination appropriate for that class of device. In the desktop space, this would just be a J2SE-based VM and class library set.

This is a big decision point in your creation of applications. The reason is that SMF must have a minimum of CDC Foundation to run. SMF does not run on MIDP devices. As long as CDC Foundation is there, the SMF model can be used. For lower-end MIDP devices, more traditional application deployment and management methods must be used. In Appendix B, “Using MIDlet applications to access Web Services” on page 361, you can see how a MIDlet can access Web Services to enable direct access to enterprise functions on a server. Alternatively, if you have a smaller device, you could just choose to use a Web container or browser presentation model.

In the MIDP case, the application has to be deployed to the device through some mechanism other than SMF. The CLDC/MIDP configuration and profile is not sufficient to run SMF, so some other solution is required to get the application to the device. It can be preloaded on the device, either by a manufacturer, platform maker, or customizer, if devices are being deployed by an IT shop. Another alternative is to have the application deployed over the air by a service provider, or even installed by the user with some type of synch operation.

All of these methods work just as well for non-SMF CDC applications. However, with the SMF platform, applications, more specifically application bundles, can be deployed as needed, updated whenever there is a new version on the server, and dynamically started and stopped with multiple applications sharing the same JVM instance. While SMF does take up some resources, SMF provides a level of scalability and flexibility not seen before, even on many desktop platforms.

10 WCTME: Application Development and Case Study

Page 27: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 1-2 Service Management platform

Figure 1-2 shows the service management platform and its location on the Java stack. When an application user attempts to start an application, the appropriate bundle manifests are examined (Figure 1-3 on page 12) for appropriate prerequisites or dependencies. Where needed, the device management server is consulted for what bundles are present. Without any user intervention, the appropriate bundles are delivered to the device so the application can be executed.

It is this SMF platform that enables bundle activation and life cycle management of the application components, or bundles. As you will see later in this book, the tools provided for application development assist in the creation of bundles, with all of the requisite housekeeping such as creating BundleActivators and so on.

The other part of the picture, implicit in this scenario, is connectivity. Connectivity can take the form of wired LAN, WiFi, cellular modem, or any number of connection methods. The important thing here is that from the platform’s perspective, the connection method does not matter. First, it is a layer below the platform. Second, the entire premise of these technologies is that they work connected, disconnected, or anywhere in between.

This discussion also provides the opportunity to mention WebSphere Everyplace Connection Manager. WebSphere Everyplace Connection Manager is a connection stack that enables a user to not only tunnel into an internal company network securely, but enables a user to roam between networks seamlessly. An example is that of a user replicating a large database, connected with WebSphere Everyplace Connection Manager. If the connection drops for any reason (driving through a tunnel, the WiFi link went down, and so on), WebSphere Everyplace Connection Manager suspends the connection. When the connection is reestablished, the replication continues as though the connection had been alive all the time. In fact, this can be extended even further.

Java Virtual Machine Execution Environment

Module

Life cycle

Service Registry

ServiceBundle

Java Class Library

Service Framework

Chapter 1. Introduction to Workplace Client Technologies 11

Page 28: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

For example, rather than a dropped connection, if you are in an office replicating a large file, such as synchronizing a customer database, and you need to head home for the evening, WebSphere Everyplace Connection Manager will allow you to reconnect the device at home with your DSL, cable modem or even dial up. Despite the fact that this is a totally different network than where you started, the replication continues as though it had never been interrupted. This process does not involve the application. What this means is that the applications are truly separated from worrying about the connection state. You can work any time, any where, without worrying about the connection state.

Figure 1-3 WCTME SMF bundle deployment

1.5 WCTME or WCTRE? A robust set of program development tools is available to facilitate the creation of not only J2ME applications, but also Web applications and even J2SE applications, and structure them either as fully local applications, server-based applications, or anything in between. One question that has been asked recently has to do with the current IBM announcements of WCTME and WCTRE (Rich

Managed ClientServices

SyncML Framework

OSGi Device Agent

Bundle B

Bundle A

Clients

HTTP

SyncML/DMProtocol

Bundle B

Bundle A

BMSModification

HTT

P

Device ManagementServer (DMS)

J2EE

Web ServicesInterfacesPlugins

Depends

Server

12 WCTME: Application Development and Case Study

Page 29: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Edition). What’s the difference? Where does each apply? This is actually an example of the evolution of the WCT product family.

Both WCTME and WCTRE use the same Java and OSGi/SMF bundle mechanism for applications. Both offer programmers the ability to write bundles that extend the services provided. The easiest way to think about this is that WCTME is the core platform, whether J2ME-based or J2SE-based, with OSGi, and extension services including DB2e, MQe and others. WCTRE is a set of application components that perform a variety of office tasks such as e-mail, calendaring, word processing, spreadsheet processing, and so on. These components are extensible and customizable through a set of programming tools, but the primary focus of WCTRE is on these application components.

WCTME is the platform upon which WCTRE (and other OSGi/SMF, as well as other core J2ME applications) is built. Figure 1-1 on page 9 shows the structure of that platform. If you plan to build applications to the base platform, you use WCTME. If you want to extend the office components, you use WCTRE.

In WCTME 5.7.1, released in August 2004, the package is built with the run times and tools for J2ME applications. Under development is a desktop (J2SE-based) offering analogous to the WCTME product. After that, the products should converge into a coordinated desktop to device, end-to-end enabling offering. In both cases, the user interface can be either a Web container (browser)-based UI, or a rich UI, written to the Eclipse RCP and SWT.

In 2005, platform offerings are evolving that combine this into one offering. The technologies currently exist, but they are segmented into J2ME and J2SE. You should soon see the convergence of these segments, along with the tools and run times to support it end-to-end. There will be applications for Web container presentation, and also Eclipse RCP with SWT (eSWT and eRCP for embedded Java applications and devices).

1.6 ToolingThrough all of the work to build these offerings, IBM understands that without developers and tools, the run times are of little use. The core tool for WCTME applications is WebSphere Studio Device Developer. This set of tools surrounds the core Eclipse platform designed primarily for J2ME application development. Figure 1-4 on page 14 shows an overview of WebSphere Studio Device Developer. WebSphere Studio Device Developer is configured to fulfill the J2ME segment of application development, supporting the various configurations and profiles, and providing tools for profiling, optimization, debugging, and deployment to remote devices and emulation of devices, in addition to the standard Eclipse tools features and functions. WebSphere Studio Device

Chapter 1. Introduction to Workplace Client Technologies 13

Page 30: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Developer can also be used to target J2SE applications and forms the foundation for the Micro Environment (ME) toolkit, which is a set of features and components that facilitates the building of SMF bundles and Web, extension and enterprise services for J2ME applications. WebSphere Studio Device Developer baseware and the ME Toolkit give you a complete development environment to code to the WCTME stack.

On top of this core tooling is a set of technologies you can install based on the additional features you want to build into your applications. These include MQe, DB2e, Mobile Media APIs (MMAPI), JDBC (JSR169) and so on. This entire set of tooling can be further extended by installing it into, or liked with WebSphere Studio Application Developer or Rational® Application Developer, depending on the version you are using. This further integrates the application development experience to the J2EE models as well.

The number of permutations can be a bit intimidating. But by looking at it the same way as the runtime stack, you can see how you can tailor the development environment based on the developer roles and tasks. You use one integrated toolset without having to learn multiple tools to move from segment to segment on the project.

Figure 1-4 WebSphere Studio Device Developer overview

The OSGi/SMF tools such as the Bundle Developer tools are extensions to WebSphere Device Developer that are installable through the Update Manager function of WebSphere Device Developer and Eclipse. These tools build on the core J2ME tooling to enable enterprise functionality such as messaging (MQe),

Eclipse

EditCode

CompletionRefactoring

WizardsVisual Editor

TeamDevelopment

United EmulatorInterface

On-Target Debuffer (JDVJDWP)On-Target Analyzer (JVMPI)

Smartlinker (JXE)JIT/AOT Compile J2ME

ProfilesConfigurationsJava Powered

J9Virtual Machine

WebSphere Everyplace MicroEnvironment

WebSphere Studio Device Developer

14 WCTME: Application Development and Case Study

Page 31: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

database (JDBC, DB2e, Cloudscape), Web services and of course, OSGi/SMF. This is one of the main components of the ME toolkit.

In addition to all of these tools in the WCTME package, WebSphere Studio Device Developer has the ability to install, or link into a copy of WebSphere Studio Application Developer and WebSphere Studio Site Developer.

This enables any programmer J2EE, J2SE, or J2ME (and even C/C++) to create an integrated application-development IDE with one user interface, one set of linkages to source code control and bug tracking system, one mechanism for team development and componentization, one set of debugging and help frameworks, and so on. In short, there is one tool to learn. Period. There is not a tool for embedded, another for debugging, another for Web development, but one, componentized, customizable, scalable tool so programmers and designers only ever have to learn one. Your job function or programming task within the overall project determines the combination of functions you use. Referring to Figure 1-5 on page 16, it is evident which pieces one would use, depending on the tasks to be completed.

Note: At the time of this writing, Rational Application Developer and Rational Web Developer version 6 have been released. WebSphere Device Developer is in the process of converging to link into RAD/RWD. The WCTME 5.7.1 product is configured only to work with WebSphere Studio Application Developer and WebSphere Studio Site Developer until this convergence is complete.

Chapter 1. Introduction to Workplace Client Technologies 15

Page 32: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 1-5 WCTME 5.7.1 tooling

As you can see in Figure 1-5, all of the tools interoperate and interlock. It is likely that no one person on a development team will need to perform all of the tasks across the tools. What is important is that they share components so that tasks that are common across segments use the same tool plugins. Developers can move among project segments and tasks without the learning curve of new tools.

The goal of tools in the past has been to make technology easier. A new approach has been taken with the WCTME tools. Rather than trying to simplify the technology, these tools are designed around tasks, and how best to streamline a task. Ultimately, the goal is to have sets of application components that developers and others can assemble as full applications. To this end, the tools are currently geared towards creation of these components through wizards and builders, doing the bulk of the required work, enabling programmers to concentrate on the real logic of the programs. Ultimately, these components will be assembled into applications.

Questions about tools in the past have been about which tools to get, and where to get them. This is no longer the case. They are all packaged together, additional technologies are available through the update manager, and it all links into the enterprise WebSphere Studio Application Developer and WebSphere Studio Site Developer, soon to be RAD and RWD, tooling.

Device Applications

End to End Applications

WebSphereStudioDevice

Developer

IBMMicro

EnvironmentToolkitfor WS

WebSphereStudio

ApplicaationDeveloper

WebSphereStudio

SiteDeveloper

SoftwareDevelopers

Server Applications

WebServices

RichClient

RichServices

WebJ2EE

J2EEJ2ME

16 WCTME: Application Development and Case Study

Page 33: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Chapter 2. The Case Study: ITSO Car Rentals

This chapter provides you with an overview of the example business scenario chosen for this study. You can see the elements of the business processes being put into place, and understand what technologies were chosen to solve the different parts of the implementation. You can also see the overall architecture of the system.

Understand that some of the choices this team made were not necessarily the best technology choices to solve a certain problem, but rather some were chosen to give you a view of the breadth of the components available to you as you make your design choices. These are pointed out throughout the text. As you read this book, you can think about the pros and cons of different design choices and get a better idea of what is involved in using different technologies to solve different business problems.

The completed sample program can be downloaded from IBM. See the Appendix D, “Additional materials and how to obtain them” on page 403 for more information about obtaining the sample program.

2

© Copyright IBM Corp. 2005. All rights reserved. 17

Page 34: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

2.1 Business overviewIt is likely that you have traveled, and upon arriving at the airport, had to board a shuttle to the rental car agency. Well, our ITSO Rentals company is no different. Upon boarding the shuttle, the driver asks for your rental record, or club membership number. They might ask for your name. Your picture might even be on the device and they do not have to ask you anything, assuming it is a good picture. They look you up on a handheld device and mark that you have arrived. Ideally, the driver will tell you in which parking space, or slot, your car is located.

When you get to the rental agency, your car is waiting for you in the designated parking space. That space is identified with the slot number given to you. How did they know when you were going to arrive? What if your flight was late? How is all of this information transmitted and coordinated between the rental agency central system, the airline, the handheld device being used by the driver, and even perhaps, a handheld device used by the rental customer?

In the IT infrastructure of this car rental agency, there are servers that house customer and rental records. Shuttle drivers need remote access to this data so that they can serve the customers.

2.1.1 Data requirementsIn this business process, the customer gets on the bus, the driver gets some identifying information, essentially checks the customer in, and gives the customer a slot number. You, okay we, have decided on a Web presentation, the reasons for which you will soon see.

Now let us look at some of the attributes of the operating environment.

� Handheld device

– Limited processor– Limited memory– Limited screen real estate

� Mobile environment

– Intermittent connectivity

• Local data is needed for disconnected operation, unless the business process is such that disconnected operation is not a viable mode in which to operate.

• Data synchronization is needed for offline portions of the operation.

• Communication with back-end servers in real time is not necessarily required for operation in this business model.

18 WCTME: Application Development and Case Study

Page 35: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

� Data such as flight information from the airlines and other external sources is used as a core process. How is this data obtained and updated to the device?

2.1.2 Information infrastructureThe sample application will be used by employees of the ITSO Rentals company. The application’s panels are viewed using a browser on a handheld device. The application’s main panel displays two groups of information. The top group has an HTML table that lists rental customers expected to arrive in the near future. The bottom group contains customers who have arrived but have not yet left the rental location. Ideally this application is used by the ITSO Rentals shuttle driver who picks up the customers at the airport terminal and takes them to their vehicle in the rental company’s parking lot.

When a customer is picked up at the airport by the company shuttle driver, the driver finds the customer's name, and picture in the top table, then checks the box next to their entry. When the Submit button is selected, the application updates the customer’s status in the local database, sending a message to the host server telling it that this customer has arrived.

The customer’s name will now be displayed in the bottom table of the application, but it is possible that the exact location of the renter's vehicle is not available yet. When the host server sends a response to the message mentioned above, it will indicate in which parking space the renter's vehicle is located. The next time the application screen is updated, the location will then be displayed. The bus driver can then take the customer directly to his or her car.

The application also checks the latest flight information for the arriving customers. If an arriving flight is delayed or cancelled, then the application will highlight that information with a background color for the bus driver.

A host server in this scenario will contain information about all the customers the company has. However, recall the data requirements. The handheld device the bus driver uses holds only a small subset of all the customers arriving in the near future. The application will be able to synchronize that subset of the host database with the use of Sync button. The driver will use this button periodically to send locally stored updates to the server and to collect any updates from the server.

Chapter 2. The Case Study: ITSO Car Rentals 19

Page 36: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 2-1 The big picture

Let us look at the data structures. The database has three tables. One for customers, one for contracts, and one for flight information. The database is loaded with customer and contract information in this example. In a real production environment, these tables would be updated by reservation agents to add customers and rental contracts, updated by car service workers to record what slot number a car is in, and other information such as the status of the customer based on the actions of the shuttle driver.

Aside from the customer data, there is also a table for flight information. Generally, a car rental agency would not maintain flight information, but for the purposes of this case study, our database will have flight information to allow the system to determine if a customer’s flight is delayed, cancelled or on time. As you will see further on, we decided to interact with this database through a Web Service, because in the real world, it is very possible the airlines would provide this information as a Web service. As a Web Service, it can also be accessed from other nonITSO Rentals-supported devices, such as MIDP devices. It might be a public service from the airlines that MIDlets can access real time flight information from a Web service so travelers, from their MIDP phones, can find out if their flights are on schedule. This is what we have done in Appendix C, “Sample server-side Web Service” on page 375.

The business process we modeled works something like this:

Web Service Client

MQe Server

Database Sync

Device Services

DB2e Sync

MQe Client

DB2e Access

WEA Server

WAS

Web Service

DB2DB2e

ServerPocket PC

Device Sync

Web Service (Offline)

Flight Delays

Car Slots

Customer IDNamePhoto

ContractID Cust IDFlight Info Car Slot Status

PendingOn busExited

FlightFlight info Status

On timeDelayedCancelled

TABLES

20 WCTME: Application Development and Case Study

Page 37: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

� Data is periodically synchronized at the device. This data includes the information and rental records for customers that will be arriving soon. We get this from the flight information. The reason for this is so that if the signal is lost, the driver is not restricted in what they can do. They have a set of data for the customer due to arrive in the next X hours.

� When a customer arrives at the shuttle, the driver gets identifying information from him or her, and marks the customer as arrived. If there is a good signal, the driver retrieves the car location (slot) number for the customer and tells him or her where the car is. The reason MQe was chosen for this function is that it might not be known until just before the customer arrives. Perhaps a car is not even assigned until the customer checks in, so the information has to be somewhat real time. Also, if the connection is currently not there for some reason, it is not a critical problem if the customer has to find out where the car is when they get to the lot, but rather this is a nice added feature assuming there is a connection.

Now we can walk though the data flow:

1. Data is updated on an ongoing basis by reservation agents. Customer records are added and updated. Rental record numbers are generated from reservations agents.

2. The flight information table is updated on an ongoing basis. Again, it is more likely that this would be queried real time from a Web service, but perhaps there is a concern that the Web service is not always available, so a Web service client can be written to grab a lot of information and store that in a local database. Again, this is an example of the design considerations and flexibility afforded you by the richness of the WCTME stack.

3. This data is synchronized to the device based on expected arrival time. The team considered the cases where the customer might not be arriving by plane. However, for this case study, we assume the customer is arriving by plane. If, for example a flight is delayed for three hours, that rental record would not need to come to the device at the originally scheduled time, but rather on projected actual arrival time.

4. A customer arrives at the airport, or rental facility. A rental agent checks this customer in on the device. The device has a local subset of the database that contains this customer’s record along with the rental record. The driver gets the identifying information from the customer, and sees the correct record on the device. They check the appropriate box on the display. A message goes to the server through MQe to ask for the car slot number. A message comes back with that slot.

5. Also, the customer is now flagged as checked in at the rental location, so that record no longer needs to be part of the synch data set.

Chapter 2. The Case Study: ITSO Car Rentals 21

Page 38: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

6. The next time the data synchronizes, that customer is no longer part of the shuttle driver’s synch data set, and any new customer and rental records replace that customer’s information.

This is the user interaction scenario. Now let we can look at the back-end systems.

� Data synchronization is periodically initiated by the client device. This uses the DB2® synch server and the local DB2e on the device. As a part of this process, the flight information is used to determine the data subset to be synchronized.

� An MQ server is in place with an MQe gateway to enable the messaging to take place for the slot number interactions.

Web Services alerts are in place which alert the client device to delayed or cancelled flights so that these records are not part of the synchronization data set. After all, if a flight is cancelled, the customer record would be part of the expected arrivals synch data set until removed by some business process, or reservation agent rebooking the car rental at the customer request. There is no reason for those records to remain on the device or on the shuttle driver’s active expected arrivals display.

To perform these functions, the application will have local DB2e database tables, send and receive MQe messages, use a Web service to get the flight information and be driven by a servlet with a JSP.

A complete implementation requires a host database to sync with, an MQe server to receive and respond to messages, and a server to supply the Web service flight information.

The application also contains a Login panel and a demonstration Config panel. The login panel allows the user to enter a user ID and password for use during the database sync step. For this demonstration, no other validation is done after the user ID and password are entered. The configuration panel is used to select what services (DB2e, MQe, Web services) should run in stand-alone mode, or with which host systems these services should communicate.

This sample application is not meant to be a complete solution, but to show the various technologies and how to combine them into a usable application.

Note: The application will be implemented in a way that will allow for demonstrations of the application without the hosts needed for flight status, messaging, and data sync. For this stand-alone operation, a Reset button will be included so the user can reset the local data to start the demo over again.

22 WCTME: Application Development and Case Study

Page 39: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

2.1.3 Design decisionsLook back at Figure 2-1 on page 20 to see how we got to some of the design points we did. The first thing is that the presentation for this project is a Web container, or browser. We could have chosen to use a rich user interface and written core Java J2ME code using, say, the Foundation Profile with a widget toolkit such as AWT. The reasons for our choosing a browser design are:

1. The eRCP and eSWT runtimes are not yet available in a publicly released product. They are in the technical preview only stage as we write this book.

2. MIDP, while it has a layout and presentation model, does not have a rich enough API set for server side data access (JDBC, MQe and so on.

3. The Web container is a simpler UI programming model. The focus of this case study is using the technology, and is not really concerned with the UI technologies themselves, especially since the UI runtime picture is not yet complete.

So we have a Web container presentation, using a number of services for data access, server communication and data synchronization.

Next, we have decided that offline operation is required, so we need to have data on the device. This makes us decide which database technology to use. The WCTME stack supports both Cloudscape as well sd DB2 in this environment. Because JDBC is the access method, the decision points come down to cost and size. You will of course need to do your own evaluations, but the significant differences between Cloudscape and DB2 in this case are that while Cloudscape is open source and less expensive, it is also a bigger footprint on the device, and being open source, reliability, scalability, and maintenance could come into question. DB2 on the other hand, is a more battle-tested product, is backed by the IBM Corporation and is a much smaller footprint. The trade-off here is it is more expensive. Note there is no quantitative information in these statements. They are designed to be generic statements to give you ideas in what to look for without putting any bias one way or the other into your heads. Also, these are the larger examples. There are many more differences between the two, so you should thoroughly evaluate your choices with respect to your requirements and environment. In the case study, we have chosen DB2 Everyplace (DB2e) on the device for this example.

Looking at Figure 2-1 on page 20, you can see that DB2e is on the client device, and a DB2 synchronization server is on the back end. The team decided that real-time access to live, service-side customer and rental records is not required. The signal in and around airports can be spotty, and while the car rental records are updated often, it is not likely that a customer on the airplane already, will need to have their record updated. A periodic synchronization is all that is needed. In some instances, daily synchronization is all that is needed. This

Chapter 2. The Case Study: ITSO Car Rentals 23

Page 40: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

brings up the considerations of limited device size and memory into the equation. You would need to make those quantitative decisions for your own project. In other instances, such as ITSO Rentals, synch is needed much more often, perhaps every 15 or 30 minutes. But the business requirement is to make the system useful by creating the ability to access data offline.

Some other design decisions include how to interact with data on the central servers. The most prominent mechanisms are messaging, Web services client agents, local database update, and a server side trigger to initiate a process on the server when changed data is synchronized out from the device. Another database-oriented alternative is to update the database on the server in real time.

Real-time, server-side database access (over a socket for example) is not feasible in this scenario because of the intermittent nature of the connection to the client device. After all, you do not want to limit the shuttle drivers’ ability to process customers when there is no signal. So we are down to messaging, Web services, and local data access with server-side triggers to complete the business process on the server.

In any event, the business process is going to be completed on the server. In our example, there no business process on the server to speak of, but in a real world implementation, this is a design consideration. In a real production environment you would need to evaluate whether secure, guaranteed delivery messaging is needed for server update. If a Web service agent could do the work for you, you would have to bear in mind the instances where there is no live connection, and how to cope with it. Perhaps a delayed update with a server side trigger on a database synch is acceptable. Perhaps, real-time, server-side database updates are needed. What helps you make this choice is the profile of the business process.

Recall that the underlying premises of the WCTME platform are:

1.A device is not just a small gadget such as a PDA or cell phone. A device is anything from one of these lower powered devices up to a tablet, notebook, or desktop PC.

2.The application model does not change from what is currently used, but rather is modified to make the assumption that the device is not necessarily always connected. While this is certainly the case for small devices, and even mobile computers, it could also be the case for a desktop. The model is to take what goes on today in the enterprises with Java 2 Enterprise Edition (J2EE) and Web container or rich UI presentation, and bring that to the lower-end devices without rewriting or rearchitecting the applications.

24 WCTME: Application Development and Case Study

Page 41: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

You will see in this case study, the device is logically some type of mobile handheld device. In other scenarios, for say an insurance adjuster, this could be a desktop, mobile computer, or even a handheld device.

2.2 Running the sample applicationThe sample application is created step by step in the following chapters. Here is an overview of the completed sample application.

2.2.1 The sample application panelsThe sample application has three panels:

� Login� Main� Config

Use the Login button to proceed to the main panel. A user ID and password must be entered. These are not verified locally or remotely in the sample application, but the same user ID and password are used during DB2 sync. See Figure 2-2.

Figure 2-2 The login panel

The main panel displays the pending and arrived rental customers. Check boxes display next to each customer so that they can be marked to be moved to the next state: Pending →Arrived. Arrived →Exited. See Figure 2-3 on page 26.

Chapter 2. The Case Study: ITSO Car Rentals 25

Page 42: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 2-3 The main panel with no data displayed

To record a status change, or just refresh the main panel, along with any messages that might have arrived, use the Refresh/Submit button.

A Sync button is available to perform a database sync with the server. Although the sync can complete quickly, there is a delay before the mirror database and the host database are replicated. After that, the change is displayed on the server.

A Device Update button is available to call a local agent to update the client device based on jobs defined on the device management server.

The Logout button returns the user to the login panel.

To configure the demo, use the Config button to navigate to the configuration panel.

For demonstration purposes, there is a Reset Demo button. This updates the local database to show that no users have arrived and clears the vehicle location information.

The config panel (Figure 2-4 on page 27) allows the user to set whether the demo should be run in stand-alone mode or to use real servers for DB2 sync,

26 WCTME: Application Development and Case Study

Page 43: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

MQe messaging and Web services. The hosts and ports to be used can be configured on this panel.

Figure 2-4 Config panels

Chapter 2. The Case Study: ITSO Car Rentals 27

Page 44: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Note that each server is defined differently!

A Cancel button is available on the config panel to quit without committing any changes.

The Save Changes button is used to store all the settings into the properties file and to initialize the appropriate services of the application.

For demonstration purposes, a Create Sample Data button is available. This creates the local database tables and insert sample data. For the same reason, an Insert Local Pictures button is available. This loads the files Image1.jpg through Image7.jpg (found in the demo-images sub directory) into the local database. Any photos can be used, but they must be less than 10,000 bytes in size and should display well at 75 x 75 pixels.

2.2.2 The sample application flowThe first time the application is started, the properties file, if not provided, will be created with default values and all services (DB2e, MQe messaging, Web services) set to stand-alone mode.

After the user logs into the application with their DB2e user ID and password, the main screen displays any pending customers. Initially, there will be no local data and a sync with the DB2 sync server will be necessary.

For a quick demonstration of the sample application, we will run with the defaults and generate local data.

1. Click the Config button and go to the config panel.

2. Scroll down to the bottom of the config panel and click Create Sample Data.

3. The config panel will redisplay, scroll down again and click the Insert Local Pictures button.

4. The config panel redisplays. Scroll down again and click the Cancel button. The main panel should redisplay with sample data. See Figure 2-5 on page 29.

28 WCTME: Application Development and Case Study

Page 45: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 2-5 Flight status info represented by colored background

5. Check one of the customers as arrived, as in Figure 2-6.

Figure 2-6 The main panel with sample data and a customer checked

Chapter 2. The Case Study: ITSO Car Rentals 29

Page 46: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

6. Click the Refresh / Submit button. The panel will update showing the selected user as arrived, as in Figure 2-7.

Figure 2-7 A customer has arrived and vehicle location received

With the MQe service running in stand-alone mode, the vehicle location is available immediately. With an MQe server configured, the messages flowing out to the server and back take a few seconds.

7. Use the Refresh / Submit button again to see if the updated information has been received. If the MQe server is configured but not available, the messages are queued for later delivery. In this case, the bus driver has to deliver the arrived customer to the rental office to find the vehicle location the old fashion way, or use the bus radio.

8. After the customer has been delivered to their assigned vehicle, the driver again checks the box next to their name to marked them as having exited the bus. The next Refresh / Submit updates the customer record again.

9. To reset the sample data, select the Reset Demo button.

2.2.3 Files created by the application on the deviceThe application creates the following files and directories in Table 2-1 on page 31 on the device:

30 WCTME: Application Development and Case Study

Page 47: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Table 2-1 Files and directories

2.2.4 Application propertiesThe sample application is designed to run in a stand-alone, demonstration mode, simulating the server side components, or attempt to use the servers configured. The application and its servers are configured using the application config page. The settings are saved in a properties file. When the application runs, if the properties file cannot be found, one is created using default values and all services will default to running in stand-alone mode.

The properties file contains the following values in Table 2-2.

Table 2-2 Properties file

file Notes

itso_rentals.properties If the application properties file is not found one is created with default values

ITSODatabase A directory for the DB2e files

ITSOQueuesa

a. The name of this file is dependant upon the device’s queue name defined onthe application configuration panel. The name must be unique in the system.

A directory for the MQe files

OSGiAgentTree.binOSGiAgentTree.bin.bak

File(s) generated by the SyncML/DM OSGi Agent bundle.

Note: Once created, you should only delete these files or directories if you intend to reset the device or the specific subsystem that created them.

Property Description

itso.database.standalone Stand-alone mode setting for database services (sync only)

Default value: true

Configured with the application config panel

syncprotocol Default value: isync:db2e:

server.url Address of the database sync server

Default value: http://your_db2sync_server:80

Configured with the application config panel

Chapter 2. The Case Study: ITSO Car Rentals 31

Page 48: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

isync.user The user ID of the person logged into the program and used during sync

Configured with application login panel

isync.password The password of the person logged into the program and used during sync

Configured with application login panel

isync.timeout sync time-out, see DB2e sync documentation

Default value: 60

isync.trace Level of sync trace, see DB2e sync documentation

Default value: default

path Directory where database tables are stored, see DB2e sync documentation

Default value: ITSODatabase

jdbcsuburl see DB2e sync documentation

filesubdir see DB2e sync documentation

itso.mqe.standalone Stand-alone mode setting for messaging services

Default value: true

Configured with application config panel

itso.mqe.QMIPAddress Address of the MQe server

Default value: your_MQe_Server

Configured with application config panel

itso.mqe.QMPort Port of the MQe server

Default value: 8086

Configured with application config panel

itso.mqe.QMName Local MQE queue name and must be unique for each client of the MQe system

Default value: ITSOQueues

Configured with application config panel

Property Description

32 WCTME: Application Development and Case Study

Page 49: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

This table includes properties necessary for performing a database sync with the server that will be discussed in Chapter 10, “DB2e synchronization” on page 271. Not all properties are editable using the sample application’s config panel.

2.2.5 Application services and technologiesThe sample application uses the following enterprise technologies:

� DB2 Everyplace� MQe messaging� Web Services� Device Management

itso.webservice.standalone Stand-alone mode setting for Web service

Default value: true

Configured with application config panel

itso.webservice.sleeptime Number of milliseconds that background Web service thread waits between attempts to contact Web service for flight information updates.

Default value: 30000 (30 seconds)

Configured with application config panel

itso.webservice.endpoint_address_property Address and port (host:port) of Web service server

Default value: your_web_service_server:80

Configured with application config panel

itso.devicemanagement.standalone Stand-alone mode setting for device management services.

Default value: true

Configured with application config panel

itso.devicemanagement.keyAddr Address and port (host:port/address) of device management server

Default value: http://your_device_management_server:80/dmserver/SyncMLDMServletAuthRequired

Property Description

Chapter 2. The Case Study: ITSO Car Rentals 33

Page 50: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Local DB2eThe application always uses a local DB2e database for storing and querying data. If the database directory does not exist, it is created. Sample customer and contract information, along with their pictures would normally be obtained with a sync with the server side database, but for demonstration purpose they can be inserted from the client locally, using buttons on the application’s config panel. For this function to work, photos named Image1.jpg through Image7.jpg must be available at runtime on the client device in a sub directory called demo-images.

See Appendix D, “Additional materials and how to obtain them” on page 403 for informantion about how to get sample image files from IBM. These photos are inserted into the local database using a button on the config panel.

The photos are displayed in the application as (scaled) 75 pixel x 75 pixel images and must be less than 10000 bytes, because that is the size allotted for their storage in the table.

The properties file and the demonstration images can be included in a platform build using the following steps:

1. Open the Platform Build project in your workspace.

2. Navigate down to the custom\files subdirectory.

3. Right-click the files folder and select import from the pop-up menu.

4. Select File System, then click Next.

5. Browse to the directory that contains the files you would like to include.

6. Select the files and or directories, click Finish.

7. Repeat as necessary to add all the files and directories you would like to include.

When running in the WebSphere Studio development environment, the image files must be located in a subdirectory off the default directory, such as:

C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\demo-images

DB2e SyncIn stand-alone mode, the sync step is skipped.

To sync with a real server, a DB2e server must be configured and running. The steps to configure and start a DB2e server are covered in Chapter 10, “DB2e synchronization” on page 271.

Use the config panel to set the host and port of the sync server. The user ID and password from the login panel are used during sync.

34 WCTME: Application Development and Case Study

Page 51: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

MQe messagingIn stand-alone mode the messages are faked.

To send and receive messages with a real MQe message, a server-side implementation must be created and running. The steps to create and start a MQe server are described in Chapter 5, “Messaging” on page 109.

Use the config panel to set the host and port of the MQe server, and the unique name of the local device queue name.

Web servicesThe application always uses a local Web service to manage flight information. The local Web service client bundle is used to query this local Web service and to format the information for displaying in the application.

In stand-alone mode, a server for flight status is not available. In this case, the local Web service will conjure up flight status data.

To use a real Web service, it must be running when the client side stub is created, at development time. This stub is then used at runtime to query flight information from the server side web service.

Appendix C, “Sample server-side Web Service” on page 375 describes the creating and running of a server-side Web service.

Use the config panel to set the Web services host and port.

Device ManagementIn stand-alone mode a device management update is simulated for demonstration purposes. To perform a real device update you can set up a WebSphere Everyplace Server as described in Chapter 11, “Device management” on page 317. Other alternatives are using the Tivoli® Device Manager or WebSphere Everyplace Device Manager (WEDM).

Use the config panel to set the host address string for the Device Manager server.

2.3 Running the sample application with live servers

DB2 and DB2e synchronizationWhen the client application is running on the device, local DB2e tables provide all the persistent storage needs for the application. Communication with the

Chapter 2. The Case Study: ITSO Car Rentals 35

Page 52: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

DB2e sync server is only done when the application's Sync button is selected. The sync server must be running.

Only a small subset of the information the server contains should be synced down to the device. Ideally this would be only the customers and contracts for today at your location. The application would only display customers who:

� Expect to arrive in the near future � Should have arrived in the resent past

For example, if our small rental company database server had 100,000 pending contracts all over the country for 65,000 customers, you would not expect to sync all of that all the time. Filters on the server would sync only the content appropriate for the device client. For example:

� Sync only the contracts for your airport location and for today. This could be, 125 records, for example.

� Sync only the customers for those contracts, 125 unless someone has multiple reservations. Because each customer’s photo is 10,000 bytes or less, the first sync of the day would take longer than a sync that updates status only.

� The application would filter that data down even more by displaying only customers arriving within the next hour (10) and those that should have arrived in the last two hours(20).

Note: The application does indicate known flight delays, but does not take any further action on that information.

Since this application is just a demonstration, we do not handle every real use-case. For the purposes of our simple sample application, we do not include airport, date or time in our database tables. This makes the demonstration repeatable with out any unnecessary complications.

See Figure 2-4 on page 27 for how to configure the database server settings that the client uses.

MQe ServerWhen showing this example application, the MQe server does not need to be running because the message will be queued. MQe messages are only queued up to be sent to the server when a customer is marked as arrived, but real-time responses with updated vehicle location information will happen only if the MQe server is up and functioning.

There can be a short delay in the delivery of MQe messages, so it will be necessary to refresh the screen once the message arrives.

36 WCTME: Application Development and Case Study

Page 53: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

See Figure 2-4 on page 27 for how to configure the MQe server settings that the client uses.

Web servicesBecause the flight information for any pending customers is queried and displayed every time the application screen refreshes, the local Web services must respond quickly to each individual request. It is unrealistic to expect each and every flight information status request to travel all the way to the server and back. To better manage our scenario, the local Web service queries the database directly for all the pending customer's flight info and periodically (configurable) wraps them up into a single, remote request of the real server side Web service.

Because flight information is not updated very often and we can ask the server for the flight information for all the pending customers at once, it makes sense to only refresh a local cache of flight information status in the background, then have the local web service read only from that cache. If the server-side Web service goes down or communication fails, the cache is flushed, because the information will quickly become old information. For that reason, it is also not stored in a local DB2e database table.

For example, 10 customers are arriving in the next hour and 20 are already expected in baggage claim, delayed flights, and so forth. The application can be refreshed several times while the bus driver travels from the airport back to the rentals lot, looking for MQe responses. Thirty requests per screen refresh go to the local Web service and to be instantly resolved. In the background, the local Web service thread periodically requests all 30 flights’ status at once and puts the latest updated information into the cache that the local Web service uses.

See Figure 2-4 on page 27 for how to configure the Web services server settings that the client uses.

Exercise for the adventurousIn this demonstration application, even the server-side Web service makes up the flight status that the client receives. Because we ask for all pending customers’ flights with repeats, it is possible that the application could display the same flight with different, fake statuses. For example, of those 30 pending customers, several could be arriving on the same flight. Change to background thread to only ask the server-side Web server once for each unique flight, instead of for all flights, with repeats.

Device Management ServerWhen updating the client application using device management services, all the client device needs to do is call the agent and it does all the work.

Chapter 2. The Case Study: ITSO Car Rentals 37

Page 54: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

The actual updates are defined on the server and applied to the client devices based on the server side definitions.

See Figure 2-4 on page 27 for how to configure the DMS server settings that the client uses.

2.3.1 Using the demonstration application with multiple devicesHere we answer some questions about using multiple devices:

� Why does the second device not see the status changes from first device?

If multiple devices on multiple buses are used, the drivers on the other buses will not see status changes made with your device, unless they regularly perform syncs. Keep in mind the time delay of syncs and mirror databases being updated with the real databases.

� Why doesn't the second device receive MQe messages regarding the location of customers’ vehicles?

Assuming multiple syncs are performed, other devices running the application will show customers who have arrived on other buses. The application is not designed to send MQe message to devices other than the requesting device. As a result, the second device will not receive the MQe messages from the server with the location of the customer's vehicle. It will continue to show a "?" for the location, until that customer is marked as "exited" and the data is sync again.

Exercise for the adventurousAdd a bus arrived status column to the database table and then update the application logic to only display arrived customers on your bus. The application will have to be synced more often for this data to be available to other client applications running against the same database.

2.4 Building the sample applicationTo implement our design for the ITSO Rentals sample application, we will create several custom application bundles.

Each bundle will encapsulate some of the functionality (and technology) behind the sample application. Separately each bundle will expose an interface or service that can be used by another bundle. A test bundle will be created to test each bundle (or combination of bundles) as we assemble the desired functionality. Together all the bundles, minus the test bundle, are our completed sample application.

38 WCTME: Application Development and Case Study

Page 55: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 2-8 The sample applications bundles

As shown in Figure 2-8, the sample application illustrated in this redbook has the following components:

1. The customer bundle will define our ITSO Rentals customer, the person who boards the bus, and the contract behind that person's rental reservation. See Chapter 3, “Service Management Framework Runtime” on page 41.

2. A test bundle will also be created in Chapter 3, “Service Management Framework Runtime” on page 41 and then updated in Chapter 4, “Database” on page 83, Chapter 5, “Messaging” on page 109 and Chapter 6, “Web Services” on page 155 to perform some simple testing of the bundles before being combined together with the servlet.

3. The database bundle will hide all the details of DB2e and expose methods for retrieving and updating of locally persisted data. See Chapter 4, “Database” on page 83.

Server Side

Customer Bundle

ITSO RentalsWeb Application

ServletTester Bundle

MQe Bundle

Web Service Client

Bundle

Device Manager Bundle

Local Web Service Bundle

Database Bundle

Database Sync

Web Service Server

Device Manager Server

DB2 Server

MQe Server

Client Side

4

6 2

3 51

7

5

108 9

10

7

Chapter 2. The Case Study: ITSO Car Rentals 39

Page 56: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

4. The messaging bundle will hide all the details of MQe and the sending and receiving of messages. See Chapter 5, “Messaging” on page 109.

5. The flight status information bundles will hide all details of the web services used to gather that information. See Chapter 6, “Web Services” on page 155.

6. The Web application bundle will manage our servlet and its jsp files and call the above bundles to retrieve and update data, send and receive messages and display up to date flight information. See Chapter 7, “HTTP services, servlets and Java server pages” on page 183.

7. The DB2 server and database synchronization will be covered in Chapter 10, “DB2e synchronization” on page 271.

8. Our MQe Server will be covered in Chapter 5, “Messaging” on page 109.

9. A example Web Services server is covered in Appendix C, “Sample server-side Web Service” on page 375.

10.Finally we will add a bundle that will allow a device management agent to request and process any pending updates for our sample application. See Chapter 11, “Device management” on page 317.

Now that you have seen the overall picture of the business overview, design considerations, data flow and technologies used, the following chapters delve into the implementation of each and show how this is all put together.

40 WCTME: Application Development and Case Study

Page 57: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Chapter 3. Service Management Framework Runtime

This chapter provides you with an overview of the Service Management Framework (SMF) Runtime, lists many of the bundles provided by WCTME, shows how to create your first SMF bundles using WebSphere Studio Device Developer. This chapter also discusses how these new bundles interact with the SMF runtime and begin the steps necessary to build the complete sample application in this book.

3

© Copyright IBM Corp. 2005. All rights reserved. 41

Page 58: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3.1 OverviewThe SMF Runtime is IBM’s implementation of the Open Service Gateway initiative (OSGi) Service Platform Release 3 (SPR3). It is a production-ready Java environment for running and managing system and application bundles in a single JVM. The OSGi model, and the SMF implementation provide a framework to manage and share bundles across applications, and more importantly, run multiple applications in a single JVM instance.

Bundles are JAR files that include the program code and classes, plus a manifest file with entries specific to the SMF environment that describe the bundle and its dependencies. The bundle is the program unit whose life cycle is managed by the framework or platform. Bundles can themselves expose further services (augmenting the ones provided by SMF) and Java code that applications (browsers, web service clients, open sockets) and other bundles can access to perform other tasks such as an HTTP server, Web application, DB2e database, MQe messaging, logging, XML parsing and so on.

SMF is documented in the WebSphere Device Developer InfoCenter help system and the PDF files included in the installation of the development environment. See Appendix A, “Installing WCTME V5.7.1” on page 347. In this section, some of the features of the SMF Runtime will be highlighted, but for a more complete understanding of the concepts, management, configuration and to find detailed reference information for SMF, review the online documentation provided with the product Information Center (see 3.2, “Documentation and Web Links” on page 48).

3.1.1 What is OSGi and the OSGi service platform?The following quote is from the OSGi Service Platform specification, release 3 which is found in the file r3.book.pdf in the toolkit product help and also at this Web site:

http://www.osgi.org

The Open Services Gateway Initiative (OSGi) was founded in March 1999. Its mission is to create open specifications for the network delivery of managed services to local networks and devices. The OSGi organization is the leading standard for next-generation Internet services to homes, cars, small offices, and other environments.

The OSGi service platform specification delivers an open, common architecture for service providers, developers, software vendors, gateway operators and equipment vendors to develop, deploy and manage services in a coordinated fashion. It enables an entirely new category of smart devices due to its flexible

42 WCTME: Application Development and Case Study

Page 59: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

and managed deployment of services. The primary targets for the OSGi specifications are set top boxes, service gateways, cable modems, consumer electronics, PCs, industrial computers, cars and more. These devices that implement the OSGi specifications will enable service providers like telcos, cable operators, utilities, and others to deliver differentiated and valuable services over their networks.

The OSGi specification enables the separation of the service interface from the service implementation, allowing scalability and extensibility. The SMF framework uses the information in the bundle manifests to populate its service registry and to manage and resolve bundle dependencies. Each bundle has it’s own class loader and name space, and the references between bundles, to access each others services, is managed by the framework.

There are tools designed specifically for bundle creation and management. Many are wizard-based, to allow you to easily create the required classes, methods and other template code for your packages, whereupon you then write the core logic to those services. WebSphere Device Developer is extended by a number of tools including the Bundle Development Kit and the other Extension Services tools. There is also a reference platform for the tooling that includes a bundle server for testing your code without the need for a production level server.

In sum, the OSGi platform is designed to enable devices of any shape and size to execute a consistent, modular program model, on a well-architected set of frameworks and core services. This framework provides services and bundle life cycle management to enable dynamic loading, starting and stopping, and more importantly, bundle and service sharing in the VM instance that is running the SMF platform.

3.1.2 What is SMF?The Service Management Framework (SMF) Runtime is IBM’s implementation of the OSGi Service Platform.

SMF is a Java application, running in a JVM. In essence, SMF is the host environment in which the bundles execute. It manages the life cycle of bundles (installing, starting, stopping, updating and uninstalling) and through the bundle manifest, the dependencies of bundles on one another. These bundles can represent several separate applications or portions of applications, all running in the same JVM.

Core and custom bundlesCore bundles provide the basic functionality of the platform. More simply, system bundles are the SMF platform itself, and custom bundles are the ones you and

Chapter 3. Service Management Framework Runtime 43

Page 60: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

other developers create to extend the framework and to form applications to perform other useful problem solving tasks.

Custom bundles can be created to expose new interfaces or Java packages and new services. For our sample application and case study, we created several custom bundles. Applications are constructed by using these services and interfaces. Each of these bundles can be managed separately, each having their own life cycle. Bundles can be installed into the framework; started, stopped, and updated independently of each other.

Bundles can implement an interface, BundleActivator, that allows the bundle to be started and stopped cleanly by the framework. During the start and stop calls, the bundle activator logic is called to manage the bundle, which can include the registering or un-registering of a service, starting and stopping threads, and allocation and de-allocation of resources.

Bundles must include a manifest file that includes information used by the framework to install and activate the bundle and determine dependencies between bundles. Import dependencies and export definitions of packages and services are described in the manifest file.

Running the frameworkYou can run the SMF Runtime inside the WebSphere Device Developer workspace (see the SMF Bundle Developer Tools documentation) and from a command line.

Consult the following sections of the SMF Runtime documentation in Table 3-1 for detailed information concerning the execution of the SMF runtime:

Table 3-1 SMF Runtime documentation

Tip: See the SMF Bundle Developer Tools documentation and the SMF Bundle Server documentation, especially the Documentation and Web Links, for more information about development, life cycle and bundle management.

smf.properties Service Management Framework� SMF Runtime User’s Guide� Getting Started� Getting Started with the SMF Runtime� Using the smf.properties file

44 WCTME: Application Development and Case Study

Page 61: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

command line arguments:

� -ide[:port]� -con[sole][:port]� -r[esourceManagement]� -platform[:platform-name][platform-ar

gs]

Service Management Framework� SMF Runtime User’s Guide� Getting Started� Getting Started with the SMF Runtime� SMF Runtime launching options� SMF Launcher command line

arguments

console commands:

� launch� close� exit� exit!� gc� init� shutdown� [setp]rop <key>=<value>

� [i]nstall <url> {start}� [un]install (<id>|<location>)+� [sta]rt (<id>|<location>)+� [sto]p (<id>|<location>)+� [r]efresh (<id>|<location>)+� [up]date (<id>|<location>)+

� [b]undle (<id>|<location>)� bundles� [p]rops � [t]hreads� ss� [s]tatus� [se]rvices {filter}� [h]eaders (<id>|<location>)+� [p]ackages

{<pkgname>|<id>|<location>}� [l]og{(<id>|<location>)}

� more� disconnect

� exec <command>� fork <command>

� sl{(<id> | <location>)}� setfwsl <start level>� setbsl <start level> (<id> | <location>)� setibsl <start level>

Service Management Framework� SMF Runtime User’s Guide� Getting Started� Getting Started with the SMF Runtime� SMF Console Commands

Tables contain details on the commands that can be run from the SMF console. These include commands to control SMF, bundles, displaying of status, start level and more.

Chapter 3. Service Management Framework Runtime 45

Page 62: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3.1.3 Core BundlesThe following are Core OSGi bundles included in SMF:

� System Bundle� HTTP Service� Log Service� Device Access� Preferences Service� Configuration Admin Service� User Admin Service� Service Tracker

See the Runtime User’s Guide documentation for more information about these bundles, their dependencies and interfaces.

Also see 8.3, “Including system services in your project” on page 231.

3.1.4 SMF Specific BundlesThe following are SMF specific bundles included with IBM’s implementation:

� Language bundles� Web Container� Web Application� Web HTTP Service� Meta Type Service� SMFAdmin� FileAdmin� XML parser APIs� Micro XML� XML4J� DependencyAdmin� RemoteVmAdminAgent� SessionService� CDSBundleSupport

See the Runtime User’s Guide documentation for more information about these bundles, their dependencies and interfaces.

Also see 8.3, “Including system services in your project” on page 231.

3.1.5 Bundles provided by Extension ServicesThe following bundles are included within Extension Services:

46 WCTME: Application Development and Case Study

Page 63: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

� Cloudscape� Cloudscape ISync Client� DB2 Everyplace � DB2 Everyplace ISync Client� WebSphere MQ Everyplace� WebSphere Everyplace using JMS� WebSphere MQ Telemetry Transport� Web Services using generated Stub Classes� Web Services using Proxy services

See the Runtime User’s Guide and Extension Services Development Guide documentation for more information about these bundles, their dependencies and interfaces.

Also see 8.3, “Including system services in your project” on page 231.

3.1.6 Bundles created in this bookThe following bundles are created in the exercises in this book. Together they make up the sample application.

� FlightInfoWebServiceBundle is a local Web Service that accesses a remote Web Service. See Chapter 6, “Web Services” on page 155.

� FlightInfoWebServiceClientBundle is a Web Service client that accesses the local Web Service. See 6.5, “Creating the FlightInfoWebServiceClient Bundle” on page 173.

� ITSOCustomerBundle is a simple Java structure. See 3.3, “Example exercise” on page 49.

� ITSORentalsDatabaseServiceBundle accesses a local OSGi agent. See Chapter 11, “Device management” on page 317.

� ITSORentalsDeviceManagementServiceBundle accesses our local database tables. See Chapter 4, “Database” on page 83.

� ITSORentalsMQeServiceBundle sends and receives MQe messages. See Chapter 5, “Messaging” on page 109.

� ITSORentalsTesterBundle performs a simple test of the other bundles. See 3.3.3, “Creating a tester bundle” on page 63.

� ITSORentalsWebApplicationBundle is our Web application that uses all the other bundles. See Chapter 7, “HTTP services, servlets and Java server pages” on page 183.

Chapter 3. Service Management Framework Runtime 47

Page 64: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3.2 Documentation and Web LinksFor more information about SMF, see

� Online references:

http://www.ibm.com/software/wireless/smf/http://www.osgi.org

Once installed (see Appendix A, “Installing WCTME V5.7.1” on page 347 for instructions on how to install WebSphere Device Developer and WCTME. WebSphere Device Developer Help includes the following references:

� SMF Runtime Javadoc

� Service Management Framework

– Runtime User’s Guide– Server User’s Guide– Bundle Developer Tools User’s Guide

Note that the PDF files for these three sections are also included.

� Extension Services Developer’s Guide

See Figure 3-1 on page 49.

48 WCTME: Application Development and Case Study

Page 65: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 3-1 SMF Help available in WebSphere Studio

3.3 Example exerciseAs stated in Chapter 2, “The Case Study: ITSO Car Rentals” on page 17, the sample application is created a bundle at a time in the relevant chapters. The first part of the sample application is a simple bundle that exposes a Java class.

Note: The completed exercises in this book can be downloaded from IBM. See the Additional Material section for more information.

Chapter 3. Service Management Framework Runtime 49

Page 66: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3.3.1 DescriptionIn this section we will create a simple bundle that contains the Customer class for our sample application.

This bundle will be used by other bundles in the application, so it will expose the Java class we will create.

We will also create another bundle to test the customer bundle.

The Customer ClassFor our sample application, our Customer only has a few fields. These fields in Example 3-1 will later map to database tables in Chapter 4, “Database” on page 83.

Example 3-1 Customer class fields

String contractID = ""; String customerID = "";String firstName = ""; String lastName = ""; String flightInfo = "";String currentStatus = "";String vehicleLocation = "";

3.3.2 ProcedureIn each chapter where we develop a portion of the sample application we will include the steps necessary to create that bundle.

The completed bundles are available for download from IBM if you do not want to complete the steps manually. See the Additional Material section for more information.

Each chapter does build on the previous chapter, and some screen shots are not duplicated in future chapters, so it might be necessary to look to previous chapters for complete examples of each step.

First we need to create a Bundle Project to hold the Customer class.

1. If WebSphere Studio Site Developer is not running, click Start → Programs → IBM WebSphere Studio → Site Developer 5.1.x.

2. Open the SMF Perspective. Select Window → Open Perspective → SMF. See Figure 3-2 on page 51.

50 WCTME: Application Development and Case Study

Page 67: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 3-2 The SMF Perspective

3. Make sure you are on the Package Explorer tab. Select File → New → Other.

4. Select Extension Services → Extension Services Bundle Project and Click Next. See Figure 3-3 on page 52.

Chapter 3. Service Management Framework Runtime 51

Page 68: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 3-3 Creating a new Bundle

5. Enter the Project name ITSOCustomerBundle and click Next. See Figure 3-4 on page 53.

52 WCTME: Application Development and Case Study

Page 69: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 3-4 Selecting platform profile and application services

Chapter 3. Service Management Framework Runtime 53

Page 70: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

6. In the Platform Profile field choose Extension Services: jclFoundation (5.7.0.).

7. For this bundle we will not be using any additional application services. Click Next.

8. In later bundles we will reference this project. Click Next.

9. Because this is a very simple bundle, we will not need a Bundle Activator, so leave that field empty. The other choices on the panel control whether Studio should manage some other settings for you. See the help documentation for more information. Click Finish.

10.If you see a panel indicating the folder has changed (Figure 3-5), click Yes.

Figure 3-5 Build Path Warning

You have just created an empty Bundle. Now we will add the Customer Java class.

11.See Figure 3-6 on page 55. From the Package Explorer tab of the SMF Perspective, select the ITSOCustomerBundle Project you just created and right-click. From the pop-up menu select New → Package.

54 WCTME: Application Development and Case Study

Page 71: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 3-6 Adding a package to the project

12.Enter the package name com.itso.rentals and click Finish. See Figure 3-7 on page 56.

Chapter 3. Service Management Framework Runtime 55

Page 72: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 3-7 Naming the new package

13.Select the package just created, right-click. From the pop-up, menu select New → Class.

56 WCTME: Application Development and Case Study

Page 73: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 3-8 Naming the new class

14.As in Figure 3-8, enter the name Customer, check the box next to Constructors from superclass and click Finish.

15.Into the Customer.java window that opens, copy the following in Example 3-2:

Example 3-2 Customer information

public final static String PENDING = "pending";public final static String ARRIVED = "arrived";public final static String EXITED = "exited";

protected String contractID = ""; protected String customerID = "";protected String firstName = ""; protected String lastName = ""; protected String flightInfo = "";

Chapter 3. Service Management Framework Runtime 57

Page 74: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

protected String currentStatus = "";protected String vehicleLocation = "";

16.Select the contractID field name, right-click, from the menu select Source → Generate Getter and Setter.... See Figure 3-9.

Figure 3-9 Generating methods

17.As in Figure 3-10 on page 59, check the box next to each of the protected fields and click OK.

58 WCTME: Application Development and Case Study

Page 75: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 3-10 Select the fields that you want getter and setter methods generated

18.For testing purposes, add the following code in Example 3-3 to the class:

Example 3-3 Sample code for the Customer Class

public Customer(String contract, String id, String first, String last, String flight, String status, String slot) {

super();contractID = contract;customerID = id;firstName = first;lastName = last;flightInfo = flight;currentStatus = status;vehicleLocation = slot;

}

public String toString() {StringBuffer sb = new StringBuffer();sb.append("Customer ");sb.append(getFirstName());sb.append(" ");

Chapter 3. Service Management Framework Runtime 59

Page 76: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

sb.append(getLastName());sb.append(" with customer ID ");sb.append(getCustomerID());sb.append(" and with contract ID ");sb.append(getContractID());sb.append(" is ");sb.append(getCurrentStatus());sb.append(" and will arrive on ");sb.append(getFlightInfo());sb.append(" and his vehicle is in slot ");sb.append(getVehicleLocation());return sb.toString();

}

19.Save the file.

You have completed creating the Customer Bundle. However, it does not share its information with anyone. We will do this next.

20.From the Package Explorer tab of the SMF Perspective, select the ITSOCustomerBundle Project you created and expand it down to the file META-INF/MANIFEST.MF. Double-click the file name MANIFEST.MF. See Figure 3-11 on page 61.

60 WCTME: Application Development and Case Study

Page 77: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 3-11 The manifest file editor

21.This opens the MANIFEST.MF editor. Scroll down to Export Packages.

Chapter 3. Service Management Framework Runtime 61

Page 78: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 3-12 Adding Exports

22.As in Figure 3-12, expand the section Export Packages and select Add...

62 WCTME: Application Development and Case Study

Page 79: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 3-13 Selecting the package to export

23.As in Figure 3-13, select the package com.itso.rentals and click OK.

24.Save the file.

The package will be exposed by this bundle and can now be used by other bundles.

3.3.3 Creating a tester bundleWe have created our Customer bundle, but we have nothing to use it. If we create another bundle we can test what we have so far.

In this section we will create another bundle that tests the Customer bundle using the exposed Java package and class methods.

Repeat the steps in 3.3.2, “Procedure” on page 50 to create a test bundle. Use the values in Table 3-2 on page 64 when creating the new bundle’s name, Java package name, and Java class name.

Chapter 3. Service Management Framework Runtime 63

Page 80: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Table 3-2 Tester bundle values

1. In step 8 on page 54, click the Projects tab and select the ITSOCustomerBundle check box. See Figure 3-14.

Figure 3-14 Adding the Customer bundle to the Tester bundle’s project path

2. In step 9 on page 54, select the check box next to Create Default Bundle Activator and then click Finish. See Figure 3-15 on page 65.

Input Value

Bundle Project Name ITSORentalsTesterBundle

package name com.itso.rentals.test

class name ITSORentalsTester

Note: While we use the steps from 3.3.2, “Procedure” on page 50, make the following changes to some of the steps to create your tester bundle.

64 WCTME: Application Development and Case Study

Page 81: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 3-15 Creating the default BundleActivator

3. In step 15 on page 57, add the following code in Example 3-4 to the ITSORentalsTester class:

Example 3-4 Tester bundle code

private BundleContext context;

public ITSORentalsTester(BundleContext context) {super();System.out.println("\nBundleTester V1.0");this.context = context;init();

}

private void init() {

//short delay to let things settle, since we are starting up the test immediately

try {Thread.sleep(5000);

} catch (InterruptedException e) {}

Chapter 3. Service Management Framework Runtime 65

Page 82: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

//basic test of customer bundleSystem.out.println("\nTesting Customer Bundle: creating a customer and

calling toString");Customer c = new Customer("1", "374906", "Jeff", "Martin", "AA 174",

Customer.PENDING,"?");System.out.println(c);// see toString()

}

4. Perform these extra steps for this project:

a. Open the MANIFEST.MF file (as in step 20 on page 60). Scroll down to Import Packages.

b. Expand the section Import Packages and select Add...

c. Select the package com.itso.rentals and click OK.

This step creates a dependency between the test bundle and the customer bundle.

d. Save the file.

e. Open the ExtensionServicesBundleActivator.java file (in the default package) and add the following code at the end of the start() method:

System.out.println("Starting Bundle Tester");ITSORentalsTester bt = new ITSORentalsTester(context);

f. Organize Imports and Save the file.

You should now be able to test the ITSOCustomerBundle with the ITSORentalsTesterBundle. We are only doing a simple test of one bundle accessing another bundle. We will build on this in the next few chapters.

Tip: To help remove unresolved compiler errors, right-click in the source and select Source → Organize Imports.

Note: The package com.itso.rentals might already have been added automatically, or you can press the Compute button to fill in the list.

Note: It generally is not a good idea to include a large amount of code in the start() method. If you have a lot of work to do to set up a service, then create a separate thread to process that work.

66 WCTME: Application Development and Case Study

Page 83: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3.3.4 Customer Bundle creation reviewBefore you use the bundles you just created, we will step back and review what we have accomplished and then explain how these bundles are used.

We used the tools to create an Extension Service Bundle Project with a simple bundle, containing a single Java class, the Customer. We then modified that bundle’s manifest file to export the Java package containing the Customer class, so that another bundles could access it.

Next we created a second bundle. When we created that bundle’s project we added the first project to the seconds project’s build path. See Figure 3-14 on page 64. This is done so that the referenced class can be resolved during development time. Then we modified the second bundle’s manifest file to import the first bundles exported package. This creates a dependency between the classes, that is used a runtime. Later when we install the second bundle into the runtime, the first bundle will be pulled along, installed, resolved during runtime execution.

In later chapters we will create projects and bundles that expose services as well as code. In those cases we will also modified bundle manifest files to list the imports and exports of these services.

Getting our test bundle to execute requires a couple more steps. These steps involve submitting the bundle to an SMF bundle server and then installing the bundle into an SMF runtime. When the SMF runtime itself is started, any bundles that are there (from previous runs) are also started. When you then install new bundles into the SMF runtime, those new bundles are then also started. For example, bundles that implement the BundleActivator interface, like or tester bundle, have the start() method called.

The next section takes you through the steps of starting the SMF bundle server, submitting the bundles into the bundle server, starting the SMF runtime, and then installing them into the runtime. You might want to peek ahead and review the referenced sections covering those steps, before you run the steps.

3.3.5 Testing the Customer BundleTo test the Customer Bundle, perform the following steps:

1. Start the SMF bundle server. For help see section 3.4, “Starting the SMF Bundle Server” on page 70.

2. Submit the ITSOCustomerBundle and the ITSORentalsTesterBundle to the bundle server. For help see section 3.8, “Submitting bundles to the SMF bundle server” on page 77.

Chapter 3. Service Management Framework Runtime 67

Page 84: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3. Start the SMF runtime. For help see section 3.5, “Starting the SMF Runtime” on page 73.

4. In the Package Explorer pane, select the SMF Bundle Servers tab. Under the Admin@localhost:8080/smf, expand the Bundles tree.

5. Right-click ITSORentalsTesterBundle, and select Install.

The test bundle and any bundles it requires, in this case the ITSOCustomerBundle, will be installed into the runtime and the bundles will be started. The output of the test bundle will display in the SMF runtime’s console.

3.3.6 TroubleshootingTo run the test bundle again, perform the following steps:

1. Select it in the runtime and right-click. 2. Select Stop from the pop-up menu. 3. Repeat the process, selecting Start.

If you accidentally skip the bundle activator step, you can create a new class or modify an existing class to implement the interface and use the manifest editor (see Figure 3-11 on page 61) to point to that class.

If you want to rename a bundle, package, class, and so on, you can do this by selecting the object you want to rename, right-clicking and selecting the Refactor → Rename feature of Studio.

Be sure to repeat the steps of submitting to the bundle server and installing to the runtime every time you modify the code, manifest file or content of a bundle.

Before submitting and installing a bundle, make sure all errors have been resolved.

When updating a bundle in the runtime, if you have not incremented the version number using the manifest editor the runtime will ignore the change. It does not see this as an update. You can either increment the version number, or uninstall the old bundle from the runtime, then install the new bundle in to the runtime.

If you want to debug into a bundle, start the runtime in debug mode. Make sure the Java class file with the break points is unique in the runtime, because the first class with that file class name is the one the debugger will find.

If you edit and save any bundle code while debugging, the code will not be reflected in the runtime until it is submitted and installed. The sample application bundles, especially those created in the next few chapters, do not use the ServiceTracker interface which allows bundles to notice when other bundles and their services are stopped, update and restarted. For this reason, make sure to

68 WCTME: Application Development and Case Study

Page 85: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

stop all the sample application’s bundles and restart all of them when you are making updates. See the Samples section in the Extension Services Developer’s Guide and example projects in the Studio workbench for other examples of coding and bundle development.

Chapter 3. Service Management Framework Runtime 69

Page 86: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

If you get an error at runtime that states a missing or unresolved Java class, check that the manifest file for your bundles, then import and export any necessary packages or services.

If you cannot resolve all the classes at development time, check that you have added all the necessary projects to the current project’s build path.

Some Studio operations will prompt you to save any open files before continuing.

3.4 Starting the SMF Bundle ServerTo create a new launch configuration for the SMF Bundle Server use the following steps:

1. From the WebSphere Application Developer menu select Run and then Run... See Figure 3-16.

Figure 3-16 Run, then Run...

70 WCTME: Application Development and Case Study

Page 87: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

2. Select the SMF Bundle Server from the Configurations list, then click New. The user ID and password are both Admin by default. See Figure 3-17 on page 71.

Figure 3-17 Creating a new SMF Bundle Server launch configuration

3. Click Run. See Figure 3-18 on page 72.

Chapter 3. Service Management Framework Runtime 71

Page 88: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 3-18 Starting the new SMF Bundle Server

The console will display messages as it starts.

Once the SMF Bundle Server has been created, you can start it again later using the Run, Run... menu, or with the shortcut in Figure 3-19 on page 73.

Note: You might receive a message concerning your current preference settings and the focus changing to the Console View automatically everytime the bundle server has output. You can adjust this setting or ignore it.

72 WCTME: Application Development and Case Study

Page 89: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 3-19 Restarting the SMF Bundle Server from shortcut

3.5 Starting the SMF RuntimeTo create a new launch configuration for the SMF Runtime in WebSphere Studio Application Developer, use the following steps:

1. From the menu select Run and then Run...

2. Select the SMF Runtime from the Configurations list, then click New. See Figure 3-20 on page 74.

Chapter 3. Service Management Framework Runtime 73

Page 90: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 3-20 Creating a new SMF Runtime launch configuration

3. Change the user ID and password to Admin. This is the default user ID and password for the Bundle Server. Click Run.

The console will display messages as it starts.

Once the SMF Runtime has been created, you can start it again later using the Run, Run... menu, or with the shortcut.

74 WCTME: Application Development and Case Study

Page 91: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3.6 Stopping the SMF Bundle ServerTo stop the WebSphere Studio Application Developer SMF Bundle Server, use the following steps.

1. Switch to the SMF Perspective. If it is not available, select Window → Open Perspective → SMF.

2. From the SMF Bundle Server Tab, select the running bundle server Admin@localhost:8080/smf and right-click. From the pop-up menu select Stop, as in Figure 3-21.

Figure 3-21 Stopping the SMF Bundle Server running in WebSphere Studio Site Developer

The bundle server should stop.

Chapter 3. Service Management Framework Runtime 75

Page 92: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3.7 Stopping the SMF RuntimeTo stop the WebSphere Studio Application Developer SMF Runtime, use the following steps.

1. Switch to the SMF Perspective. If it is not available, select Window → Open Perspective → SMF.

2. From the SMF Runtime View, click the small downward pointing triangle next to the title of the view. From the pop-up menu select Terminate runtime, as in Figure 3-22.

Figure 3-22 Stopping the SMF Runtime in WebSphere Studio Site Developer

The SMF runtime should stop.

76 WCTME: Application Development and Case Study

Page 93: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3.8 Submitting bundles to the SMF bundle serverAs you create and debug bundles, you must submit them to the bundle server before they can be installed into the runtime. Use these steps to submit bundles to the bundle server:

1. Make sure the bundle server is running as in 3.4, “Starting the SMF Bundle Server” on page 70.

2. From the SMF Perspective, Package Explorer view, select the bundle projects you want to submit. Right-click and select SMF →Submit Bundle...

Figure 3-23 Submitting bundles to the bundle server

3. Check the box next to Submit Jar, select the Admin@localhost:8080/smf and check Replace Bundles box, then click Finish. See Figure 3-24 on page 78.

Chapter 3. Service Management Framework Runtime 77

Page 94: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 3-24 Submitting a bundle to the local bundle server

The bundles are deployed to bundle server or directory selected.

Note: This screen can also be used to add a directory to the Export Targets list. Bundles can be deployed to directories when performing a Platform Build.

78 WCTME: Application Development and Case Study

Page 95: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3.9 Installing bundles into the SMF RuntimeOnce bundles are submitted to the bundle server, they can be installed into the runtime. Any dependencies on other bundles will cause them to be installed, if necessary.

Use these steps to install bundles to the runtime:

1. Make sure the bundle server is running.

2. From the SMF Perspective, Bundle Server view, select the bundle projects you want to submit. Right-click and select Install, as in Figure 3-25.

Figure 3-25 Installing bundles to the SMF Runtime in WebSphere Studio Site Developer

The bundles are installed into the runtime and started. Any output to System.out will show in the runtimes console. You can also see exceptions from the sample application in the console.

Chapter 3. Service Management Framework Runtime 79

Page 96: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

The icons in the runtime indicate if a bundle is started, stopped, or had an exception during startup. You can also right-click the bundle name to Show Exception if an exception occurs during startup.

3.10 Removing bundles from the SMF bundle serverTo remove bundles from the bundle server use these steps:

1. Make sure the bundle server is running.

2. From the SMF Perspective, Bundle Server view, select the bundles you want to remove. Right-click and select Remove All Versions, as in Figure 3-26.

Figure 3-26 Removing bundles from the SMF Bundle Server

The bundles are removed.

80 WCTME: Application Development and Case Study

Page 97: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3.11 Uninstalling bundles from the SMF RuntimeTo remove bundles from the runtime use these steps:

1. Make sure the runtime is running.

2. From the SMF Runtime view, select the bundles you want to uninstall. Right-click and select Uninstall, as in Figure 3-27.

Figure 3-27 Uninstalling bundles from the SMF Runtime

The bundles will be stopped and uninstalled from the runtime.

Important: There is only one bundle server and one runtime in the development system. If you create multiple workspaces, each bundle server and runtime will point to the same content.

Chapter 3. Service Management Framework Runtime 81

Page 98: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

82 WCTME: Application Development and Case Study

Page 99: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Chapter 4. Database

In an information world, record keeping is a cornerstone to doing business. All kinds of information become more useful and organized when saved in database tables.

Pervasive devices are no exception and relational database solutions are key to many customer solutions.

This chapter describes the device database support technology of WCTME.

4

© Copyright IBM Corp. 2005. All rights reserved. 83

Page 100: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

4.1 Database support overviewWCTME includes the following bundles for database support

� DB2EveryplaceClient� DB2EveryplaceClientSync� IBM Cloudscape 5.1� IBMCloudscapeSyncClient

DB2 Everyplace and Cloudscape are relational database implementations for the device environment.

Used locally, these databases can be used to store information that can be sorted, updated, queried, and deleted using SQL commands.

Combined with a host-side sync server, you can synchronize enterprise data with the client device, making that data available locally in a disconnected environment.

Both DB2e and Cloudscape are zero-administration systems, meaning they require no database administration on the client.

The sample application database bundle created in this chapter includes the following database access examples:

� Selecting a rental customer using a contract ID, using two simple SELECT statements, one on each table

� Selecting a sorted list of customers based on their state

Create a SELECT statement that joins the two tables and uses ORDER BY to sort the results.

� Updating a rental contract’s state, a simple UPDATE statement

� Updating a rental contract’s vehicle location, another simple UPDATE

� Selecting a picture (Blob) from the customer table, a SELECT used with a getBlob() method.

Note: Bundle activators for these bundles perform the Class.forName(“driver_name”) step, so it is not required in your application.

Note: If the local DB2e database tables exist prior to a sync, as in our sample application in demonstration mode, the local database tables and content will be lost and replaced with the server-side content.

84 WCTME: Application Development and Case Study

Page 101: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

For demo mode we also include:

� Dropping and creating database tables using DROP TABLE and CREATE TABLE statements

� Inserting sample data into the local tables using INSERT statements.

� Resetting all the contract states and vehicle locations by using UPDATE for an entire column of a table.

� Inserting a picture (Blob) into the customer table, using an UPDATE used with a setBytes() method.

4.1.1 DB2 Everyplace Client The DB2 Everyplace Client bundle is a complete implementation of DB2 Everyplace, which is IBM’s mobile version of DB2 Universal Database™.

DB2e is a small, high performance, reliable, native relational database that resides on the user’s device, providing access and update capabilities to local data.

4.1.2 DB2 Everyplace ISync ClientThe DB2 Everyplace ISync Client bundle is an implementation of the synchronization logic necessary to sync locally stored information in database tables with the host-based enterprise data.

Filters and subscription limit the amount of data synced with the server to include only the subset required by the user.

See Chapter 10, “DB2e synchronization” on page 271 for more information about synchronizing databases with a host server.

4.1.3 IBM Cloudscape Client The IBM Cloudscape Client bundle is a 100% Java implementation of a relational database system. Because it is written in Java, no native files are required.

4.1.4 IBM Cloudscape ISync ClientThe IBM Cloudscape ISync Client bundle is an Java based implementation of synchronization logic necessary to sync locally stored information in database tables with the host-based enterprise data.

Chapter 4. Database 85

Page 102: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

4.2 DB2 Everyplace versus CloudscapeDB2 Everyplace and Cloudscape are similar, but each has features that might make one a better choice for particular client needs. See Table 4-1.

Table 4-1 Comparing DB2e with Cloudscape

This is not an exhaustive comparison of the two products. See production documentation for a more compete information about each product.

4.3 Documentation and Web LinksInformation about database access and configuration are available both online and in WebSphere Studio’s Help.

4.3.1 DB2eFor more information about DB2e, see the following online references:

http://www.ibm.com/software/data/db2/everyplace/everyplacedb.htmlhttp://www.ibm.com/software/data/db2/everyplace/syncserver.html

DB2e Cloudscape

implementation High performance native implementation (see documentation for a complete list of supported devices)

Java-based, platform-independent implementation

storage requirements 200KB 2MB

connections Allows one connection to a database at a time

Allows multiple connections to a database at a time

supports Limited set of data types Full SQL 92 support

database directory create Directory for database tables must be created prior to use

Cloudscape creates the directory

sample URL jdbc:db2e:(directory) jdbc:db2j:(directory);create=true

Restriction: Cloudscape is not appropriate for a memory-constrained device. Make sure your device is appropriate if choosing Cloudscape for your device implementation.

86 WCTME: Application Development and Case Study

Page 103: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Once installed (see Appendix A, “Installing WCTME V5.7.1” on page 347 for instructions on how to install WebSphere Studio Application Developer and WCTME).

WebSphere Studio Application Developer Help includes the following PDF references as shown in Figure 4-1.

� RDB2 Everyplace documentation:

– Installation and User’s Guide– Application Developers Guide– Sync Server and Administration Guide

Figure 4-1 DB2e Help available in WebSphere Studio

4.3.2 CloudscapeFor more information about Cloudscape, see the following Web site:

http://www.ibm.com/software/data/cloudscape/

4.4 Example database exerciseIn this section, we add database support to the sample application. The sample application uses two local database tables for rental contracts and customer

Chapter 4. Database 87

Page 104: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

information. We need to be able to query the contract status and access the customer records in the database.

In Chapter 10, “DB2e synchronization” on page 271 we address the steps to synchronize the local client database tables with a host-side sync server.

4.4.1 DescriptionIn this section, we create a database service bundle that provides all the access to local storage for our application data. The sample application does not normally create or remove Customers from the database. However, the database does access Customers with their rental contract as a group based on their status, then updates these records individually as Customers arrive and exit.

In later chapters, other bundles access this bundle to update data and to cause a database sync with the DB2e Sync server.

Because we want this application to run in a stand-alone mode, without a server, we will initialize the bundle with properties that include a stand-alone flag. This flag will cause the database bundle to perform a sync with the server or just create local demo data and fake syncing with a server.

Service InterfaceThis is the set of methods we want to implement with this service bundle in Example 4-1:

Example 4-1 Service bundle

boolean init(Properties p);boolean update2Arrived(String contractID);boolean update2Exited(String contractID);boolean updateVechicleLocation(String contractID, String VechicleLocation);Customer getCustomer(String contractID);Vector getPendingCustomers();Vector getArrivedCustomers();InputStream getPicture(String customerID);

String sync(Properties userProps);

public String createLocalData();public boolean insertPictures();boolean resetDemo();

The sync method is implemented in Chapter 10, “DB2e synchronization” on page 271, but the interface is defined here for use later.

88 WCTME: Application Development and Case Study

Page 105: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

For stand-alone demonstrations, we implement a method to insert local pictures into the database and another method to reset the database for the next demo.

4.4.2 Configuring a development system for DB2e and DB2e SyncIn this section, we describe the steps to configure a window development system for DB2e and DB2e Sync.

Before you beginBefore your DB2e application can run in the development environment and find the native DB2e drivers, some configuration is necessary.

1. For local DB2e database access, add the DB2e drivers to your system path. They can be found in the directory:

C:\Program Files\IBM\DeviceDeveloper\wsdd\wsdd5.0\technologies\ese\files\db2e\win32\x86.

2. For DB2e sync, add the DB2e drivers to your system path. They can be found in the directory:

C:\Program Files\IBM\DeviceDeveloper\wsdd\wsdd5.0\technologies\ese\files\db2eisync\win32\x86.

3. On your development system’s desktop, right-click My Computer and select properties.

4. Select the Advanced tab and click the Environment Variables button.

5. Highlight PATH under System Variables and click Edit.

6. Add these directories, separated by a semicolon:

C:\Program Files\IBM\DeviceDeveloper\wsdd5.0\technologies\eswe\files\db2e\win32\x86;C:\Program Files\IBM\DeviceDeveloper\wsdd5.0\technologies\eswe\files\db2eisync\win32\x86

7. Click OK, then click OK again to save and close the properties window.

8. If it is currently running, restart WebSphere Studio so that the change will become effective immediately.

Configuring the bundlesFirst we need to create a Bundle Project to hold the database classes.

1. If WebSphere Studio Site Developer is not running, click Start → Programs → IBM WebSphere Studio → Site Developer 5.1.x.

2. Open the SMF Perspective. Select Window → Open Perspective → SMF.

3. Make sure you are in the Package Explorer tab. Select File → New → Other.

Chapter 4. Database 89

Page 106: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

4. Select Extension Services → Extension Services Bundle Project and Click Next.

5. Enter the Project name ITSORentalsDatabaseServiceBundle and click Next. See Figure 4-2.

Figure 4-2 Selecting the DB2e application services

6. In the Platform Profile field choose Extension Services: jclFoundation (5.7.0.).

7. Select the check boxes next to the application services DB2 Everyplace and DB2 Everyplace ISync Client. Click Next.

90 WCTME: Application Development and Case Study

Page 107: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

8. Click the Projects tab and select the check box next to ITSOCustomerBundle. Click Next.

Figure 4-3 Selecting other projects for this project’s build path

9. Select the check box next to Create Default Bundle Activator. Click Finish.

10.If you see a panel indicating the folder has changed, click Yes.

11.From the Package Explorer tab of the SMF Perspective, select the ITSORentalsDatabaseServiceBundle Project you just created and right-click. From the pop-up menu, select New →Package.

Chapter 4. Database 91

Page 108: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

12.Enter the package name com.itso.rentals.database and click Finish.

13.Select the package just created and right-click. From the pop-up menu select New →Interface.

14.Enter the name ITSORentalsDatabaseService and click Finish.

15.Into the ITSORentalsDatabaseService.java window that opens, copy the following code in Example 4-2:

Example 4-2 ITSORentalsDatabaseService code

boolean init(Properties p);boolean update2Arrived(String contractID);boolean update2Exited(String contractID);boolean updateVechicleLocation(String contractID, String VechicleLocation);Customer getCustomer(String contractID);Vector getPendingCustomers();Vector getArrivedCustomers();InputStream getPicture(String customerID);

String sync(Properties userProps);

public String createLocalData();public boolean insertPictures();boolean resetDemo();

16.Save the file.

17.Select the package just created, right-click. From the pop-up menu select New → Class.

18.In the New Java Class window (Figure 4-4 on page 93), enter the name ITSORentalsDatabaseImpl. In the Interfaces: field, click the Add button. Add the Interface ITSORentalsDatabaseService. Click OK, then click Finish.

Tip: To help remove unresolved compiler errors, right-click in the source and select Source →Organize Imports.

92 WCTME: Application Development and Case Study

Page 109: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 4-4 Creating the class implementing an interface

19.Replace the class methods generated automatically with the code in Example 4-3:

Example 4-3 Class methods

private boolean standAlone = true;private String path = "ITSODatabase";

private Connection con;private Statement st;private ResultSet rs;private String driver = "jdbc:db2e:" + path + File.separator + "rentals";

/** synchronize all access to DB2e */private Object syncLock = new Object();

/* (non-Javadoc) * @see

com.itso.rentals.ITSORentalsDatabaseService#init(java.util.Properties) */public boolean init(Properties p) {

Chapter 4. Database 93

Page 110: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

//allow properties to override defaultsif (p != null) {

String standAloneString = p.getProperty("itso.database.standalone","true");

standAlone = standAloneString.equalsIgnoreCase("true");path = p.getProperty("path", "ITSODatabase");driver = "jdbc:db2e:" + path + File.separator + "rentals";

}

//create directory if it doesn't existFile dbDir = new File(path + File.separator + "rentals");if (!dbDir.exists()) {

if (!dbDir.mkdirs()) {System.out.println("Unable to create directory: " +

dbDir.getAbsolutePath());}

}

return true;}

/* (non-Javadoc) * @see

com.itso.rentals.ITSORentalsDatabaseService#update2Arrived(java.lang.String) */public boolean update2Arrived(String contractID) {

return updateStatus(contractID, Customer.ARRIVED);}

/* (non-Javadoc) * @see

com.itso.rentals.ITSORentalsDatabaseService#update2Exited(java.lang.String) */public boolean update2Exited(String contractID) {

return updateStatus(contractID, Customer.EXITED);}

/** * Update this contract to the status provided * @param contractID * @param status * @return */private boolean updateStatus(String contractID, String status) {

boolean results = false;

//only allow one thread to access DB2esynchronized (syncLock) {

94 WCTME: Application Development and Case Study

Page 111: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

try {con = DriverManager.getConnection(driver);st = con.createStatement();

st.executeUpdate("UPDATE CONTRACTS SET STATUS = '" + status + "' WHERE CONTRACTID = '" + contractID + "'");

results = true;} catch (SQLException sqlEx) {

System.out.println("SQL EXCEPTION: ERROR CODE: " + sqlEx.getErrorCode() + " state: " + sqlEx.getSQLState());

sqlEx.printStackTrace();} finally {

try {st.close();con.close();

} catch (SQLException e1) {}

}}return results;

}

/* (non-Javadoc) * @see

com.itso.rentals.ITSORentalsDatabaseService#getCustomer(java.lang.String) */public Customer getCustomer(String contractID) {

Customer customer = null;

//only allow one thread to access DB2esynchronized (syncLock) {

try {con = DriverManager.getConnection(driver);st = con.createStatement();

customer = new Customer();

//first find the contact and then...rs = st.executeQuery("SELECT CONTRACTID, CUSTOMERID, FLIGHT,

STATUS, LOCATION FROM CONTRACTS WHERE CONTRACTID = '" + contractID + "'");

while (rs.next()) { // should only be 1customer.setContractID(rs.getString(1));customer.setCustomerID(rs.getString(2));customer.setFlightInfo(rs.getString(3));customer.setCurrentStatus(rs.getString(4));customer.setVehicleLocation(rs.getString(5));

}

Chapter 4. Database 95

Page 112: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

rs.close();

// ...find the name that match the customer id rs = st.executeQuery("SELECT FIRSTNAME, LASTNAME FROM CUSTOMERS

WHERE CUSTOMERID = '" + customer.getCustomerID() + "'");

while (rs.next()) { // should only be 1customer.setFirstName(rs.getString(1));customer.setLastName(rs.getString(2));

}

} catch (SQLException sqlEx) {System.out.println("SQL EXCEPTION: ERROR CODE: " +

sqlEx.getErrorCode() + " state: " + sqlEx.getSQLState());sqlEx.printStackTrace();

} finally {try {

if (rs != null) rs.close();st.close();con.close();

} catch (SQLException e1) {}

}}return customer;

}

/* (non-Javadoc) * @see com.itso.rentals.ITSORentalsDatabaseService#sync() */public String sync(Properties userProps) {

if (standAlone) {return "Data refreshed successfully";

} else {return "Not implemented yet!";

}}

/* (non-Javadoc) * @see com.itso.rentals.ITSORentalsDatabaseService#getPending() */public Vector getPendingCustomers() {

return getState(Customer.PENDING);}

/* (non-Javadoc) * @see com.itso.rentals.ITSORentalsDatabaseService#getArrived() */

96 WCTME: Application Development and Case Study

Page 113: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

public Vector getArrivedCustomers() {return getState(Customer.ARRIVED);

}

/** * Returns a Vector of Customers that have the requested state * @param status * @return */private Vector getState(String status) {

Vector results = new Vector();

//only allow one thread to access DB2esynchronized (syncLock) {

try {con = DriverManager.getConnection(driver);st = con.createStatement();

//join the two tables and find the desired resultsrs = st.executeQuery("SELECT CUSTOMERS.CUSTOMERID,

CONTRACTS.CONTRACTID, CUSTOMERS.FIRSTNAME, CUSTOMERS.LASTNAME, CONTRACTS.FLIGHT, CONTRACTS.STATUS, CONTRACTS.LOCATION FROM CUSTOMERS, CONTRACTS WHERE CUSTOMERS.CUSTOMERID = CONTRACTS.CUSTOMERID AND CONTRACTS.STATUS = '"+ status +"' ORDER BY CUSTOMERS.LASTNAME, CUSTOMERS.FIRSTNAME");

while (rs.next()) {Customer customer = new Customer();

customer.setCustomerID(rs.getString(1));customer.setContractID(rs.getString(2));customer.setFirstName(rs.getString(3));customer.setLastName(rs.getString(4));customer.setFlightInfo(rs.getString(5));customer.setCurrentStatus(rs.getString(6));customer.setVehicleLocation(rs.getString(7));

//add to results Vectorresults.add(customer);

}} catch (SQLException sqlEx) {

System.out.println("SQL EXCEPTION: ERROR CODE: " + sqlEx.getErrorCode() + " state: " + sqlEx.getSQLState());

sqlEx.printStackTrace();} finally {

try {if (rs != null) rs.close();st.close();

Chapter 4. Database 97

Page 114: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

con.close();} catch (SQLException e1) {}

}}return results;

}

/* (non-Javadoc) * @see com.itso.rentals.ITSORentalsDatabaseService#insertPictures() */public boolean insertPictures() {

//for demo (stand-alone) mode can put local pictures in the database storeBlob("374906", "demo-images\\Image1.jpg");storeBlob("GHJ453", "demo-images\\Image2.jpg");storeBlob("JW3G56", "demo-images\\Image3.jpg");storeBlob("DI4F56", "demo-images\\Image4.jpg");storeBlob("XT345G", "demo-images\\Image5.jpg");storeBlob("FT3H78", "demo-images\\Image6.jpg");storeBlob("JK34S5", "demo-images\\Image7.jpg");

return true;}

/* (non-Javadoc) * @see com.itso.rentals.ITSORentalsDatabaseService#resetDemo() */public boolean resetDemo() {

//reset the status field and clear the vechicle location fieldboolean results = false;

//only allow one thread to access DB2esynchronized (syncLock) {

try {con = DriverManager.getConnection(driver);st = con.createStatement();

st.executeUpdate("UPDATE CONTRACTS SET STATUS = 'pending'");st.executeUpdate("UPDATE CONTRACTS SET LOCATION = '?'");results = true;

} catch (SQLException sqlEx) {System.out.println("SQL EXCEPTION: ERROR CODE: " +

sqlEx.getErrorCode() + " state: " + sqlEx.getSQLState());sqlEx.printStackTrace();

} finally {try {

98 WCTME: Application Development and Case Study

Page 115: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

st.close();con.close();

} catch (SQLException e1) {}

}}return results;

}

/** * For stand-alone use we must create and populate the database (we can

still sync with server later) * @return Results as a String * @see

com.itso.rentals.database.ITSORentalsDatabaseService#createLocalData() */public String createLocalData() {

String msg = "";

//only allow one thread to access DB2esynchronized (syncLock) {

try {con = DriverManager.getConnection(driver);st = con.createStatement();

try {st.executeUpdate("DROP TABLE CUSTOMERS");st.executeUpdate("DROP TABLE CONTRACTS");System.out.println("Tables have been dropped");

} catch (SQLException sqlEx) {System.out.println(

"Error dropping 1 or more tables. Probably because it did not exist");

}

st.executeUpdate("CREATE TABLE CUSTOMERS(CUSTOMERID VARCHAR(15) NOT NULL PRIMARY KEY, FIRSTNAME VARCHAR(20), LASTNAME VARCHAR(25), PHOTO BLOB(10000))");

st.executeUpdate("CREATE TABLE CONTRACTS(CONTRACTID VARCHAR(10) NOT NULL PRIMARY KEY, CUSTOMERID VARCHAR(15), FLIGHT VARCHAR(10), STATUS VARCHAR(15), LOCATION VARCHAR(10))");

st.executeUpdate("INSERT INTO CUSTOMERS VALUES( '374906' , 'Jeffrey', 'Martin', null)");

st.executeUpdate("INSERT INTO CUSTOMERS VALUES( 'GHJ453' , 'David', 'Reich', null)");

st.executeUpdate("INSERT INTO CUSTOMERS VALUES( 'JW3G56' , 'Gianfranco', 'Rutigliano', null)");

Chapter 4. Database 99

Page 116: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

st.executeUpdate("INSERT INTO CUSTOMERS VALUES( 'DI4F56' , 'Joel', 'Wickham', null)");

st.executeUpdate("INSERT INTO CUSTOMERS VALUES( 'XT345G' , 'Sid', 'Perera', null)");

st.executeUpdate("INSERT INTO CUSTOMERS VALUES( 'FT3H78' , 'Guillermo', 'Villavicencio', null)");

st.executeUpdate("INSERT INTO CUSTOMERS VALUES( 'JK34S5' , 'Juan', 'Rodriguez', null)");

st.executeUpdate("INSERT INTO CONTRACTS VALUES('1', '374906' , 'ITSO 4678', '" + Customer.PENDING + "', '?')");

st.executeUpdate("INSERT INTO CONTRACTS VALUES('2', 'GHJ453' , 'ITSO 1982', '" + Customer.PENDING + "', '?')");

st.executeUpdate("INSERT INTO CONTRACTS VALUES('3', 'JW3G56' , 'ITSO 329', '" + Customer.PENDING + "', '?')");

st.executeUpdate("INSERT INTO CONTRACTS VALUES('4', 'DI4F56' , 'ITSO 6', '" + Customer.PENDING + "', '?')");

st.executeUpdate("INSERT INTO CONTRACTS VALUES('5', 'XT345G' , 'ITSO 107', '" + Customer.PENDING + "', '?')");

st.executeUpdate("INSERT INTO CONTRACTS VALUES('6', 'FT3H78' , 'ITSO 1245', '" + Customer.PENDING + "', '?')");

st.executeUpdate("INSERT INTO CONTRACTS VALUES('7', 'JK34S5' , 'ITSO 11', '" + Customer.PENDING + "', '?')");

msg = "The CUSTOMERS and CONTRACTS tables have been successfully created!";

} catch (SQLException sqlEx) {System.out.println("SQL EXCEPTION: ERROR CODE: " +

sqlEx.getErrorCode());sqlEx.printStackTrace();

msg = "The local tables were not successfully created!";

} finally {try {

st.close();con.close();

} catch (SQLException e1) {}

}}System.out.println(msg);

return msg;}

/* (non-Javadoc)

100 WCTME: Application Development and Case Study

Page 117: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

* @see com.itso.rentals.database.ITSORentalsDatabaseService#updateVechicleLocation(java.lang.String, java.lang.String)

*/public boolean updateVechicleLocation(String contractID, String

vechicleLocation) {

//update the contract indicated with the location indicatedboolean results = false;

//only allow one thread to access DB2esynchronized (syncLock) {

try {con = DriverManager.getConnection(driver);st = con.createStatement();

st.executeUpdate("UPDATE CONTRACTS SET LOCATION='" + vechicleLocation + "' WHERE CONTRACTID='" + contractID + "'");

results = true;} catch (SQLException sqlEx) {

System.out.println("SQL EXCEPTION: ERROR CODE: " + sqlEx.getErrorCode() + " state: " + sqlEx.getSQLState());

sqlEx.printStackTrace();} finally {

try {st.close();con.close();

} catch (SQLException e1) {}

}}return results;

}

/** * For stand-alone mode, this method will insert pictures into the database * @param customerID * @param filename * @return */public boolean storeBlob(String customerID, String filename) {

FileInputStream fis = null;int size = 0;try {

fis = new FileInputStream(filename);size = fis.available();

} catch (IOException e) {

Chapter 4. Database 101

Page 118: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

System.out.println("Picture store (file = "+ filename +") for customerID = "+ customerID + " failed because " + e.getMessage());

}

if (fis != null) {PreparedStatement pstmt = null;//only allow one thread to access DB2esynchronized (syncLock) {

try {con = DriverManager.getConnection(driver);byte[] indata = new byte[size];// create a stream to read the fileDataInputStream in = new DataInputStream(fis);try {

in.readFully(indata);in.close();

} catch (IOException e1) {e1.printStackTrace();

} // Read file contents into array

pstmt = con.prepareStatement("UPDATE CUSTOMERS SET PHOTO = ? WHERE CUSTOMERID = '" +

customerID + "'");pstmt.setBytes(1, indata);pstmt.executeUpdate();

} catch (SQLException sqlEx) {System.out.println("SQL EXCEPTION: ERROR CODE: " +

sqlEx.getErrorCode() + " state: " + sqlEx.getSQLState());sqlEx.printStackTrace();

} finally {try {

if (rs != null) rs.close();pstmt.close();con.close();

} catch (SQLException e1) {}

}}

} else { return false;

}

return true;

}

/* (non-Javadoc)

102 WCTME: Application Development and Case Study

Page 119: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

* @see com.itso.rentals.database.ITSORentalsDatabaseService#getPicture(java.lang.String)

*/public InputStream getPicture(String customerID) {

InputStream is = null;Blob data = null;

//only allow one thread to access DB2esynchronized (syncLock) {

try {con = DriverManager.getConnection(driver);st = con.createStatement();

rs = st.executeQuery("SELECT PHOTO FROM CUSTOMERS WHERE CUSTOMERID = '" + customerID + "'");

while (rs.next()) { // should only be 1data = rs.getBlob(1);

}

} catch (SQLException sqlEx) {System.out.println("SQL EXCEPTION: ERROR CODE: " +

sqlEx.getErrorCode() + " state: " + sqlEx.getSQLState());sqlEx.printStackTrace();

} finally {try {

if (rs != null) rs.close();st.close();con.close();

} catch (SQLException e1) {}

}}

if (data != null) {try {

is = data.getBinaryStream();} catch (SQLException e) {

e.printStackTrace();}

}

return is;}

Chapter 4. Database 103

Page 120: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

20.Save the file.

21.Open the ExtensionServicesBundleActivator.java file (in the default package) and add the following line of code to the class:

private ServiceRegistration svcdb;

22.Add the following code in Example 4-4at the end of the start() method:

Example 4-4 Registering the start() method

svcdb = context.registerService(ITSORentalsDatabaseService.class.getName(),new ITSORentalsDatabaseImpl(),null);

This code registers the database service, so that other bundles can resolve it.

23.Add the following line of code at the end of the stop() method:

svcdb.unregister();

This code unregisters the service when the bundle stops.

24.Organize Imports and Save the file.

25.From the Package Explorer tab of the SMF Perspective, select the ITSORentalsDataBaseServiceBundle Project you created and expand it down to the file META-INF/MANIFEST.MF. Double-click the file name MANIFEST.MF. This opens the MANIFEST.MF editor.

26.Scroll down to Export Packages. Expand the section Export Packages and select Add...

27.Select the package com.itso.rentals.database and click OK.

28.Expand the section Export Services and select Add...

29.Select the service com.itso.rentals.database.ITSORentalsDatabaseService and click OK.

30.Save the file.

This package and its service can now be used by other bundles.

Tip: To help remove unresolved compiler errors, right-click in the source and select Source → Organize Imports.

If prompted, choose the Connection class in the java.sql package.

If prompted, choose the FileInputStream class in the java.io package.

104 WCTME: Application Development and Case Study

Page 121: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

4.4.3 Extending the Tester bundleIn this section we add to the Tester bundle created in Chapter 3, “Service Management Framework Runtime” on page 41 so that it uses the database bundle we just created. We are modifying the existing project build path to include the newly created bundle.

1. Select the ITSORentalsTesterBundle project. Right-click and select Properties, then select Java Build Path.

2. From the Projects tab, select the ITSORentalsDatabaseServiceBundle check box. Click OK.

3. Open the ITSORentalsTester.java file and add the following code in Example 4-5at the end of the init() method:

Example 4-5 Adding the new bundle to the project build path

//basic test of database service bundleSystem.out.println("\nTesting Database Service Bundle: ");//Resolve Database serviceITSORentalsDatabaseService databaseService = null;ServiceReference dbRef =

context.getServiceReference(ITSORentalsDatabaseService.class.getName());if (dbRef != null) {

databaseService = (ITSORentalsDatabaseService) context.getService(dbRef);

System.out.println("Found Database service!");}//initialize with defaultsdatabaseService.init(null);databaseService.createLocalData();

//simple database access testSystem.out.println("Getting contract 1: " +

databaseService.getCustomer("1"));System.out.println("Vector of arrived: " +

databaseService.getArrivedCustomers());System.out.println("Vector of pending: " +

databaseService.getPendingCustomers());

//test setting stateSystem.out.println("Updating contract 1 to arrived:");

databaseService.update2Arrived(databaseService.getCustomer("1").getContractID());

System.out.println("Updated contract: " + databaseService.getCustomer("1"));

Chapter 4. Database 105

Page 122: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

//test setting stateSystem.out.println("Updating contract 1 to exited:");

databaseService.update2Exited(databaseService.getCustomer("1").getContractID());

System.out.println("Updated contract: " + databaseService.getCustomer("1"));

4. Organize Imports and Save the file.

5. Open the MANIFEST.MF file. Scroll down to Import Packages.

6. Expand the section Import Packages and select Add...

7. Select the package com.itso.rentals.database and click OK.

8. Expand the section Import Services and select Add...

9. Select the service com.itso.rentals.database.ITSORentalsDatabaseService and click OK.

10.Save the file.

You should now be able to test the ITSORentalsDatabaseServiceBundle with the ITSORentalsTesterBundle. We are only doing a simple test of the database, but we will build on this in the next few chapters.

4.4.4 Database bundle reviewAs in the previous chapter lets review what we have done.

We created a new project and bundle that handles all the database activity for the sample application we are building. Since we are using DB2 Everyplace, we modified the development systems’s PATH to include the native DLLs that will be used. In the code we included the steps to register the new database service (see the bundle activator’s start() method) so that at runtime, other bundles will be able to find the new service. We also modified the bundle’s manifest file to show we export the new database package and service.

Note: By passing a null reference during the database service init method, we will be running with defaults and in stand-alone mode.

Note: The package com.itso.rentals.database might already have been added automatically, or you can press the Compute button to fill in the list.

106 WCTME: Application Development and Case Study

Page 123: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Then we went back to the tester bundle created in the previous chapter and modified it to access the new bundle and service that it exposes. These steps included new code to find the new database service registered by the new bundle and updating the manifest file to tell the runtime that the tester bundle now requires that new bundle’s package and service.

We still will have to submit the new and modified bundles to the bundle server and then install them into the runtime, so that we can successfully run the updated tester bundle.

Although this new bundle defaults to stand-alone mode, only the sync function, that will be covered in a later chapter, is controlled by that setting.

4.4.5 Testing the database bundleIn order to test the database Bundle, do the following:

1. If it is not running, start the SMF bundle server. For help see section 3.4, “Starting the SMF Bundle Server” on page 70.

2. Submit the ITSORentalsDatabaseServiceBundle and the updated ITSORentalsTesterBundle to the bundle server. For help see section 3.8, “Submitting bundles to the SMF bundle server” on page 77.

3. If it is not running, start the SMF runtime. For help see section 3.5, “Starting the SMF Runtime” on page 73.

4. Uninstall all the sample bundles previous installed into the runtime. Select each/all of those bundles, then right-click and select Uninstall.

5. In the Package Explorer pane, select the SMF Bundle Servers tab. Under the Admin@localhost:8080/smf, expand the Bundles tree.

6. Right-click the DB2EveryplaceClient bundle, and select Install.

7. Right-click ITSORentalsTesterBundle, and select Install.

Note: Later when we build the entire project and export it to run outside of Studio, the required DB2e dlls will automatically be included in the output and available on the target device.

Important: This extra step of adding the DB2EveryplaceClient manually is necessary because the drivers for DB2e are loaded dynamically and the tools cannot detect dynamically loaded classes.

Chapter 4. Database 107

Page 124: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

The test bundle and any bundles it requires will be installed into the runtime and the bundles will be started. The output of the test bundle will display in the SMF runtime’s console.

Review the output of the tester program in the console and verify that the tester bundles was able to access the database service and manipulate the database.

A directory named ITSODatabase is created on the device the first time the database bundle is initialized. In stand-alone mode, the call to createLocalData() will create and populate the local DB2e tables. The first sync with a DB2e sync server will destroy the local tables, if they exist, and create them with the appropriate server side content.

4.4.6 TroubleshootingIn this section, we list some common problems when developing database bundles.

� If you get an error stating that the driver cannot be found (java.sql.SQLException: No suitable driver), you need to add the DB2EveryplaceClient bundle manually to the runtime.

� If you get an unsatisfied link error for the DB2e driver or DB2e ISync driver (java.lang.UnsatisfiedLinkError: Can't find library DB2e (DB2e.dll) in java.library.path) or (java.lang.UnsatisfiedLinkError: Can't find library imsaconfig (imsaconfig.dll) in java.library.path), then you need to add the directories containing the missing dlls to the system PATH and restart WebSphere Studio. See the steps at the beginging of the procedure notes.

� If you get SQL exception, for example SQL EXCEPTION: ERROR CODE: -204 state: 42704, you can look up the errors in the DB2 Everyplace Documentation, Application Developers guide. See Figure 4-1 on page 87. This reference can be Access with Help-> Help Contents, then scroll down to DB2 Everyplace documentation -> DB2 Everyplace reference documentation -> Application Development Guide. For this specific error see Chapter 18 -> DB2 Everyplace SQL statement support. --> SQLState messages reported by SQL (Table 26). Or just open the development guide and search for the error number.

108 WCTME: Application Development and Case Study

Page 125: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Chapter 5. Messaging

This chapter discusses the concept of sending messages between programs running on different computers. It covers how a program running on a device can use the services of WebSphere MQ Everyplace to send and receive messages.

5

© Copyright IBM Corp. 2005. All rights reserved. 109

Page 126: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

5.1 Overview of MQeWebSphere MQ Everyplace (MQe) is a member of the IBM WebSphere MQ family of business messaging products. It exchanges messages with various applications, providing once and once-only assured delivery. WebSphere MQ Everyplace is designed to integrate well with other members of the WebSphere MQ family, and other components of the WebSphere MQ Everyplace Server.

WebSphere MQ Everyplace is designed to satisfy the messaging needs of lightweight devices, such as sensors, phones, Personal Digital assistants (PDAs), and mobile computers. It supports mobile environments and is suitable for use over public networks, supporting requirements that arise from the use of fragile communication networks. Because many WebSphere MQ Everyplace applications run outside the protection of an Internet firewall, MQe also provides security capabilities.

SMF is designed for running programs on devices which might not always be connected to other computers. However, these programs might still want to communicate with other programs. They can do this by sending messages. MQe provides the facilities to build and send messages asynchronously. MQe guarantees delivery, assuming that the device is connected to the network at least some of the time.

Examples of messages a program might send include: order entry, status updates, or requests for information. A program can also receive messages, with information about orders received, a list of things to be done, or replies to requests. Messages can be formatted any way that the program wishes, as long as both the sender and receiver agree on the format. A message can include simple text strings, or even serialized Java objects.

5.1.1 Documentation and Web LinksFor more information about MQe, see this Web site:

http://www.ibm.com/software/integration/wmqe/v20network/

The following are the WebSphere MQ Everyplace publications, available on the product CD and the Web site:

� WebSphere MQ Everyplace Read Me First, SC34-6276–02

This book contains general planning, migration, and installation information for WebSphere MQ Everyplace.

Note: This chapter is not intended to be a complete discussion of MQe or of messaging. For more detail, refer to the MQe documentation.

110 WCTME: Application Development and Case Study

Page 127: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

� WebSphere MQ Everyplace Introduction, SC34-6277–02

This book provides a general introduction to WebSphere MQ Everyplace, covering the product concepts and the relationship between WebSphere MQ Everyplace and other WebSphere MQ products.

� WebSphere MQ Everyplace Configuration Guide, SC34-6283–03

This book contains information about system administration using administration messages and the C administration API. It also describes the creation and administration of the fundamental components of a WebSphere MQ.

� WebSphere MQ Everyplace Application Programming Guide, SC34-6278–01

This book contains information about how to use the WebSphere MQ Everyplace Java class and C class libraries (described in the WebSphere MQ Everyplace Java Programming Reference) and the client platform C APIs (described in the WebSphere MQ Everyplace C Programming Reference).

� WebSphere MQ Everyplace System Programming Guide, SC34-6274–01

This book contains guidance and procedural information for writing WebSphere MQ Everyplace Java and C applications, and administering your systems.

5.1.2 Definition of termsIn order to understand the concepts of MQe, we need to discuss several terms:

� Messages� Queues� Queue managers� Connections� Listeners

MessagesMessages are objects which are subclasses of MQeMsgObject. The contents of a message can be anything the program wants. There are convenience methods to put data into a message and to extract it. Each field has a name and a value. For example to put a text field into a message, you would type:

msg.putAscii(“MyField”, “Hello, world!”);

To extract the value, you would use the getAscii() method, for example:

String myString = msg.getAscii(“MyField”);

Chapter 5. Messaging 111

Page 128: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

QueuesA queue is where messages are stored before they are sent to their destination, and after they have arrived there. A program can define its own queues or use the standard queues provided by MQe.

A queue can be local or remote. A local queue resides on the same system as the program sending messages to it. It could be used, for example, to send messages between programs running on the same computer. A remote queue exists on another computer, but MQe stores messages locally before forwarding them to their destinations.

A remote queue can be synchronous or asynchronous. A synchronous queue requires a connection to the actual queue. An asynchronous queue allows messages to be sent even if there is no active connection. Messages are stored until they are delivered.

Queue managersQueue managers manage the queues and take care of details of sending and receiving messages. Your program interacts with the queue manager, rather than the queues.

In MQe, there can only be one queue manager for each JVM.

ConnectionsA connection acts as a pipe between queue managers, allowing messages to flow between computers. A connection identifies the target queue manager, the IP address and the port number of the listener for the queue manager.

Before you can define a remote queue, you must define a connection to the remote queue manager. The connection does not have to be active. You do not have to have a link to the other queue manager, but you must define the connection.

ListenersIn order for a queue manager to receive messages from another, remote queue manager, it must have defined a listener. A listener identifies the port number where the system will listen for incoming messages. The port number of the listener must match the port number of any connections to that queue manager.

5.1.3 Message flow in MQeIn order to see how these pieces fit together, we can look at a simple scenario (Figure 5-1 on page 113) where program A, running on a computer identified as Client, with an IP address of 192.168.0.100, wants to send a message to

112 WCTME: Application Development and Case Study

Page 129: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

program B, which is running on a computer identified as Server, with an IP address of 192.168.0.1.

The queue manager on Server is QM1. The queue on QM1 is Q1.

Figure 5-1 Simple Message Flow in MQe

Program A begins by defining a connection to QM1. It knows that QM1 is on 192.168.0.1, and will be listening on port 8082. Next, program A defines Q1 as a remote queue on QM1.

Meanwhile, program B defines Q1 on QM1. On QM1, Q1 is a local queue. On QM2, it is a remote queue. Program B then defines a listener for QM1, listening on port 8082. Finally, it defines a message listener for Q1. The message listener is a Java interface with a method, messageArrived() which will be called whenever a message arrives on Q1.

Program A builds a message, puts data into it, and calls QM2 to send the message to Q1. If there is no connection between the systems, MQe stores the message in the remote queue on the client. The message will be sent later when a connection exists.

When the message arrives on QM1, MQe calls the message listener. Program B can then receive the message and process it.

Note that if program B wants to send a reply back to program A, it would have to know the queue manager and queue name. It would also have to have connection to QM2, and QM2 would have to be a listener. So, program B would also have to know the IP address and port number for the listener. In other words, the program running on the client would have to set up an MQe server.

Server

QM1

Q1

Client 192.168.0.100Server 192.168.0.1

ListenerPort:8082

Message Listener

QM2

QM1/Q1

ConnectionQM1

192.168.0.1Port:8082

Program A

Chapter 5. Messaging 113

Page 130: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

This would work well with machines that are always connected or at least have a fixed IP address. However, the devices we are working with have neither a constant connection nor a guaranteed fixed IP address. MQe provides the facilities to handle this situation, using two new types of queues: a store and forward queue and a home server queue.

In Figure 5-2 on page 115, we see how the pieces of our system can communicate even if program B does not know the address of program A.

Program B defines Q2 as a remote queue on QM2. It also defines a store and forward queue named SFQ. It tells QM1 that SFQ will handle messages for QM2. Now, program B simply sends a message to QM2/Q2. Since there is no connection to QM2, QM1 stores the message in the store and forward queue.

Meanwhile, program A establishes a home server queue. The home server queue identifies the store and forward queue SFQ on QM1 as its target. (There has to be a connection to QM1 defined as well.) Periodically, the home server queue will attempt to retrieve messages from the store and forward queue. If there is an active connection to QM1, the messages will flow. If not, QM2 will try again later.

In order for the home server queue to retrieve the messages, program A must call the triggerTransmission() method on QM2. Typically this is done by setting up a thread that sleeps for some interval, calls triggerTransmission(), and then sleeps again.

Note that because QM2 pulls the messages from the store and forward queue, program B does not need to know where QM2 resides.

114 WCTME: Application Development and Case Study

Page 131: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 5-2 Using Store and Forward and Home Server Queues

5.1.4 Building MQe MessagesMessages in MQe can contain any type of information needed by the applications that use them. The primary class to use is MQeMsgObject.

To create a message, use code such as this:

MQeMsgObject msg = new MQeMsgObject();

To add data to the message, use the various putXXXX() methods available. Each method takes a field name and a value. For example, to insert a field called ContractID with a value of G4573, use code such as the following:

msg.setAscii(“ContractID”,”G4573”);

There are also methods to insert Unicode, primitive data, objects, and arrays of primitive data.

You send a message by calling the putMessage method on the queue manager. You must give it the name of the queue manager and queue where the message is destined, as well as other parameters.

qm.putMessage(“QM1”,”Q1”,msg,null);

SFQ - QM2

QM1 QM2

qm.putMessage(qm2,q2,msg,null);

Pull

App A

App B

QM2/Q2

HSQ:QM1:SFQ

Message Listener

Q2

Chapter 5. Messaging 115

Page 132: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

5.1.5 Processing MQe messagesTypically you process messages inside the message listener method messageArrived(). This method is called by the queue manager. The parameter is MQeMsgEventObject. You retrieve the message by calling getMessage() on the queue manager. For example:

MQeMsgObject msg = qm.getMessage(null,”Q2”,null,null,0);

The getMessage() method allows you to filter which messages you retrieve. The third parameter is an instance of an MQeFields object which represents the filter describing the messages you want.

If there are no messages, getMessage throws an exception.

Once you have retrieved the message, you can extract the data using the various getXXXX() methods. The parameter is the name of the field that you want to retrieve. For example, to get the value of the ContractID field, you would code:

String contractID = msg.getAscii(“ContractID”);

Note that if the field does not exist in the message, the getXXXX() methods also throw an exception.

5.2 Using MQe in the example applicationIn our example application, we use messages to determine the slot number for a customer’s vehicle when he gets on the bus. The server determines the slot number and sends a message back to the device. The message listener updates the database with the slot number. The next time the Web page is refreshed, the driver can see the slot number.

To do this, the MQe service bundle must set up a connection to the server and a remote queue to which to send the messages. It must also define a home server queue, because the server will not know the IP address of the device.

The server sets up a queue to receive the messages, a listener, and a store and forward queue for each device. When a message arrives, the server determines the slot number. The message includes the reply queue manager name and the reply queue, the two pieces of information that the server needs to send the reply. If the queue manager is not yet included in the store and forward queue, the server adds it. The server program then sends the message.

116 WCTME: Application Development and Case Study

Page 133: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

In the next sections, we will look at some of the code involved in doing this. For the complete code, look at the sample code. This code concentrates on the code in the device, rather than the server code.

5.3 Example messaging exerciseThe sample application uses messaging to tell the server when a customer arrives and the server will use messaging to tell the client what slot the customer’s vehicle is located.

5.3.1 Messaging exercise descriptionIn this section we create a message service bundle that uses MQe message delivery. There are two messages in our application:

� The first message is from the client application to the server, telling the server that a customer has arrived.

� The second message is the server’s response telling the client in what slot the customer’s vehicle is located.

Other bundles will be able to access this bundle to send the message. The server’s response will be processed and the updated information stored in the local database.

Because we want this application to run in a stand-alone mode without a server we will initialize the bundle with properties that include a stand-alone flag. This flag will cause the messaging bundle to send a message to the server or just fake the message for the demonstration.

Service InterfaceThis is the set of methods we want to implement with this service bundle:

boolean init(Properties p);boolean customerArrived(String contractNumber);void shutdown();

5.3.2 Perform the exerciseFirst we need to create a Bundle Project to hold the messaging classes.

1. If WebSphere Studio Site Developer is not running, click Start → Programs → IBM WebSphere Studio → Site Developer 5.1.x.

2. Open the SMF Perspective. Select Window →Open Perspective →SMF.

Chapter 5. Messaging 117

Page 134: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3. Make sure you are on the Package Explorer tab. Select File →New → Other.

4. Select Extension Services →Extension Services Bundle Project and Click Next.

5. Enter the Project name ITSORentalsMQeServiceBundle and click Next.

Figure 5-3 Selecting the MQe application service

6. In the Platform Profile field (Figure 5-3) choose Extension Services: jclFoundation (5.7.0.).

118 WCTME: Application Development and Case Study

Page 135: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

7. Select the check box next to the application services WebSphere MQ Everyplace. Click Next.

Figure 5-4 Selecting other projects for this project’s build path

8. As in Figure 5-4, click the Projects tab and select the ITSORentalsDatabaseServiceBundle check box. Click Next.

9. Select the Create Default Bundle Activator check box. Click Finish.

10.If you see a panel indicating the folder has changed, click Yes.

Chapter 5. Messaging 119

Page 136: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

11.From the Package Explorer tab of the SMF Perspective, select the ITSORentalsMQeServiceBundle Project you just created and right-click. From the pop-up menu select New →Package.

12.Enter the package name com.itso.rentals.mqe and click Finish.

13.Select the package just created, and right-click. From the pop-up menu select New → Interface.

14.Enter the name ITSORentalsMQeService and click Finish.

15.Into the ITSORentalsMQeService.java window that opens, copy the following:

boolean init(Properties p);boolean customerArrived(String contractNumber);void shutdown();

16.Save the file.

17.Select the package just created, right-click. From the pop-up menu select New → Class. See Figure 5-5 on page 121.

Tip: To help remove unresolved compiler errors, right-click in the source and select Source →Organize Imports.

120 WCTME: Application Development and Case Study

Page 137: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 5-5 Creating the class implementing three interfaces

18.Enter the name ITSORentalsMQeImpl. Click the Interfaces: field Add button, add the Interface ITSORentalsMQeService, MQeMessageListenerInterface, Runnable and click OK. Click Finish.

19.Replace the methods generated automatically with the code in Example 5-1:

Example 5-1 Listener interface methods

private BundleContext context;private ITSORentalsDatabaseService databaseService = null;

private boolean standAlone = true;private static int count = 1;private MQeAdmin mqeAdmin;private String myQMName;private String myRegistry;private String targetQMName = "Transponder";private String targetQMIPAddress;private String targetQMPort;

Chapter 5. Messaging 121

Page 138: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

private String targetQName = "SYSTEM.DEFAULT.LOCAL.QUEUE";private String targetSFQ = "SFQ";private boolean createdQM;

private boolean timeToQuit = false;

/** * The public constructor * It stores the bundle context,sets up an MQe client to send messages to

the server, * and then sets up an MQe server to receive responses from the server * @param context */public ITSORentalsMQeImpl(BundleContext context) {

super();this.context = context;

}

/** * @see

com.itso.rentals.mqe.ITSORentalsMQeService#init(java.util.Properties) */public boolean init(Properties p) {

//deal with propertiesif (p != null) {

String standAloneString =p.getProperty("itso.mqe.standalone", "true");

standAlone = standAloneString.equalsIgnoreCase("true");targetQMIPAddress =

p.getProperty("itso.mqe.QMIPAddress", "127.0.0.1");targetQMPort = p.getProperty("itso.mqe.QMPort", "8086");targetQMName = p.getProperty("itso.mqe.QMName", "Transponder");myQMName = p.getProperty("itso.mqe.DeviceQMName", "ITSOQueues");myRegistry = myQMName;

}if (!standAlone) {

mqeAdmin = new MQeAdmin(myQMName, myRegistry);setupMQeClient();setupMQeServer();

}//Resolve Database serviceServiceReference dbRef =

context.getServiceReference(ITSORentalsDatabaseService.class.getName());

if (dbRef != null) {databaseService =

(ITSORentalsDatabaseService) context.getService(dbRef);

122 WCTME: Application Development and Case Study

Page 139: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

System.out.println("Found DataBase service!");

}

return true;}

/** * sends a message when a customer arrives * @param String - contract number of the customer who has arrived * @return boolean - always returns true */public boolean customerArrived(String contractNumber) {

if (standAlone) {databaseService.updateVechicleLocation(contractNumber, "A" +

count++);} else {

sendMessage(contractNumber);}

return true;}

/** * Checks to see if a QM is already running. If not it uses the MQeAdmin * to define a new QM, start it then create a connection definition * to the receivers QM. It then adds a remote queue definition to the * receivers local queue. */public void setupMQeClient() {

if (MQeQueueManager.getDefaultQueueManager() == null) {

mqeAdmin.defineQM();mqeAdmin.startQM();mqeAdmin.setRemoteQueueManagerName(targetQMName);mqeAdmin.createConnection(targetQMIPAddress, targetQMPort);mqeAdmin.addRemoteQueueDefinition(targetQMName, targetQName);

} else {mqeAdmin.startQM();

}

}

/*** Sets up the MQe Server. Calls MQeAdmin to create and start a

listener, then

Chapter 5. Messaging 123

Page 140: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

* adds a message itself as a message listener*/

public void setupMQeServer() {mqeAdmin.createHomeServerQueue(targetQMName, targetSFQ);

Thread kicker = new Thread(this);kicker.start();

MQeQueueManager qm = MQeQueueManager.getDefaultQueueManager();try {

qm.addMessageListener(this, MQe.System_Default_Queue_Name, null);} catch (Exception e) {

e.printStackTrace();}

}

/** * This method is called by the queue manager when a message arrives * The method extracts the contract id and slot number from the message,

and updates * the database with the information */public void messageArrived(MQeMessageEvent arg0) throws Exception {

MQeQueueManager qm = MQeQueueManager.getDefaultQueueManager();

//until we run out of messagesfor (;;) {

try {MQeMsgObject msg = qm.getMessage(null,

MQe.System_Default_Queue_Name, null, null, 0);String contractID = msg.getAscii("ContractID");String slot = msg.getAscii("Slot");System.out.println( "In messageArrived. Updating " + contractID +

" to slot " + slot);databaseService.updateVechicleLocation(contractID, slot);

} catch (MQeMessageStoreException mqemse) {System.out.println("Exception in messageArrived. [" +

mqemse.getMessage() + "]");mqemse.printStackTrace();

} catch (Exception e) {if (!e.getMessage().equalsIgnoreCase("Message not found")) {

System.out.println("Exception in messageArrived. [" + e.getMessage() + "]");

e.printStackTrace();}break;

}

124 WCTME: Application Development and Case Study

Page 141: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

}}

/** * Creates a message to send to the server. It includes the * "return address" information, including our queue manager * and queue names, plus the text of the message * * @param text - the text to be sent in the message * @return true if the message is sent without an exception */public boolean sendMessage(String text) {

if (mqeAdmin != null) {try {

String qmName =MQeQueueManager.getDefaultQueueManager().getName();

String qName = MQe.System_Default_Queue_Name;

MQeQueueManager qm = null;

MQeMsgObject outMessage = new MQeMsgObject();

outMessage.putAscii("ContractID", text);

outMessage.putAscii(MQe.Msg_ReplyToQ, qName);outMessage.putAscii(MQe.Msg_ReplyToQMgr, qmName);

qm = MQeQueueManager.getDefaultQueueManager();qm.putMessage(

targetQMName,MQe.System_Default_Queue_Name,outMessage,null,0);

return true;} catch (Exception e) {

e.printStackTrace();return false;

}} else {

return false;}

}

public void shutdown() {if (!standAlone) {

timeToQuit = true;mqeAdmin.stopQM();

}

Chapter 5. Messaging 125

Page 142: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

}

/** * The run method sleeps for 15 seconds and then tells the queue * manager to check for messages */public void run() {

while (!timeToQuit) {try {

MQeQueueManager.getDefaultQueueManager().triggerTransmission();Thread.sleep(15000);

} catch (Exception e) {e.printStackTrace();

}}

}

20.Organize Imports and Save the file.

21.Open the ExtensionServicesBundleActivator.java file (in the default package) and add the following code to the class:

private ServiceRegistration svcdb;private BundleContext context;private ITSORentalsMQeImpl mqeSvc;

22.Add the following code in Example 5-2 at the end of the start() method:

Example 5-2 Appending the start() method

this.context = context;mqeSvc = new ITSORentalsMQeImpl(context); svcdb = context.registerService(

ITSORentalsMQeService.class.getName(),mqeSvc,null);

This code registers the messaging service, so that other bundles can resolve it.

23.Add the following code at the end of the stop() method:

mqeSvc.shutdown();svcdb.unregister();

Note: There will be some unresolved external references until we build the MQAdmin class.

126 WCTME: Application Development and Case Study

Page 143: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

This code unregisters the service when the bundle stops.

24.Organize Imports and save the file.

25.From the Package Explorer tab of the SMF Perspective, select the ITSORentalsDatabaseServiceBundle Project you created and expand it down to the file META-INF/MANIFEST.MF. Double-click the file name MANIFEST.MF.

26.This opens the MANIFEST.MF editor. Scroll down to Export Packages.

27.Expand the section Export Packages and select Add...

28.Select the package com.itso.rentals.mqe and click OK.

29.Scroll down to Export Services and select Add...

30.Select the service com.itso.rentals.mqe.ITSORentalsMQeService and click OK.

31.Scroll down to Import Services.

32.Expand the section Import Services and select Add...

33.Select the service com.itso.rentals.database.ITSORentalsDatabaseService and click OK.

34.Save the file.

5.3.3 Creating the MQeAdmin ClassThe MQeAdmin class is required for both the client side and the MQe server side implementation. The MQeAdmin class contains a number of utility methods to access and manipulate queue managers and queues.

1. Create the MQeAdmin class in the same package as above. Insert the following code in Example 5-3 into the class file:

Example 5-3 MQeAdmin class code

/** * MQeAdmin class provides helper methods to create and configure * an MQeQueueManager. * * The QM name and Reg location to be used are passed in via * the constructor. * * This class configures QueueManagers to use the following adapters: * MQeTcpipHttpAdapter is used for comms. * MQeDiskFieldsAdapter is used for registry storage. *

Chapter 5. Messaging 127

Page 144: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

*/

public class MQeAdmin {

private String adapterClass = "com.ibm.mqe.adapters.MQeTcpipHttpAdapter";

private long channelTimeout = 3600000;private int maxNumberChannels = 10;

private MQeFields parms;private String myQmName;private String myReg;private MQeQueueManager qm = null;private MQeQueueManagerConfigure qmConfig = null;private String queueStore;private String DISK_ADAPTER = "com.ibm.mqe.adapters.MQeDiskFieldsAdapter";private String remoteQueueManagerName;private String queueName = "SYSTEM.DEFAULT.LOCAL.QUEUE";private String receiverQMIPAddress;

/** * Private reference to a disk adapter, to make sure * that configuration information set up in one method is not * garbage collected before it is used in other methods. */private MQeDiskFieldsAdapter myMemory = null;

/** * Constructor to create a new MQeAdmin. * This sets the QueueManager name and Registry location * to be used by the MQeQueuemanager. */

public MQeAdmin(String qmName, String regLocation) {

myQmName = qmName;myReg = regLocation;

}/** * setRemoteQueueManagerName sets the queue manager name * * @param remoteQueueManagerName */public void setRemoteQueueManagerName(String remoteQueueManagerName) {

this.remoteQueueManagerName = remoteQueueManagerName;}

/**

128 WCTME: Application Development and Case Study

Page 145: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

* Defines the Queue Manager */

public void defineQM() {

try {myMemory = new com.ibm.mqe.adapters.MQeDiskFieldsAdapter();queueStore =

DISK_ADAPTER+ ":"+ myReg+ File.separator+ "queues"+ File.separator;

parms = new MQeFields();MQeFields queueManagerParameters = new MQeFields();MQeFields registryParameters = new MQeFields();

// add qm name herequeueManagerParameters.putAscii(MQeQueueManager.Name, myQmName);// add reg location hereregistryParameters.putAscii(MQeRegistry.DirName, myReg);registryParameters.putAscii(MQeRegistry.Adapter, DISK_ADAPTER);parms.putFields(

MQeQueueManager.QueueManager,queueManagerParameters);

parms.putFields(MQeQueueManager.Registry, registryParameters);

// use MQeConfigqmConfig = new MQeQueueManagerConfigure(parms, queueStore);

// define default queuesqmConfig.defineQueueManager();qmConfig.defineDefaultSystemQueue();qmConfig.defineDefaultDeadLetterQueue();qmConfig.defineDefaultAdminReplyQueue();qmConfig.defineDefaultAdminQueue();

} catch (MQeException e) {if (e.code() == MQeExceptionCodes.Except_QMgr_AlreadyExists) {

System.out.println("MQeAdmin: QMgr already exists");} else {

System.out.println("Some MQeException in defining QM");e.printStackTrace();

}} catch (Exception e) {

System.out.println("MQeAdmin: Error defining QM " + e);

Chapter 5. Messaging 129

Page 146: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

e.printStackTrace();

} finally {try {

qmConfig.close();} catch (Exception e) {

System.out.println("MQeAdmin: Error closing QueueManager Configuration");

e.printStackTrace();}

}}

/** * Stops the Queue Manager */public void stopQM() {

try {// System.out.println("MQeAdmin: Stopping QM");if (qm.isQueueManagerActive()) {

qm.closeQuiesce(3000);}

} catch (Exception e) {

System.out.println("MQeAdmin: Error closing QM " + e);e.printStackTrace();

}

}

/** * Starts the Queue Manager */

public void startQM() {try {

qm = MQeQueueManager.getDefaultQueueManager();if (qm == null) {

qm = new MQeQueueManager();}if (parms != null) {

qm.activate(parms);}

} catch (Exception e) {System.out.println("MQeAdmin: Error starting QM " + e);e.printStackTrace();

}}

130 WCTME: Application Development and Case Study

Page 147: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

/** * Creates a listener on the Queue Manager */

public void createListener(int portNumber) {try {

MQeCommunicationsListenerAdminMsg createMessage =new MQeCommunicationsListenerAdminMsg();

// set the name of the resource we wish to createcreateMessage.setName("Listener 1");// provide the parameters to the method that will set the action of

the// administration message as well as the correct parameter names

using our// inputcreateMessage.create(

adapterClass,portNumber,channelTimeout,maxNumberChannels);

// set the target queue managercreateMessage.setTargetQMgr(myQmName);MQeAdminMsg response = sendMsgAndWait(createMessage);

if (response.getRC() != MQeAdminMsg.RC_Success) {throw new MQeException(response.getReason());

}} catch (Exception e) {

e.printStackTrace();}

}

/** * Starts the Listener that should have already been created on the QM. */

public void startListener() {try {

MQeCommunicationsListenerAdminMsg startMessage =new MQeCommunicationsListenerAdminMsg();

// set the name of the resource we wish to createstartMessage.setName("Listener 1");// provide the parameters to the method that will set the action of

the

Chapter 5. Messaging 131

Page 148: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

// administration message as well as the correct parameter names using our

// inputstartMessage.start();MQeAdminMsg response = sendMsgAndWait(startMessage);if (response.getRC() != MQeAdminMsg.RC_Success) {

throw new MQeException(response.getReason());}

} catch (Exception e) {System.out.println(

"MQeAdmin: Error creating starting Listener. " + e);System.out.println(

"MQeAdmin: Check that another server is not running and that nothing else is using this port");

e.printStackTrace();}

}

/** * Stops the Queue Managers Listener */

public void stopListener() {try {

MQeCommunicationsListenerAdminMsg startMessage =new MQeCommunicationsListenerAdminMsg();

// set the name of the resource we wish to createstartMessage.setName("Listener 1");// provide the parameters to the method that will set the action of

the// administration message as well as the correct parameter names

using our// inputstartMessage.stop();

MQeAdminMsg response = sendMsgAndWait(startMessage);if (response.getRC() != MQeAdminMsg.RC_Success) {

throw new MQeException(response.getReason());}

} catch (Exception e) {e.printStackTrace();

}}

/** * method to delete the listener using an administration message */

132 WCTME: Application Development and Case Study

Page 149: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

public void deleteListener() {try {

MQeCommunicationsListenerAdminMsg deleteMessage =new MQeCommunicationsListenerAdminMsg();

// set the name of the resource we wish to createdeleteMessage.setName("Listener 1");// provide the parameters to the method that will set the action of

the// administration message as well as the correct parameter names

using our// inputdeleteMessage.setAction(MQeAdminMsg.Action_Delete);

MQeAdminMsg response = sendMsgAndWait(deleteMessage);if (response.getRC() != MQeAdminMsg.RC_Success) {

throw new MQeException(response.getReason());}

} catch (Exception e) {e.printStackTrace();

}}

/** * Adds a remote queue definition. This is used by the client to setup * a remote queue definition to the servers local queue. * * @param remoteQueueManagerName * @param queueName */public void addRemoteQueueDefinition(

String remoteQueueManagerName,String queueName) {try {

this.remoteQueueManagerName = remoteQueueManagerName;this.queueName = queueName;MQeRemoteQueueAdminMsg remQueueMsg =

new MQeRemoteQueueAdminMsg(remoteQueueManagerName, queueName);remQueueMsg.setTargetQMgr(

MQeQueueManager.getDefaultQueueManager().getName());MQeFields parms = new MQeFields();

parms.putByte(MQeQueueAdminMsg.Queue_Mode,MQeQueueAdminMsg.Queue_Asynchronous);

parms.putAscii(MQeQueueAdminMsg.Queue_FileDesc, queueStore);

remQueueMsg.create(parms);MQeAdminMsg response = sendMsgAndWait(remQueueMsg);

Chapter 5. Messaging 133

Page 150: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

if (response.getRC() != MQeAdminMsg.RC_Success) {if (response

.getReason()

.indexOf(String.valueOf(MQeExceptionCodes.Except_QMgr_QExists))

== -1) {throw new MQeException(response.getReason());

}}

} catch (Exception e) {e.printStackTrace();

}

}

/** * method to show how a connection definition may be created using an

administration * message. This is used by the client to setup a connection definition to

the * server so messages can be sent. * * @param receiverQMIPAddress * @param receiverQMPort */public void createConnection(

String receiverQMIPAddress,String receiverQMPort) {try {

MQeConnectionAdminMsg connectionMessage =new MQeConnectionAdminMsg();

// Set the name of the resource we wish to create. The connection definition name

// is always the same as the name of the remote queue manager to which its

// information will allow you to goconnectionMessage.setName(remoteQueueManagerName);

// Call the method that will automatically set the correct MQeFields for our connection.

connectionMessage.create(//"com.ibm.mqe.adapters.MQeTcpipHttpAdapter:""Network:" + receiverQMIPAddress + ":" + receiverQMPort,

null,null,"DefaultChannel",

134 WCTME: Application Development and Case Study

Page 151: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

"Example connection");MQeAdminMsg response = sendMsgAndWait(connectionMessage);

} catch (Exception e) {System.out.println("MQeAdmin: Error creating connection " + e);e.printStackTrace();

}}

/** * method to show how a connection definition may be deleted using an

administration * message */public void deleteConnection() {

try {MQeConnectionAdminMsg deleteMessage = new MQeConnectionAdminMsg();

// set the target queue managerdeleteMessage.setTargetQMgr(myQmName);

deleteMessage.setName(remoteQueueManagerName);

deleteMessage.setAction(MQeAdminMsg.Action_Delete);

// indicate that we require a reply messagedeleteMessage.putInt(MQe.Msg_Style, MQe.Msg_Style_Request);

// use default reply-to queue on the target queue manager.deleteMessage.putAscii(

MQe.Msg_ReplyToQ,MQe.Admin_Reply_Queue_Name);

deleteMessage.putAscii(MQe.Msg_ReplyToQMgr, myQmName);

// create a unique tag that we can identify the reply withString match = "Msg" + System.currentTimeMillis();

deleteMessage.putArrayOfByte(MQe.Msg_CorrelID, match.getBytes());

System.out.println("MQeAdmin: delete connection administration message created");

// now put the administration message to the default administration queue

qm.putMessage(myQmName,MQe.Admin_Queue_Name,deleteMessage,null,

Chapter 5. Messaging 135

Page 152: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

0);

// create the filter so we get the matchMQeFields filter = new MQeFields();filter.putArrayOfByte(MQe.Msg_CorrelID, match.getBytes());

// now wait for a replyMQeAdminMsg response =

(MQeAdminMsg) qm.waitForMessage(myQmName,MQe.Admin_Reply_Queue_Name,filter,null,0,3000);

// the administration message has a method that will get out the return code

switch (response.getRC()) {case MQeAdminMsg.RC_Success :

System.out.println("MQeAdmin: connection deleted");break;

case MQeAdminMsg.RC_Fail :System.out.println(

"MQeAdmin: connection not deleted, failed with: "+ response.getReason());

break;case MQeAdminMsg.RC_Mixed :

processMixedResult(response);break;

}if (response.getRC() != MQeAdminMsg.RC_Success) {

throw new MQeException(response.getReason());}

} catch (Exception e) {e.printStackTrace();

}}

/** * A utility method to process a mixed response from sending an admin

message * @param response * @throws Exception */public void processMixedResult(MQeAdminMsg response) throws Exception {

if (response.getReason().indexOf(

136 WCTME: Application Development and Case Study

Page 153: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

String.valueOf(MQeExceptionCodes.Except_QMgr_QExists))

// if it is not that the queue already exists== -1) {

MQeFields errors = response.getErrorFields();Enumeration fields = errors.fields();

while (fields.hasMoreElements()) {String value[];String name = (String) fields.nextElement();

if (errors.dataType(name) == MQeField.TypeArrayElements)value = errors.getAsciiArray(name);

elsevalue = new String[] { errors.getAscii(name)};

for (int j = 0; j < value.length; j++) {

if (value[j].indexOf(

String.valueOf(MQeExceptionCodes.Except_QMgr_QExists))

// if it is not that the queue already exists== -1)System.out.println(

"MQeAdmin: Field "+ name+ " failed with "+ value[j]);

}}

}}/**

* Creates a home server queue on the Queue Manager */

public void createHomeServerQueue(String targetQMName, String qName) {try {

MQeHomeServerQueueAdminMsg createMessage =new MQeHomeServerQueueAdminMsg(targetQMName, qName);

MQeFields params = new MQeFields();params.putLong(MQeHomeServerQueueAdminMsg.Queue_QTimerInterval, 0L);

// provide the parameters to the method that will set the action of the

// administration message as well as the correct parameter names using our

// input

Chapter 5. Messaging 137

Page 154: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

createMessage.create(params);

MQeAdminMsg response = sendMsgAndWait(createMessage);

if (response.getRC() != MQeAdminMsg.RC_Success) {if (response

.getReason()

.indexOf(String.valueOf(

MQeExceptionCodes.Except_QMgr_QExists))// if it is not that the queue already exists== -1) {

throw new MQeException(response.getReason());}

}} catch (Exception e) {

e.printStackTrace();}

}

/** * Create a store and forward queue * * @param targetQueueManagerName - the name of the local queue manager * @param qName - the name of the store and forward queue */public void createStoreAndForwardQueue(

String targetQueueManagerName,String qName) {

try {MQeStoreAndForwardQueueAdminMsg createMessage =

new MQeStoreAndForwardQueueAdminMsg(targetQueueManagerName,qName);

parms = new MQeFields();// provide the parameters to the method that will set the

action of the// administration message as well as the correct parameter names

using our// inputcreateMessage.create(parms);MQeAdminMsg response = sendMsgAndWait(createMessage);// if the SFQ already exists, it is not a problemif (response.getRC() != MQeAdminMsg.RC_Success) {

if (response.getReason()

138 WCTME: Application Development and Case Study

Page 155: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

.indexOf(String.valueOf(

MQeExceptionCodes.Except_QMgr_QExists))// if it is not that the queue already exists== -1) {

throw new MQeException(response.getReason());}

}} catch (Exception e) {

e.printStackTrace();}

}

/** * This method adds a target queue manager to the existing store and

forward queue * The hosting queue manager is usually the local queue manager. * * @param hostingQMgr - name of the hosting queue manager * @param qName - name of the store and forward queue * @param acceptForQMgr - the name of the queue manager that the SFQ will

hold messages for */public void addTargetQMgrToStoreAndForwardQueue(

String hostingQMgr,String qName,String acceptForQMgr) {try {

MQeStoreAndForwardQueueAdminMsg createMessage =new MQeStoreAndForwardQueueAdminMsg(hostingQMgr, qName);

createMessage.addQueueManager(acceptForQMgr);MQeAdminMsg response = sendMsgAndWait(createMessage);

if (response.getRC() != MQeAdminMsg.RC_Success) {if (response

.getReason()

.indexOf(String.valueOf(

MQeExceptionCodes.Except_QMgr_QExists))// if it is not that the queue already exists== -1) {//throw new MQeException(response.getReason());

}}

} catch (Exception e) {e.printStackTrace();

Chapter 5. Messaging 139

Page 156: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

}}

/** * This method encapsulates the process of sending a message to the admin

queue and * waiting for a response. * @param createMessage * @return the return MQeQdminMsg * @throws Exception */public MQeAdminMsg sendMsgAndWait(MQeAdminMsg createMessage)

throws Exception {// set the target queue managercreateMessage.setTargetQMgr(myQmName);

// indicate that we require a reply messagecreateMessage.putInt(MQe.Msg_Style, MQe.Msg_Style_Request);

// use default reply-to queue on the target queue manager.createMessage.putAscii(MQe.Msg_ReplyToQ, MQe.Admin_Reply_Queue_Name);createMessage.putAscii(MQe.Msg_ReplyToQMgr, myQmName);

// create a unique tag that we can identify the reply withString match = "Msg" + System.currentTimeMillis();

createMessage.putArrayOfByte(MQe.Msg_CorrelID, match.getBytes());

// now put the administration message to the default administration queue

qm.putMessage(myQmName, MQe.Admin_Queue_Name, createMessage, null, 0);

// create the filter so we get the matchMQeFields filter = new MQeFields();

filter.putArrayOfByte(MQe.Msg_CorrelID, match.getBytes());

// now wait for a replyMQeAdminMsg response =

(MQeAdminMsg) qm.waitForMessage(myQmName,MQe.Admin_Reply_Queue_Name,filter,null,0,3000);

// the administration message has a method that will get out the return code

140 WCTME: Application Development and Case Study

Page 157: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

switch (response.getRC()) {case MQeAdminMsg.RC_Success :

//System.out.println("MQeAdmin: listener created");break;

case MQeAdminMsg.RC_Fail :if ((response

.getReason()

.indexOf(String.valueOf(

MQeExceptionCodes.Except_QMgr_QExists))// if it is not that the queue already exists== -1)&& (response

.getReason()

.indexOf(String.valueOf(

MQeExceptionCodes.Except_QMgr_AlreadyExists))// if it is not that the queue manager already exists

== -1)) {System.out.println(

"MQeAdmin: action failed with: "+ response.getReason());

//throw new MQeException(response.getReason());}

break;case MQeAdminMsg.RC_Mixed :

processMixedResult(response);break;

}

return response;}

}

2. Organize Imports and Save the class.

This should eliminate the unresolved reference error messages from ITSORentalsMQeServiceBundle.

5.3.4 Extending the Tester BundleIn this section we add to the Tester bundle so that it uses the messaging bundle we just created.

1. Select the ITSORentalsTesterBundle project, right-click and select Properties, then select Java Build Path.

Chapter 5. Messaging 141

Page 158: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

2. Select the ITSORentalsMQeServiceBundle check box from the Projects tab. Click OK.

3. Open the ITSORentalsTester.java file and add the following code at the end of the init() method

Example 5-4 ITSORentalsTester.java file init() method extender

//basic test of MQe serviceSystem.out.println("\nTesting MQe Service Bundle: ");//Resolve MQe serviceITSORentalsMQeService mqeService = null;ServiceReference mqRef =

context.getServiceReference(ITSORentalsMQeService.class.getName());if (mqRef != null) {

mqeService = (ITSORentalsMQeService) context.getService(mqRef);System.out.println("Found MQe service!");

}//initialize with defaultsmqeService.init(null);

//simple mqe access testmqeService.customerArrived("1");System.out.println("Getting contract 1: " +

databaseService.getCustomer("1"));

4. Organize imports and Save the file.

5. Open the MANIFEST.MF file. Scroll down to Import Packages.

6. Expand the section Import Packages and select Add...

7. Select the package com.itso.rentals.mqe and click OK.

8. Expand the section Import Services and select Add...

9. Select the service com.itso.rentals.mqe.ITSORentalsMQeService and click OK.

10.Save the file.

You should now be able to test the ITSORentalsMQeServiceBundle with the ITSORentalsTesterBundle. We are only doing a simple test of sending a message in a standalone environment, but we will build on this in the next few chapters.

Note: The package com.itso.rentals.mqe might already have been added automatically, or you can press the Compute button to fill in the list.

142 WCTME: Application Development and Case Study

Page 159: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

5.3.5 Example messaging reviewWe created a new project and bundle that handles all the messaging activity for the sample application we are building. In the code, we included the steps to register the new messaging service so that at runtime, other bundles will be able to find the new service. We also modified the bundle’s manifest file to show we export the new messaging package and service.

Then we went back to the tester bundle and modified it to access the new bundle and service that it exposes. These steps included new code to find the new messaging service registered by the new bundle and updating the manifest file to tell the runtime that the tester bundle now requires that new bundle’s package and service.

We still will have to submit the new and modified bundles to the bundle server and then install them into the runtime, so that we can successfully run the updated tester bundle.

At this point we have not created the server side of the MQe service. The service will run in a stand-alone mode that does not send or receive messages. Running the tester bundle now will confirm that a connection between the bundles has been made and that, when a message is received, the database is updated. See the init(Properties) method of the message service to see what needs to be configured before an MQe message can be sent. In a later chapter, the properties data will be created and messages can be sent if enabled.

5.3.6 Testing the MQe bundleIn order to test the MQe bundle, perform the following steps:

1. If it is not running, start the SMF bundle server. For help see section 3.4, “Starting the SMF Bundle Server” on page 70.

2. Submit the ITSORentalsMQeServiceBundle and the updated ITSORentalsTesterBundle to the bundle server. For help see section 3.8, “Submitting bundles to the SMF bundle server” on page 77.

3. If it is not running, start the SMF runtime. For help see section 3.5, “Starting the SMF Runtime” on page 73.

4. Uninstall all the sample bundles previous installed into the runtime. Select each or all of those bundles, then right-click and select Uninstall.

5. In the bundle server pane, select the SMF Bundle Servers tab. Under the Admin@localhost:8080/smf, expand the bundles tree.

6. Right click ITSORentalsTesterBundle, and select Install.

Chapter 5. Messaging 143

Page 160: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

The test bundle and any bundles it requires are installed into the runtime and the bundles are started. The output of the test bundle displays in the SMF runtime’s console.

Review the output of the tester program in the console and verify that the tester bundles were able to access the messaging service in stand-alone mode.

5.4 Creating the MQe ServerThe MQe server (Transponder) is the server side of the MQe messaging system. In a real application, it would look up the slot number for the customer. In our application, it generates a random slot number.

The server receives the messages from the client. The message includes the contract ID as well as the return address information. It builds a message and sends it to the remote queue. The message resides on the store and forward queue until the client retrieves it.

1. Make sure you are on the Package Explorer tab. Select File → New → Project → Java → Java Project. Click Next. See Figure 5-6 on page 145.

144 WCTME: Application Development and Case Study

Page 161: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 5-6 Creating a new Java Project

2. As in Figure 5-7 on page 146, enter the name ITSOMQeServer, then click Next.

Chapter 5. Messaging 145

Page 162: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 5-7 Naming the new Java Project

3. On the Java Settings panel (Figure 5-8 on page 147), select the Libraries tab, then Add External Jars...

146 WCTME: Application Development and Case Study

Page 163: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 5-8 Adding External Jars files to a project

4. Navigate to the ESWE technologies bundlefiles directory (C:\Program Files\IBM\DeviceDeveloper\wsdd5.0\technologies\eswe\bundlefiles) and select MQeBundle.jar then click Open. See Figure 5-9 on page 148.

Chapter 5. Messaging 147

Page 164: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 5-9 Selecting the MQeBundle jar file

5. Click Finish. If you get prompted to change to the Java Perspective, select Yes.

The ITSOMQeServer project is created. Now we will add some code to the project. See Figure 5-10 on page 149.

6. Create a new package called com.ibm.wctme.host.

7. Create a class called MQeTransponder. Be sure to include a main method. MQeTransponder should implement the MQeMessageListenerInterface interface.

148 WCTME: Application Development and Case Study

Page 165: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 5-10 Creating the MQeTransponder class

8. Replace the class contents with the following code in Example 5-5:

Example 5-5 ITSOMQeServer project code

public static final String QMName = "Transponder";public static final String QMDirectory = "/Transponder";public static final String LISTEN_PORT_NUMBER = "8086";public static final String STORE_AND_FORWARD_QUEUE = "SFQ";

private MQeAdmin mqeAdmin;private List knownQMs;

private Frame simpleFrame = new Frame("ITSO Rentals (Sample) MQeServer");private Button shutdownButton = new Button("Shut down");

Chapter 5. Messaging 149

Page 166: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

public MQeTransponder() throws Exception {mqeAdmin = new MQeAdmin(MQeTransponder.QMName,

MQeTransponder.QMDirectory);knownQMs = new ArrayList();

simpleFrame.setLayout(new FlowLayout());simpleFrame.add(new Label("MQe Server"));simpleFrame.add(shutdownButton);simpleFrame.setSize(250, 100);simpleFrame.setLocation(250, 100);simpleFrame.setVisible(true);simpleFrame.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent we) {shutdown();

}});shutdownButton.addActionListener( new ActionListener() {

public void actionPerformed( ActionEvent e ) {shutdown();

}});

}

/** * Checks to see if a QM is already running. If not it uses the MQeAdmin * to define a new QM, create a store and forward queue, * start it then create a listener and start it. * If a QM is already running then an exception is thrown. */public void setupMQeServer() throws Exception {

if (MQeQueueManager.getDefaultQueueManager() == null) {mqeAdmin.defineQM();mqeAdmin.startQM();mqeAdmin.createStoreAndForwardQueue(

MQeQueueManager.getDefaultQueueManager().getName(),MQeTransponder.STORE_AND_FORWARD_QUEUE);

mqeAdmin.createListener(Integer.parseInt(MQeTransponder.LISTEN_PORT_NUMBER));

mqeAdmin.startListener();MQeQueueManager qm = MQeQueueManager.getDefaultQueueManager();qm.addMessageListener(this, MQe.System_Default_Queue_Name, null);System.out.println("MQeTransponder listening for messages");} else {

throw new Exception("ERROR - QM Already Running");}

}

150 WCTME: Application Development and Case Study

Page 167: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

/* (non-Javadoc) * @see

com.ibm.mqe.MQeMessageListenerInterface#messageArrived(com.ibm.mqe.MQeMessageEvent)

*/public void messageArrived(MQeMessageEvent arg0) throws Exception {

MQeQueueManager qm = MQeQueueManager.getDefaultQueueManager();

//until we run out of messagesfor (;;) {

try {MQeMsgObject msg = qm.getMessage(null,

MQe.System_Default_Queue_Name, null,null, 0);

String qmName = msg.getAscii(MQe.Msg_ReplyToQMgr);String qName = msg.getAscii(MQe.Msg_ReplyToQ);String contractID = msg.getAscii("ContractID");System.out.println("MQeTransponder: Message text :" + contractID);if (!knownQMs.contains(qmName)) {

mqeAdmin.addTargetQMgrToStoreAndForwardQueue(MQeQueueManager.getDefaultQueueManager().getName(),MQeTransponder.STORE_AND_FORWARD_QUEUE,qmName);

knownQMs.add(qmName);}

MQeMsgObject replyMsg = new MQeMsgObject();replyMsg.putAscii("ContractID", contractID);replyMsg.putAscii("Slot", getSlotNo());qm.putMessage(qmName, qName, replyMsg, null, 0);System.out.println("MQeTransponder: Sent message");

} catch (MQeMessageStoreException mqemse) {System.out.println("MQeTransponder: Exception in messageArrived.

[" + mqemse.getMessage() + "]");mqemse.printStackTrace();

} catch (Exception e) {if (!e.getMessage().equalsIgnoreCase("Message not found")) {

System.out.println("Exception in messageArrived. [" + e.getMessage() + "]");

e.printStackTrace();}break;

}}

}

/** * Generate a random slot number between 1 and 100

Chapter 5. Messaging 151

Page 168: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

* @return "A" + the slot number */private String getSlotNo() {

int slotNo = (int) (Math.random() * 100) + 1;return "A" + slotNo;

}public static void main(String[] args) throws Exception {

MQeTransponder dem = new MQeTransponder();dem.setupMQeServer();

}

/** * shutdown **/public void shutdown() {

System.out.println("Shuting Down...");

//call MQe and tell to shutdown...mqeAdmin.stopQM();

simpleFrame.dispose();System.exit(0);

}

9. Organize Imports and Save the code. If you are prompted, choose the java.util.List class. There will be some unresolved external references to the MQeAdmin class.

10.Copy and paste the MQAdmin file from the ITSORentalsMQeServiceBundle to this project’s java package. This should resolve the external references.

This completes the ITSOMQeServer project.

5.4.1 Running the MQe ServerThe MQe server is a Java program that waits for a message, then sends back a reply message with a slot number.

To start the MQe server in WebSphere Studio Site Developer, do the following:

1. Select the ITSOMQeServer project.

2. From the Run menu, select Run → Run As → Java Application

The program starts and message displayed in the console. A message displays every time a message is received and processed.

152 WCTME: Application Development and Case Study

Page 169: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

You can export the ITSOMQeServer project to run on your MQe server and launch it from the command line with the following command:

java -cp "MQeBundle.jar;ITSOMQeServer.jar" com.ibm.wctme.host.MQeTransponder

MQeBundle.jar is from your MQe Server installation and ITSOMQeServer.jar is the exported project.

The completed MQe server project is available from IBM. See the Additional Materials appendix for information about how to download it.

The running MQe server creates the directory \Transponder on the system that you run the program. This directory contains the queues necessary to process the inbound and outbound MQ messages. Only delete this directory to completely reset the queues.

5.4.2 Message troubleshootingEach client must have a unique device queue name configured. Use the configuration panel of the sample application to set the device queue name before you disable stand-alone MQe operations.

There might be a short delay in the processing of MQe messages, requiring you to refresh the screen to see the returned message.

The MQe messages are stored on the client side until the server is available. They will be processed when you start the server.

Chapter 5. Messaging 153

Page 170: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

154 WCTME: Application Development and Case Study

Page 171: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Chapter 6. Web Services

This chapter introduces Web Services and how Web Services are supported in WCTME.

This chapter contains the following topics:

� Service-Oriented Architecture concepts� Web Services concepts� Web Services in WCTME� Sample scenario of Web Services with WCTME

6

© Copyright IBM Corp. 2005. All rights reserved. 155

Page 172: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

6.1 Service-Oriented ArchitectureA Service-Oriented Architecture (SOA) is an approach to specifying the integration of diverse architectures using services. Services can be defined as the different functional units of an application packaged as a reusable component. They encapsulate reusable business functions by neutral interfaces defined according to industry standards and independent of the software and hardware platform implementation of the service. These interfaces are invoked through defined protocols of communication.

The following list discusses components of an SOA:

� Service provider offers services based in SOA approach by publishing their interfaces to a service broker.

� Service broker makes available the information about the interfaces published by services provider to any requestor.

� Service requestor searches on broker information for available services and requests the corresponding provider to use these services.

Figure 6-1 shows how these three components interact with each other.

Figure 6-1 SOA components

Using neutral interfaces, the service provider hides any technical implementation details of its services to the service requestor. That is known as loose coupling between services. Loose coupling allows different systems to interact and change without impacting the other.

Service Broker

Publish InterfacesService Provider

Service Requestor

Search Interfaces Information

Request/Response for Services

156 WCTME: Application Development and Case Study

Page 173: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

6.2 Web servicesWeb services is a technology that allows applications to communicate with each other across a network, based in XML-formatted requests and with standard communications protocols. Web services are self-contained, self-describing modular applications that can be accessed over the network:

� Self-contained

On the client side, the only requirement is a programming language with XML and HTTP client support. On the server side, an HTTP and SOAP server are required.

� Self-describing

Client and server communicate each other using established request and response messages. The definition of the message format travels with the messages.

� Modular

Web services can interact together to form an aggregate, more complex Web service.

Web services are, essentially a way to implement a service-oriented architecture, but not the only one. Web services allows:

� The interaction of applications of different architectures

� Changes in structure and implementation of the services using loose coupling services

� A faster adaptation to any business condition or customer need change

� The creation of service interfaces for existing or legacy software applications without changing them.

Note: For more information about SOA, consult the following references:

� WebSphere Version 6 Web Services Handbook: Development and Deployment. SG24-6461-00.

� WebSphere Version 5.1 Application Developer 5.1.1 Web Services Handbook. SG24-6891-00.

� See the Web site:

http://www.ibm.com/developerworks/webservices

Chapter 6. Web Services 157

Page 174: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Web services are based on standards to guarantee interoperability with different platforms. The core Web services standards are:

� Simple Object Access Protocol (SOAP) is an XML-based standard for the exchange of structured information in a decentralized, distributed environment. It is composed of three parts:

– An envelope specifying who and how to deal with the message, and the message itself.

– A set of encoding rules

– A remote procedure call (RPC) representation.

SOAP runs over existing Internet infrastructure.

� Web Services Description Language (WSDL) is an XML-based open specification that describes Web services interfaces over the network. It provides a simple way to service providers to describe the format of the requests for the services their offer, regardless of their implementation.

Service providers can specify the following Web services characteristics using WSDL:

– Name and address information

– How to access the Web services operations (protocol and encoding style)

– Type of information (operations, parameters and data types that conform the Web Service interface)

WSDL documents allow you to expose applications as network-accessible services on the Internet.

� Universal, Description, Discovery and Integration (UDDI) is an open, platform-independent standard that allow to publish and discover information about Web Services over the Internet.

� Web Services Inspection Language (WSIL) is an XML-based specification that describes the way to locate available Web Services descriptions on a Web site. The WSIL specification complements UDDI facilitating the discovery of services that are available on Web sites that may not be listed yet in a UDDI registry.

� XML is the foundation standard of Web services.

The Java standards and APIs that are relevant to Web Services are:

� JSR 101 - Java APIs for XML based RPC (JAX-RPC)� JSR 109 - Implementing Enterprise Web Services� JSR 31 - XML Data Binding Specification (JAXB)� JSR 67 - Java APIs for XML Messaging 1.0 (JAXM)� JSR 93 - Java API for XML Registries 1.0 (JAXR)

158 WCTME: Application Development and Case Study

Page 175: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

� JSR 110 - Java APIs for WSDL (WSDL4J)� JSR 172 - J2ME Web Services Specification� JSR 173 - Streaming API for XML� JSR 181 - Web Services Metadata for the Java Platform� JSR 208 - Java Business Integration (JBI)� JSR 222 - Java Architecture for XML Binding (JAXB) 2.0� JSR 224 - Java API for XML-Based RPC (JAX-RPC) 2.0� JSR 921 - Implementing Enterprise Web Services 1.1

Figure 6-2 shows the relationship between SOAP, WSDL and UDDI in Web Services architecture:

� A service provider makes available a Web service and can be accessed by a service requestor using HTTP or SOAP.

� A WSDL document contains the description of the Web service.

� The WSDL document is referenced by the service broker using UDDI.

� The service requestor can discover Web services using UDDI.

Figure 6-2 Web services components and standards

Service Broker

Service Provider

Publish

Request/Response (SOAP)

WSDL Document

UDDI

Service Requestor

SO

AP

DiscoverSO

AP

HTT

P

HTT

P

Chapter 6. Web Services 159

Page 176: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

6.3 Web Services in WCTMEWeb Services in WCTME is a subset of the full Web Services specification. For example, WCTME supports a reduced set of data types. See JSR 172 for a description the limitations imposed in the J2ME environment.

The sample application created in this book gives two examples of Web Services in WCTME.

Figure 6-3 Accessing Web Services from a WCTME platform

The first is a local Web Service client accessing a remote Web Service.

The sample application uses a local Web Service client to access a remote Web Service for flight information. Periodically a thread queries the Web Service server for all flight information for all pending customers. This information is stored locally on the device in an a memory cache.

Because communications between the client device and the remote Web Service server might be sporadic, programming logic must handle any communication exceptions that occur.

Note: For more information about Web services consult the following references:

� WebSphere Version 6 Web Services Handbook: Development and Deployment. SG24-6461-00.

� WebSphere Version 5.1 Application Developer 5.1.1 Web Services Handbook. SG24-6891-00.

� IBM WebSphere Studio Application Developer 5.1.1 Information center.

� The Developer Works Web Services Web site:

http://www.ibm.com/developerworks/webservices

Web Service Client

Web Service

WCTME Platform

160 WCTME: Application Development and Case Study

Page 177: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 6-4 Accessing Web Services in a WCTME platform

The second example is a local Web Service client calling a local Web Service running inside of WCTME.

The sample application uses a local Web Service client to query for individual flights about which the local Web Service might or might not have information. Our local Web Service also formats the information for display in an HTML page.

6.4 Web Services sample scenarioThe sample application uses local Web Services to get up-to-date information about the flight on which the customer is arriving. This information is displayed in the application.

6.4.1 Web Services sample descriptionIn this section we create a bundle that exposes itself as a Web Service. The purpose of this Web Service will to return information about flights arriving at our airport.

We will also create another bundle that represents a client to the Web Service. The sample application will use this client bundle to retrieve information about the arriving customers. For our purposes, we will have the Web Service client return an HTML string that we will include directly in the displayed page of our application. If a flight is indicated to be delayed or cancelled, the returned HTML string will include a background color to show the flight’s status.

Because we want this application to run in a stand-alone mode we will initialize the bundle with properties that include a stand-alone flag. This flag will cause the Web Service bundle to contact the server or just create fake flight information status.

Local Web Service interfaceThese two lines represent the set of methods we want to implement with this bundle and expose as a Web Service:

Web Service Client

Web Service

WCTME Platform

Chapter 6. Web Services 161

Page 178: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

public boolean init(String[] keys, String[] elements);public String getFlightInfo(String flight);

Local Web Service Client interfaceThese three lines are the set of methods we want to implement with this client bundle:

boolean init(Properties properties);String getFlightInfoAsHTMLTableData(String flight);String getFlightInfo(String flight);

Our sample application will call the local Web Service client, which will call the local Web Service. This allows the client bundle to catch any Web Service exceptions and to format the Web Service information about flight status into the HTML table data that we want our application to use.

The properties that are passed to the local Web Service are used to configure it. This includes the destination address of the server side Web Service that our local Web Service will call if it is not operating in stand-alone mode.

6.4.2 Procedure for creating a Web ServiceFirst we need to create a Bundle Project to hold the Web Service classes.

1. If WebSphere Studio Site Developer is not running, click Start → Programs →IBM WebSphere Studio →Site Developer 5.1.x.

2. Open the SMF Perspective. Select Window →Open Perspective →SMF.

3. Make sure you are on the Package Explorer tab. Select File →New →Other.

4. Select Extension Services →Extension Services Bundle Project and click Next.

5. Enter the Project name FlightInfoWebServiceBundle and click Next.

6. In the Platform Profile field choose Extension Services: jclFoundation (5.7.0.). See Figure 6-5 on page 163.

Note: The local Web Service init method takes two arrays as the initialization parameters instead of a Properties object because SMF Web Services do not easily support complex Java objects.

162 WCTME: Application Development and Case Study

Page 179: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 6-5 Selecting the Web Services application service

7. Select the application services Web Services using Proxy Services check box. Click Next. See Figure 6-6 on page 164.

Chapter 6. Web Services 163

Page 180: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 6-6 Selecting other projects for this project’s build path

8. Click the Projects tab and select the check boxes next to ITSOCustomerBundle and ITSORentalsDatabaseServiceBundle. Click Next.

9. Select the check box next to Create Default Bundle Activator. Click Finish.

10.If you see a panel indicating the folder has changed, click Yes.

11.From the Package Explorer tab of the SMF Perspective, selected the FlightInfoWebServiceBundle Project you just created and right-click. From the pop-up menu select New →Package.

164 WCTME: Application Development and Case Study

Page 181: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

12.Enter the package name com.itso.flightInfo and click Finish.

13.Select the package just created, right-click. From the pop-up menu select New →Interface.

14.Enter the name FlightInfoWebService and click Finish.

15.Into the FlightInfoWebService.java window that opens, copy the following:

public boolean init(String[] keys, String[] elements);public String getFlightInfo(String flight);

16.Save the file.

With the next few steps, we generate the Web Service client to the server side Web Service. See Appendix C, “Sample server-side Web Service” on page 375 on building a Web Service.

See the Additional Materials appendix for instructions on how to download a sample version of the server side Web Service. To complete the next few steps, you can run that service side Web Service locally.

Tip: To help remove unresolved compiler errors, right-click in the source and select Source → Organize Imports.

Attention: Before completing the next section, make sure the server-side Web Service is running. Open a browser and point it to:

http://webservice_host:9080/DelayedFlightsWS/services/DelayedFlights/wsdl/DelayedFlights.wsdl

In this example, webservice_host is the host name of your Web Service host, and 9080 is the real port on which the service is running.

The browser should show the wsdl for the Web Service.

Note: If you will not be running the sample program with a real Web Service server, you can skip some steps and you will need to comment out some code in the local Web Service that calls the server-side web service.

Skip steps 17 and 18, the generation of the local client stub to the remote web service.

In step 21, comment out the reference to the private DelayedFlightsSoap_Stub stub that was not generated in steps 17 and 18. Also comment out any code that uses this stub.

Chapter 6. Web Services 165

Page 182: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

17.Select the package com.itso.flightInfo and, right-click. From the pop-up menu select New → Other → Mobile Web Services Client → Mobile Web Services Client and click Next.

Figure 6-7 Generating the Web service client for the server side Web service

18.Make sure the source folder field is pointing to the current project, enter the package name com.itso.flightInfo and the WSDL location of http://webservice_host:9080/DelayedFlightsWS/services/DelayedFlights/wsdl/DelayedFlights.wsdl. Remember, webservice_host is the host name of the Web Service host and 9080 is port number, as appropriate. Click Finish.

Now we can create the local Web Service that will call the remote Web Service stub we have just generated.

19.Select the package com.itso.flightInfo, and right-click. From the pop-up menu select New → Class.

20.Enter the name FlightInfoWebServiceImpl. Click the Interfaces: Add button, add the Interface FlightInfoWebService and click OK. Click Finish.

166 WCTME: Application Development and Case Study

Page 183: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

21.Replace the methods generated automatically with the following code in Example 6-1:

Example 6-1 Web Services method code

public static BundleContext context;static private int count = 0;private boolean standAlone = true;private ITSORentalsDatabaseService databaseService = null;private Hashtable flightInfoCache = new Hashtable();private WebServiceBackgroundThread backgroundThread;private long sleepTime = 1000 * 60 * 2; private String overrideAddress = null;

private DelayedFlightsSoap_Stub stub = null;

/** * */public FlightInfoWebServiceImpl() {

super();}

/* (non-Javadoc) * @see com.itso.flightInfo.FlightInfoWebService#init(java.lang.String[],

java.lang.String[]) */public boolean init(String[] keys, String[] elements) {

if ((keys != null) || (elements != null)) {//loop thru propertiesfor (int i = 0; i < keys.length; i++) {

if ((keys[i] != null) && (elements[i] != null)) {if (keys[i].equalsIgnoreCase("itso.webservice.standalone")) {

standAlone = elements[i].equalsIgnoreCase("true");} if (keys[i].equalsIgnoreCase("itso.webservice.sleeptime")) {

sleepTime = Integer.parseInt(elements[i]);}if

(keys[i].equalsIgnoreCase("itso.webservice.endpoint_address_property")) {overrideAddress = elements[i];

}}

}}

//remove any previously running threadsif (backgroundThread != null) {

Chapter 6. Web Services 167

Page 184: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

backgroundThread.terminate = true;backgroundThread.interrupt();backgroundThread = null;

}

// if we are not stand-alone, prepare for the server-side web // service and the thread that will access itif (!standAlone) {

//create client stub to server-side web service stub = new DelayedFlightsSoap_Stub();

// override WS properties as neededif (overrideAddress != null) {

String newAddress = "http://" + overrideAddress + "/DelayedFlightsWS/services/DelayedFlights";

stub.properties.put(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, newAddress);

} //Resolve Database serviceServiceReference dbRef =

context.getServiceReference(ITSORentalsDatabaseService.class.getName());

if (dbRef != null) {databaseService =

(ITSORentalsDatabaseService) context.getService(dbRef);System.out.println("Found DataBase service!");

//should already be initialized by servlet

// if we have the referenceif (databaseService != null) {

backgroundThread = new WebServiceBackgroundThread();backgroundThread.start();backgroundThread.setName("BackGround WebService Thread.");

}}

}

return true;}

* @see com.itso.flightInfo.flightInfoWebService#getFlightInfo(java.lang.String)

*/public String getFlightInfo(String flight) {

168 WCTME: Application Development and Case Study

Page 185: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

String results = flight;

if (standAlone) { //fake some datacount++;if ((count % 3) == 0) results = flight + " Delayed";if ((count % 6) == 0) results = flight + " Cancelled";if ((count % 10) == 0) results = flight + " Error";

} else {

//pull the latest data out of the "cache"String updateInfo = (String) flightInfoCache.get(flight);

if (updateInfo == null) results = flight + "!";else if (updateInfo.equalsIgnoreCase("e")) results = flight + "

Error";else if (updateInfo.equalsIgnoreCase("d")) results = flight + "

Delayed";else if (updateInfo.equalsIgnoreCase("c")) results = flight + "

Cancelled";}

/* (non-Javadoc)return results;}

/** * A background thread to gather pending flight information. */class WebServiceBackgroundThread extends Thread implements Runnable {

public boolean terminate = false;

/* (non-Javadoc) * @see java.lang.Runnable#run() */public void run() {

//every so often check the server-side web service and update the local cached data.

for (;;) {Vector pendingCustomers = null;String[] pendingArray = null;String[] resultsArray = null;

// get all the pending customers flight info to query from serverif (databaseService != null) pendingCustomers =

databaseService.getPendingCustomers();

Chapter 6. Web Services 169

Page 186: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

if ((pendingCustomers != null) && (pendingCustomers.size() > 0 )) {

//create string array to pass to server-side web servicependingArray = new String[pendingCustomers.size()];for (int i = 0;i< pendingArray.length;i++) {

Customer c = (Customer) pendingCustomers.get(i);pendingArray[i] = c.getFlightInfo();

}

//call server-side web serviceresultsArray = null;if (stub != null) {

try {System.out.println("Back ground web service thread

calling server side web service");resultsArray = stub.getDelayedFlights(pendingArray);

} catch (RemoteException e1) {System.out.println("RemoteException on remote web

service call - no new flight info data");} catch (JAXRPCException e1) {

System.out.println("JAXRPCException on remote web service call - no new flight info data");

}}

//put results into "cache"flightInfoCache = new Hashtable(); //move inside if, if you

want the last good dataif (resultsArray != null) {

for (int i = 0;i< resultsArray.length;i++) {flightInfoCache.put(pendingArray[i], resultsArray[i]);

}}

}

try {Thread.sleep(sleepTime);

} catch (InterruptedException e) {}if (terminate) return;

}}

}

22.Organize Imports and Save the file.

The code in Example 6-1 includes a private class. If the local Web Service is not running in stand-alone mode, a background thread is created and started that

170 WCTME: Application Development and Case Study

Page 187: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

calls the server-side Web Service and asks for updated information for all pending customers’ flights. To get the list of pending customers’ flights, this thread accesses the database service.

23.Open the ExtensionServicesBundleActivator.java file (in the default package) and add the following to the class:

private BundleContext context;

24.Add the interface Runnable to the class definition

25.Add the code in Example 6-2 at the end of the start() method:

Example 6-2 Append the start() method

this.context = context;FlightInfoWebServiceImpl.context = context;Thread t = new Thread(this);t.start();t.setName("Find Provider Thread.");

26.Add the methods in Example 6-3 to the end of the class:

Example 6-3 Class methods

private WebServiceProvider getProvider(BundleContext context) {String providerName = "com.ibm.pvcws.osgi.proxy.WebServiceProvider"; ServiceReference ref =

context.getServiceReference(providerName);if (ref == null) {

return null;}WebServiceProvider provider =(WebServiceProvider) context.getService(ref);return provider;

}

/* (non-Javadoc) * @see java.lang.Runnable#run() */public void run() {

Hashtable props = new Hashtable(3);

props.put("com.ibm.wstkmd.bundle", "");props.put(Constants.SERVICE_PID, "flightInfo");

context.registerService(

Chapter 6. Web Services 171

Page 188: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

FlightInfoWebService.class.getName(),new FlightInfoWebServiceImpl(),props);

WebServiceProvider provider = getProvider(context);// make sure it resolveswhile (provider == null ) {

try {System.out.println("Provider was not available yet!; Trying again

in 1 secs...");Thread.sleep(1000);

} catch (InterruptedException ie) {}provider = getProvider(context);

}

provider.exportPid("flightInfo");

}

This code exposes the Web Service to other bundles. Because the WebServiceProvider reference will not be available immediately, we have created a thread that will look for this reference until it is available. It will be available when all the prerequisite bundles have been started. That should only take a few seconds.

27.Save the file.

28.From the Package Explorer tab of the SMF Perspective, select the FlightInfoWebServiceBundle Project you created and expand it down to the file META-INF/MANIFEST.MF. Double-click the file name MANIFEST.MF.

29.This opens the MANIFEST.MF editor. Scroll down to Export Services and select Add...

30.Select the service com.itso.flightInfo.FlightInfoWebService and click OK.

31.Expand the section Export Packages and select Add...

32.Select the package com.itso.flightInfo and click OK.

33.Expand the section Import Packages and select Add...

Tip: To help remove unresolved compiler errors, right-click in the source and select Source →Organize Imports.

If prompted, choose the Constants class in the org.osgi.framework package.

172 WCTME: Application Development and Case Study

Page 189: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

34.Select the packages com.itso.rentals and com.itso.rentals.database and click OK.

35.Expand the section Import Services and select Add...

36.Select the service com.itso.rentals.database.ITSORentalsDatabaseService and click OK.

37.Save the file.

6.5 Creating the FlightInfoWebServiceClient BundleThe bundle we created above is a Web Service. Now we will create a client bundle that calls this Web Service.

To perform this step, the Web Service created in the previous section needs to be running:

1. If it is not running, start the SMF bundle server. For help see section 3.4, “Starting the SMF Bundle Server” on page 70.

2. Submit the FlightInfoWebServiceBundle to the bundle server. For help see section 3.8, “Submitting bundles to the SMF bundle server” on page 77.

3. If it is not running, start the SMF runtime. For help see section 3.5, “Starting the SMF Runtime” on page 73.

4. In the Package Explorer pane, select the SMF Bundle Servers tab. Under the Admin@localhost:8080/smf, expand the Bundles tree.

5. Right-click the FlightInfoWebServiceBundle bundle, and select Install.

The local Web Service bundle and any bundles it requires will be installed into the runtime and the bundles will be started.

Note: The packages com.itso.rentals and com.itso.rentals.database might already have been added automatically, or you can press the Compute button to fill in the list.

Attention: Before completing the next section, make sure the Web Service is running. Open a browser and point it to http://localhost:6080/ws/pid/flightInfo?wsdl. The browser should show the wsdl for the Web Service.

Chapter 6. Web Services 173

Page 190: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

6.5.1 ProcedureTo implement the service, perform the following steps:

1. If WebSphere Studio Site Developer is not running, click Start → -> Programs →IBM WebSphere Studio →Site Developer 5.1.x.

2. Open the SMF Perspective. Select Window →Open Perspective →SMF.

3. Make sure you are on the Package Explorer tab. Select File → New → Other.

4. Select Extension Services → Extension Services Bundle Project and Click Next.

5. Enter the Project name FlightInfoWebServiceClientBundle and click Next. See Figure 6-8 on page 175.

174 WCTME: Application Development and Case Study

Page 191: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 6-8 Selecting the Web services client application service

6. In the Platform Profile field, choose Extension Services: jclFoundation (5.7.0.).

7. Select the check box next to the application services Web Services using generated Stub classes. Click Next.

8. Click Next.

9. This client does not need a bundle activator, so do not check box next to Create Default Bundle Activator. Click Finish.

Chapter 6. Web Services 175

Page 192: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

10.If you see a panel indicating the folder has changed, click Yes. See Figure 6-9.

11.From the Package Explorer tab of the SMF Perspective, select the FlightInfoWebServiceClientBundle Project you just created and right-click. From the pop-up menu select New →Package.

12.Enter the package name com.itso.flightInfo.client and click Finish.

13.Select the package just created and right-click. From the pop-up menu select New →Other → Mobile Web Services Client → Mobile Web Services Client and click Next.

Figure 6-9 Generating the Web Service client for the local Web Service

14.Make sure the source folder field is pointing to the current project, enter the package name com.itso.flightInfo.client and enter the WSDL location of http://localhost:6080/ws/pid/flightInfo?wsdl, then Finish.

15.Expand the package and select the file Stub_Soap.java.

16.Open the file and find this line of code:

176 WCTME: Application Development and Case Study

Page 193: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

properties.put(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, "http://x.x.x.x:6080/ws/pid/flightInfo");

In the code, x.x.x.x is your IP address. Change the IP address referenced to 127.0.0.1.

The Web Service will be running on our device, and not on your development system. This change will cause the stub to access the local device for this service. If this client were to reference a Web Service running on a server, that IP address would need to point to that system.

17.Save the file.

18.Select the file Stub_Soap.java, right-click and select Refactor →Rename...

19.Rename the file to FlightInfo_Stub and click OK. This step is optional, but makes it easier to identify in our project.

20.Select the package com.itso.flightInfo.client, and right-click. From the pop-up menu select New →Interface.

21.Enter the name ITSORentalsWebServiceClient and click Finish.

22.Into the ITSORentalsWebServiceClient.java window that opens, copy the following:

boolean init(Properties properties);String getFlightInfoAsHTMLTableData(String flight);String getFlightInfo(String flight);

23.Save the file.

24.Select the same package, and right-click. From the pop-up menu select New →Class.

25.Enter the name ITSORentalsWebServiceClientImpl. Click the Interfaces: Add button. Add the Interface ITSORentalsWebServiceClient and click OK, then click Finish.

26.Replace the methods generated automatically with the code in Example 6-4:

Example 6-4 Class methods

private FlightInfo_Stub stub = new FlightInfo_Stub();

/** *

Tip: To help remove unresolved compiler errors, right-click in the source and select Source →Organize Imports.

Chapter 6. Web Services 177

Page 194: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

*/public ITSORentalsWebServiceClientImpl() {

super();}

/* (non-Javadoc) * @see

com.itso.flightInfo.client.ITSORentalsWebServiceClient#init(java.util.Properties)

*/public boolean init(Properties properties) {

//convert Properties into 2 arrays of StringsString[] keys = null;String[] values = null;

if (properties != null ){int size = properties.size();keys = new String[size];values = new String[size];Enumeration key = properties.keys();Enumeration value = properties.elements();for (int i = 0; i< size ; i++) {

keys[i] = (String) key.nextElement();values[i] = (String) value.nextElement();

}}

try {stub.init(keys, values);

} catch (RemoteException e2) {System.out.println("RemoteException - trying to init local web

service");} catch (JAXRPCException e2) {

System.out.println("JAXRPCException - trying to init local web service");

}return true;

}

/* (non-Javadoc) * @see

com.itso.flightInfo.client.ITSORentalsWebServiceClient#getFlightInfo(java.lang.String)

*/public String getFlightInfo(String flight) {

String results = null;try {

178 WCTME: Application Development and Case Study

Page 195: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

results = stub.getFlightInfo(flight);} catch (RemoteException e) {

System.out.println("RemoteException - trying to call local web service");

} catch (JAXRPCException e) {System.out.println("JAXRPCException - trying to call local web

service");}return results;

}

/* (non-Javadoc) * @see

com.itso.flightInfo.client.ITSORentalsWebServiceClient#getFlightInfoAsHTMLTableData(java.lang.String)

*/public String getFlightInfoAsHTMLTableData(String flight) {

StringBuffer results = new StringBuffer();try {

results.append("<TD align=\"center\"");

String tempResults = stub.getFlightInfo(flight);if (tempResults != null) {

if (tempResults.indexOf("Error") != -1) {results.append(" bgcolor=\"#c0c0c0\""); // grey

} else if (tempResults.indexOf("Cancelled") != -1) {results.append(" bgcolor=\"#ff0000\""); // red

} else if (tempResults.indexOf("Delayed") != -1) {results.append(" bgcolor=\"#ffff00\""); // yellow

} else if (tempResults.indexOf("!") != -1) {results.append(" bgcolor=\"#ff8000\""); // orange

}}

} catch (RemoteException e1) {System.out.println("RemoteException2 - trying to call local web

service");} catch (JAXRPCException e1) {

System.out.println("JAXRPCException2 - trying to call local web service");

} finally {results.append(">" + flight + "</TD>");

}return results.toString();

}

27.Organize Imports and Save the file.

Chapter 6. Web Services 179

Page 196: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

28.From the Package Explorer tab of the SMF Perspective, select the FlightInfoWebServiceClientBundle Project you created and expand it down to the file META-INF/MANIFEST.MF. Double-click the file name MANIFEST.MF.

29.This opens the MANIFEST.MF editor. Scroll down to Export Packages.

30.Expand the section Export Packages and select Add...

31.Select the package com.itso.flightInfo.client and click OK.

32.Expand the section Import Services and select Add...

33.Select the service com.itso.flightInfo.FlightInfoWebService and click OK.

34.Save the file.

6.5.2 Extending the Web Services Tester bundleIn this section we add to the Tester bundle so that it uses the Web Service and client bundles we just created.

35.Select the ITSORentalsTesterBundle project, then right-click and select Properties. Select Java Build Path.

36.From the Projects tab, select the FlightInfoWebServiceClientBundle () check box. Click OK.

37.Open the ITSORentalsTester.java file and add the code in Example 6-5 at the end of the init() method:

Example 6-5 Tester bundle extension

//basic test of flightInfo serviceSystem.out.println("\nTesting FlightInfo Web Service Client Bundle: ");

ITSORentalsWebServiceClientImpl i = new ITSORentalsWebServiceClientImpl();

i.init(null);System.out.println("Results of checking on flight ITSO 1982: " +

i.getFlightInfo("ITSO 1982"));System.out.println("Results of checking on flight ITSO 1982

AsHTMLTableData: " + i.getFlightInfoAsHTMLTableData("ITSO 1982"));

38.Organize Imports and Save the file.

39.Open the MANIFEST.MF file. Scroll down to Import Packages.

Note: By passing a null reference during the Web Service init method, we will be running with defaults and in stand-alone mode.

180 WCTME: Application Development and Case Study

Page 197: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

40.Expand the section Import Package and select Add...

41.Select the package com.itso.flightInfo.client and click OK.

42.Save the file.

You should now be able to test the FlightInfoWebServiceClientBundle with the ITSORentalsTesterBundle.

6.5.3 Messaging Web Service reviewFirst we created a Web Service bundle project. That local Web Service calls a remote Web Service using a client stub, running on a background thread. That stub was generated using a Studio wizard. This local Web Service periodically retrieves flight information from the server-side Web Service.

Then we created a Web Service client bundle project to call the local Web Service and format the retrieved flight information into a format appropriate for our sample application. Again the client stub was generated using a wizard.

As before, we modified the manifest files to export and import the necessary services and interfaces. We again went back to the tester bundle and modified it to access the local Web Service using the client bundle, and updating its manifest file to tell the runtime that the tester bundle now requires the new Web Service client bundle.

We still will have to submit the new and modified bundles to the bundle server and then install them into the runtime, so that we can successfully run the updated tester bundle.

The new local Web Service defaults to stand-alone mode, but using the properties passed to it through the client bundle, we can configure which remote Web Services server should be contacted for the most current flight information.

6.5.4 Testing the Web Service and Web Service client bundlesIn order to test the flight information Web server and Web Service client bundles, perform the following steps:

1. If it is not running, start the SMF bundle server. For help see section 3.4, “Starting the SMF Bundle Server” on page 70.

Note: The package com.itso.flightInfo.client might already have been added automatically, or you can press the Compute button to fill in the list.

Chapter 6. Web Services 181

Page 198: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

2. Submit the FlightInfoWebServiceBundle, FlightInfoWebServiceClientBundle and the updated ITSORentalsTesterBundle to the bundle server. For help see section 3.8, “Submitting bundles to the SMF bundle server” on page 77.

3. If it is not running, start the SMF runtime. For help see section 3.5, “Starting the SMF Runtime” on page 73.

4. Uninstall all the sample bundles previous installed into the runtime. Select each/all of those bundles, then right-click and select Uninstall.

5. In the Package Explorer pane, select the SMF Bundle Servers tab. Under the Admin@localhost:8080/smf, expand the Bundles tree.

6. Right-click ITSORentalsTesterBundle, and select Install.

The test bundle and any bundles it requires will be installed into the runtime and the bundles will be started. The output of the test bundle will display in the console.

Review the output of the tester program in the console and verify that the tester bundles was able to access the Web Service.

6.5.5 Web Services troubleshootingIf you call the Web Service client before the Web Service is completely running, you will get an exception. Stop the test bundle, then start the test bundle.

182 WCTME: Application Development and Case Study

Page 199: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Chapter 7. HTTP services, servlets and Java server pages

In this chapter, we discuss using a device as an HTTP server. This allows companies to use their existing servlets and Java server pages (JSPs) almost unchanged on devices.

7

© Copyright IBM Corp. 2005. All rights reserved. 183

Page 200: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

7.1 OverviewBefore we see how we use WCTMe to build Web applications, we will discuss Web applications in general.

7.1.1 Servlets and JSPsServlets are Java programs which typically run on a web server. They act as extensions to HTML pages and can generate dynamic content. They are similar to CGI (Common Gateway Interface) programs, but offer all the advantages of the Java language. They can do almost anything a Java application can do, including accessing databases, setting up socket connections, accessing Enterprise Java Beans (EJBs) and so on. Servlets often act as controllers of complex business logic in processing requests that come in from Web pages.

Java Server Pages(JSPs) are HTML pages that can include Java program code and logic. They can access other Java programs using Java beans. When combined with servlets, JSPs act as the view component in the model-view-controller paradigm. Servlets act as the controllers.

7.1.2 Web applicationsA Web application consists of a collection of HTML pages, servlets, JSPs, image files and supporting Java programs. A Web server, such as WebSphere Application Server, combines these into a single file, known as a WAR (Web ARchive) file.

Each Web application is self contained. It contains all the files it needs under a single directory. The application is identified by its context root. This is the name that users will use to access the application. For example, if an application has a context root of ITSORentals, the user will call pages from the application by entering:

http://www.myhost.com/ITSORentals

7.1.3 Web applications in WCTMEIn order to develop web applications in WCTME, you will have to install WebSphere Studio Device Developer as a plugin to either WebSphere Studio Application Developer or WebSphere Studio Site Developer.

Tip: Context roots are case sensitive.

184 WCTME: Application Development and Case Study

Page 201: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

The SMF Web container supports the Servlet 2.3 and JSP 1.2 specifications with minor differences. Therefore, you can use standard Web application development tools and methodologies. However, you must ensure that you develop against a JRE and library set that matches the runtime environment of the targeted SMF. For example, if a Web application will run within an SMF instance running on J2ME Foundation, you should develop against J2ME Foundation libraries.

7.2 Using HTTP Services in WCTMEIn this section we discuss using HTTP services, including building a Web application and using it in an SMF environment.

7.2.1 Building a Web applicationIn order to create a new Web application, perform the following steps:

1. Navigate to the Web perspective.

2. Create a new Web application by selecting New →Dynamic Web Project from the File menu.

3. Enter the name of the application.

4. Click the Configure Advanced Options check box, and then click the Next button.

5. In the next frame, you can configure Java 2 Enterprise Edition (J2EE) settings. The most important is the context root, because this is how your users will reach your application from their browsers. Enter the context root, and click Next.

6. On the next frame, you can select extra features that your Web application will use, including struts and JSP tag libraries. For more information about these subjects, see WebSphere Studio Application Developer Version 5 Programming Guide, SG24-6957. Click Next if you want to configure default page templates for your Web application, or simply click Finish.

Once you have created the skeleton for your application, you will have to create the Java files for the servlets, the JSPs and other HTML files, as well as any other auxiliary files. You do this from the Project Navigator pane in the Web perspective. For example, to create a servlet, perform the following steps:

1. Select the Java Resources under you project, click New → Package, and create the package.

Chapter 7. HTTP services, servlets and Java server pages 185

Page 202: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

2. Select the package and click New →Servlet. Follow the steps in the wizard to create the parameters for your servlet.

3. To create JSPs, HTML files and other resources for the application, right-click the Web Content tab under the project, select New and the type of resource you want to create.

You can also configure your Web application by editing the Web Deployment Descriptor. This allows you to add and configure JSPs and Servlets, as well as defining the welcome and error pages for your application.

7.2.2 Converting a Web application to an SMF bundleTo run a Web application under the SMF Web container, you must translate the Web application into an OSGi bundle called a Web application bundle, or WAB. SMF provides a WAB command line utility to perform this translation. The following simple example translates Web application myWebapp.war using the wab utility.

wab myWebapp.war

You can also use WebSphere Studio Device Developer to convert the Web application. You can make a copy of your Web application as you copy it, so that the original application is left unchanged. To do this, perform the following steps:

1. Select New → Other → Extension Services → Convert Web to Extension Services Project. You will see a list of Web projects in your workspace.

2. Select the one you want to convert. If you want to make a copy, click the check box, and enter the name of the copied project. Click Next.

3. You will see a pane which allows you to select the JRE and the application services that your application will use. Generally you will select Extension Services: jclFoundation for a JRE if you are going to run in a J2ME environment. Click Finish to generate the SMF bundle.

If you do not select the application services your application will use, such as DB2 Everyplace, you can add them later, but it is much easier to do it here.

7.2.3 Using SMF services from a Web applicationIf your Web application needs to access the services of other SMF bundles, you will need to make the BundleContext available to the applications. You can do this by modifying the bundle services activator created when you converted the Web application to an extension services project.

The default bundle activator is in the default package. You can find it in the Extension Services Content folder under the Java Resources folder. The start

186 WCTME: Application Development and Case Study

Page 203: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

method receives a BundleContext object as a parameter. You can store a reference to the bundle context anywhere that your application code can access it. For example, you could create a class with static get and set methods. The start method would call the setContext method. The application code would call the getContext method to retrieve the context.

7.3 Sample Web applicationIn this section we build a simple Web application and convert it into an ESWE bundle.

It is not necessary to create a separate Web application and convert it. However, this tool can be very useful if you already have Web applications and want to convert them to run in the WCTME environment.

After we convert the Web application, we will add the logic to access the other bundles that we have created in previous chapters.

We want our application to display a list of customers arriving and those that have arrived. We will create a table for each list and put a check box next to each name list, so that it can be used to move that customer to the next state.

We will also need a button to sync the local data with the server and another to reset the database when we are running in stand-alone mode.

Later we will add a Login panel and a Config panel so that we have a complete sample application.

7.3.1 Web application descriptionIn this section we will create a simple Web application. This represents a mock-up of the final application.

These steps will create a servlet that can be deployed on a server. You must be using WebSphere Studio Site Developer or WebSphere Studio Application Developer to load the servlet into a WebSphere Test environment. We will not be deploying this servlet to a real server, but will convert it to run in a bundle.

7.3.2 ProcedureFirst we need to create a Web Project to hold the servlet and jsp file.

1. If WebSphere Studio Site Developer is not running, click Start → Programs → IBM WebSphere Studio → Site Developer 5.1.x.

Chapter 7. HTTP services, servlets and Java server pages 187

Page 204: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

2. Select File → New → Project → Web → Dynamic Web Project and click Next. See Figure 7-1.

Figure 7-1 Creating a new Web project

3. Enter ITSOCheckInAndSyncWebProject for the Project name, as in Figure 7-2 on page 189. Make sure to check the Configure advanced options box and then click Next.

188 WCTME: Application Development and Case Study

Page 205: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 7-2 Naming a new Web project

4. See Figure 7-3 on page 190. Change the context root to ITSORentals. You can rename the EAR project field name, but we will not be using it to deploy to a real server. Click Next.

Chapter 7. HTTP services, servlets and Java server pages 189

Page 206: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 7-3 Setting the context root

5. On the Features Page (Figure 7-4 on page 191), select the Tag Libraries for accessing JSP objects and click Finish.

Note: See the Help documentation to see which features are supported in the SMF environment.

190 WCTME: Application Development and Case Study

Page 207: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 7-4 Selecting JSP tags

6. Accept the suggestion to switch to the Web Perspective.

The Web project is created and added to the workspace. Now we will add the components of our simple Web application.

7. Right-click the project you just created and select New →Servlet. See Figure 7-5 on page 192.

Chapter 7. HTTP services, servlets and Java server pages 191

Page 208: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 7-5 Creating a new servlet

8. Enter the package name of com.itso.servlet and the class name of CheckInAndSync. Click Finish.

9. Into the CheckInAndSync.java window that opens, copy Example 7-1:

Example 7-1 Web application components

public void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {

Enumeration enum = req.getParameterNames();while (enum.hasMoreElements()){

String attrib = (String) enum.nextElement();String aValue = (String) req.getParameter(attrib);System.out.println("attrib= "+ attrib + " Value=" + aValue);

}

//if Checked Button pressedif(req.getParameter("CheckButton") != null) {

192 WCTME: Application Development and Case Study

Page 209: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Enumeration params = req.getParameterNames();while (params.hasMoreElements()){

String attrib = (String) params.nextElement();if (attrib.startsWith("check_in_")) {

String renter = attrib.substring(9);System.out.println("Checkin in user = "+ renter);

}if (attrib.startsWith("check_out_")) {

String renter = attrib.substring(10);System.out.println("Checkin out user = "+ renter);

}}

}

//if Sync Button pressedif(req.getParameter("SyncButton") != null) {

// perform a syncSystem.out.println("syncing");

}

ServletContext context = this.getServletContext();RequestDispatcher rd =

context.getRequestDispatcher("/CheckIn.jsp");rd.forward(req, resp);

}

public void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {

doGet(req, resp);}

10.Save the file. Our servlet forwards the request to a jsp file to display the results.

11.Expand the project down to the folder WebContent. Select WebContent, right-click and select New →JSP File. See Figure 7-6 on page 194.

Tip: To help remove unresolved compiler errors, right-click in the source and select Source →Organize Imports.

If prompted, choose the Enumeration class in the java.util package.

Chapter 7. HTTP services, servlets and Java server pages 193

Page 210: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 7-6 Creating a new JSP file

12.Enter the file name CheckIn and click Finish.

13.In the CheckIn.jsp window that opens (and using the Source editor), change the <title> to ITSO Vehicle Rental App and replace the <body> of the document with the following in Example 7-2:

Example 7-2 Web application table code

<BODY><FORM method="post" action="/ITSORentals/CheckInAndSync"><IMG

border="0" src="Logo.jpg" width="176" height="69">

<TABLE width="240"><TBODY>

<TR>

194 WCTME: Application Development and Case Study

Page 211: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

<TD align="left">Place holder for sync messages</TD></TR><TR>

<TD align="left" valign="bottom"><B>Arriving Customers</B></TD><TD align="right" valign="middle"><INPUT type="submit"

name="SyncButton" value="Sync"></TD></TR>

</TBODY></TABLE>

<TABLE width="240" border="2" cellpadding="0" cellspacing="0"><TBODY>

<TR bgcolor="#c0c0c0"><TD><B>Name</B></TD><TD align="center"><B>Photo</B></TD><TD align="center"><B>Flight<BR>Info</B></TD><TD align="center" width="55"><B>Arrived</B></TD>

</TR><%/* Display the vector of all the pending customers/contracts here*/%><TR>

<TD>Lastname, <BR>Firstname</TD><TD align="center" valign="middle"><IMG border="0"

src="a_dynamic_picture_of_customer" width="75" height="75"></TD><TD align="center">Some Info</TD><TD align="center" valign="middle"><INPUT type="checkbox"

name="check_in_CONTRACTNUMBER" value="true"></TD></TR>

</TBODY><TBODY></TBODY>

</TABLE>

<TABLE width="240"><TBODY>

<TR><TD align="left" valign="bottom"><B>On Bus</B></TD><TD align="right" valign="middle"><INPUT type="submit"

name="CheckButton" value="Refresh / Submit"></TD></TR>

</TBODY><TBODY></TBODY>

</TABLE>

<TABLE width="240" border="2" cellpadding="0" cellspacing="0"><TBODY>

<TR bgcolor="#c0c0c0"><TD><B>Name</B></TD><TD align="center"><B>Vehicle<BR>

Chapter 7. HTTP services, servlets and Java server pages 195

Page 212: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Location</B></TD><TD align="center" width="55"><B>Exited</B></TD>

</TR><%/* Display the vector of all the arrived customers/contracts here*/%><TR>

<TD>Lastname, <BR>Firstname</TD><TD align="center" valign="middle">Some Info</TD><TD align="center" valign="middle"><INPUT type="checkbox"

name="check_out_CONTRACTNUMBER" value="true"></TD></TR>

</TBODY></TABLE><INPUT type="submit" name="ResetButton" value="Reset Demo"> <INPUT

type="submit" name="ConfigButton" value="Config"> <INPUT type="submit"name="LogoutButton" value="Logout"></FORM>

</BODY>

14.Save the file.

The main application panel is designed for display on a PocketPC.

15.If you have a Logo.jpg file (Figure 7-7 on page 197), import it into the project’s WebContent directory. Select the project’s WebContent folder and right-click. From the pop-up menu select Import... and then File System, Next. Find the file, then select Finish.

Attention: You will not automatically have the Logo.jpg file referenced above. See the Appendix D, “Additional materials and how to obtain them” on page 403 about how to get the Logo.jpg file from IBM.

196 WCTME: Application Development and Case Study

Page 213: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 7-7 Importing a logo into our Web application

If you change to the Design editor, the JSP file should look as illustrated in Figure 7-8 on page 198.

Chapter 7. HTTP services, servlets and Java server pages 197

Page 214: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 7-8 Design editor view of simple JSP

We have now created a simple Web application, a servlet and jsp. Remember this is just a mock-up of the sample application to be completed in a later section.

16.Navigate to the Java Resources. Select the CheckInAndSync.java file, right-click and select Run on Server.... See Figure 7-9 on page 199.

198 WCTME: Application Development and Case Study

Page 215: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 7-9 Run on Server

17.On the Server Selection panel we are going to Create a new server. In the Server Type field, select WebSphere version 5.1, Test Environment. Click Finish.

This should start the WebSphere Test Environment, launch the Web browser and point the web browser to the jsp file (http://localhost:9080/ITSORentals/CheckInAndSync). At this point, we have a running Web application that does not have any real data in it. Some of the buttons work, but do not call any real functions. In the next section we will:

Chapter 7. HTTP services, servlets and Java server pages 199

Page 216: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

� Convert this Web application into a bundle

� Add the code that accesses the local database bundle, calls the local Web service and sends an MQe message when the bus driver checks in the customer.

7.4 Converting from a J2EE Web application to a bundleIn this section, we convert the J2EE Web application into a bundle. This will allow the Web application to run as a true servlet in the SMF environment.

1. If WebSphere Studio Site Developer is not running, click Start → Programs → IBM WebSphere Studio →Site Developer 5.1.x.

2. Open the Web Perspective, or the SMF Perspective.

3. From the Project manager (or Package Explorer) view select File → New → Other.

4. As in Figure 7-10 on page 201, select Extension Services → Convert Web to Extension Services Project and Click Next.

200 WCTME: Application Development and Case Study

Page 217: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 7-10 Converting the Web project into a Web application bundle

5. As in Figure 7-11 on page 202, Select the project ITSOCheckInAndSyncWebProject. Make sure to check the Copy before creating box and enter the new name ITSORentalsWebApplicationBundle. Click Next.

Chapter 7. HTTP services, servlets and Java server pages 201

Page 218: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 7-11 Converting the Web project

6. In the Platform Profile field (Figure 7-12 on page 203) choose Extension Services: jclFoundation (5.7.0.).

202 WCTME: Application Development and Case Study

Page 219: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 7-12 Converting the Web project

7. Click Finish.

You might have noticed that you did not get to pick some other options that you get when you create a bundle from scratch. We will need to add the other required projects to the build path manually, but a bundle activator file was created by default.

Before we fix the build path and add the remaining code to our application, we need to run the generated bundle.

Chapter 7. HTTP services, servlets and Java server pages 203

Page 220: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

8. Navigate into the ITSORentalsWebApplicationBundle project just created and select the CheckInAndSync.java file, right-click and select Run on Server.... See Figure 7-13.

Figure 7-13 Run on local server

9. On the Server Selection panel, we are going to Create a new server. In the Server Type field, select the Extension Services, Local Server. Click Finish.

Important: Stop the bundle server and the runtime if they are running. Also, stop the WebSphere Test Environment server if it is still running

204 WCTME: Application Development and Case Study

Page 221: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

The local bundle server will start along with the runtime and the Web browser will open displaying the servlet.

7.4.1 Completing the sample applicationNow that we have the servlet running and, have implemented the other services for our application, we just need to complete the code calling those services.

The code that you will be using below calls the various services and packages completed in previous chapters. For these to resolve, we need to modify the (WebSphere Studio Site Developer) project path.

10.Select the ITSORentalsWebApplicationBundle project, right-click and select Properties, then select Java Build Path.

11.From the Projects tab, select the check box next to:

– FlightInfoWebServiceClientBundle – ITSOCustomerBundle – ITSORentalsDatabaseServiceBundle – ITSORentalsMQeServiceBundle

Click OK.

12.Open the ExtensionServicesBundleActivator.java file. Look in the Extension Services Content folder and in the default package. Add the following code at the end of the start() method:

CheckInAndSync.context = context;

Note: You might have noticed that we started this bundle using a technique different than starting the tester bundle or the J2SE Web application.

Although ITSORentalsWebApplicationBundle is a bundle, as a Web application it is not in a form ready to be deployed directly to the SMF Runtime.

The Run on Server... step will process the bundle, submit it to the bundle server and install it into the runtime. Once installed, you only need to restart the runtime to access the Web application again.

This Run on Server... process will also be familiar to Web application developers who have used WebSphere Studio Site Developer.

Note: If the bundle server and the runtime are still running, stop them while you edit the files.

Chapter 7. HTTP services, servlets and Java server pages 205

Page 222: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

We are copying the bundle context to the servlet so that we can resolve it at run time.

13.Save the file.

14.Open the file CheckInAddSync.java in the Java Source folder and replace the class content with the following code in Example 7-3:

Example 7-3 CheckInAddSync.java class code

public static BundleContext context;private ITSORentalsDatabaseService databaseService = null;private ITSORentalsMQeService mqeService = null;private ITSORentalsWebServiceClientImpl flightInfoWebserviceClient = null;

// private ITSORentalsDeviceManagementService dmService = null;

final static String PROPERTIES = "itso_rentals.properties";protected Properties properties = null;

/*** @see javax.servlet.http.HttpServlet#void

(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)*/public void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

HttpSession session = req.getSession( true );

//This servlet also serves up pictures for the applicationString s = req.getParameter("Blob");if (s != null) {

System.out.println("Blob request for userid " + s);returnBlob(resp, s);return;

}

Tip: To help remove unresolved compiler errors, right-click in the source and select Source →Organize Imports. There will be an unresolved reference until you update the servlet code.

Note: If you have skipped any of the previous chapters, you will need to modify the sample application so that it no longer requires the missing bundles.

206 WCTME: Application Development and Case Study

Page 223: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

//if Login button pressedif(req.getParameter("LoginButton") != null) {

// perform a loginSystem.out.println("login");if (!verifyLogin(req, resp)) {

forward2Page(req, resp, "/Login.jsp");return;

} else {session.setAttribute("LoggedIn", "yes");

}}

//if Logout button pressedif(req.getParameter("LogoutButton") != null) {

// perform a logoutSystem.out.println("logout");session.setAttribute("LoggedIn", "no");

}

//has the user not logged in yet or just logged offString loggedIn = (String) session.getAttribute("LoggedIn");if ((loggedIn == null) ||

((loggedIn != null) && (!loggedIn.equalsIgnoreCase("yes")))) {forward2Page(req, resp, "/Login.jsp");return;

}

//if Config button pressedif(req.getParameter("ConfigButton") != null) {

// perform a loginSystem.out.println("configure");req.setAttribute("Properties", properties);forward2Page(req, resp, "/Configure.jsp");return;

}

//if Insert Pictures button pressedif(req.getParameter("InsertButton") != null) {

System.out.println("Inserting pictures into the local database");databaseService.insertPictures();forward2Page(req, resp, "/Configure.jsp");return;

}

//if Create Sample Data button pressedif(req.getParameter("CreateButton") != null) {

System.out.println("Inserting sample data into the local database");

databaseService.createLocalData();

Chapter 7. HTTP services, servlets and Java server pages 207

Page 224: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

forward2Page(req, resp, "/Configure.jsp");return;

}

//if Set button pressedif(req.getParameter("SetButton") != null) {

// set demo propertiesSystem.out.println("set");processConfig(req);

}

//if Reset button pressedif(req.getParameter("ResetButton") != null) {

// perform a resetSystem.out.println("reseting");databaseService.resetDemo();

}

//if Sync button pressedif(req.getParameter("SyncButton") != null) {

// perform a syncSystem.out.println("syncing");//call sync -- set response as message for JSP to displayreq.setAttribute("SyncMessage", databaseService.sync(properties));

}

//if Update button pressedif(req.getParameter("UpdateButton") != null) {

// perform an updateSystem.out.println("updating");//call update -- set response as message for JSP to display

// if (dmService != null)// req.setAttribute("SyncMessage", dmService.updateApplication());

}

//if Refresh/Submit button pressedif(req.getParameter("CheckButton") != null) {

Enumeration params = req.getParameterNames();while (params.hasMoreElements()){

String attrib = (String) params.nextElement();if (attrib.startsWith("check_in_")) {

String contractID = attrib.substring(9);System.out.println("Check in customer with contract = "+

contractID);

//update local status for contract customerdatabaseService.update2Arrived(contractID);

208 WCTME: Application Development and Case Study

Page 225: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

//send message to MQe servermqeService.customerArrived(contractID);

}if (attrib.startsWith("check_out_")) {

String contractID = attrib.substring(10);System.out.println("Check out customer with contract = "+

contractID);

//update local status for contract customerdatabaseService.update2Exited(contractID);

}}

}

//get all pending customers for JSP to display req.setAttribute("PendingCustomers",

databaseService.getPendingCustomers());

//get all arrived customers for JSP to displayreq.setAttribute("ArrivedCustomers",

databaseService.getArrivedCustomers());

forward2Page(req, resp, "/CheckIn.jsp");}

/** * Forward to the request page (including the current set of properties) * @param req * @param resp * @param nextpage */private void forward2Page(HttpServletRequest req, HttpServletResponse resp,

String nextpage) throws ServletException, IOException {

//always add the properties (for login and config)req.setAttribute("Properties", properties);

ServletContext context = this.getServletContext();RequestDispatcher rd = context.getRequestDispatcher(nextpage);rd.forward(req, resp);

}

* @param req */private void processConfig(HttpServletRequest req) {

properties.setProperty("itso.database.standalone" , (req.getParameter("itso.database.standalone") == null) ? "false": "true");

Chapter 7. HTTP services, servlets and Java server pages 209

Page 226: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

properties.setProperty("itso.mqe.standalone", (req.getParameter("itso.mqe.standalone") == null) ? "false": "true");

properties.setProperty("itso.webservice.standalone",(req.getParameter("itso.webservice.standalone") == null) ? "false": "true");

properties.setProperty("itso.devicemanagement.standalone",(req.getParameter("itso.devicemanagement.standalone") == null) ? "false": "true");

/** * Save any changes to the configuration and re-init

String syncHost = req.getParameter("server.url");if (syncHost != null) properties.setProperty("server.url", syncHost);String mqHost = req.getParameter("itso.mqe.QMIPAddress");if (mqHost != null) properties.setProperty("itso.mqe.QMIPAddress",

mqHost);String mqPort = req.getParameter("itso.mqe.QMPort");if (mqPort != null) properties.setProperty("itso.mqe.QMPort", mqPort);String qName = req.getParameter("itso.mqe.DeviceQMName");if (qName != null) properties.setProperty("itso.mqe.DeviceQMName",

qName);String address =

req.getParameter("itso.webservice.endpoint_address_property");if (address != null)

properties.setProperty("itso.webservice.endpoint_address_property", address);String sleeptime = req.getParameter("itso.webservice.sleeptime");if (sleeptime != null)

properties.setProperty("itso.webservice.sleeptime", sleeptime);String dmsHost = req.getParameter("itso.devicemanagement.keyAddr");if (dmsHost != null)

properties.setProperty("itso.devicemanagement.keyAddr", dmsHost);

save(properties);

databaseService.init(properties);mqeService.shutdown();mqeService.init(properties);flightInfoWebserviceClient.init(properties);

// if (dmService != null) dmService.init(properties);

}

/** * The login button has been pressed and we need to perform * some verification step * @param req * @param resp

210 WCTME: Application Development and Case Study

Page 227: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

* @return */private boolean verifyLogin(HttpServletRequest req, HttpServletResponse

resp) {String userid = (String) req.getParameter("userid");String password = (String) req.getParameter("password");if ((userid != null) && (!userid.equalsIgnoreCase("")) &&

(password != null) && (!password.equalsIgnoreCase(""))) {//insert a real login verification here!!!//save for demo use laterproperties.setProperty("isync.user", userid);properties.setProperty("isync.password", password);save(properties);

return true;}req.setAttribute("LoginMessage", "Login Falied!");return false;

}

/** * This servlet also serves up the pictures of our customer * (taken directly from a BLOB in the database. * @param resp * @param s */private void returnBlob(HttpServletResponse resp, String s) {

Object input = null;Object output = null;

//call database bundle for pitcure streamInputStream ins = databaseService.getPicture(s);

if (ins != null) {resp.setContentType("Content-Type: image/jpg");OutputStream outs;try {

outs = resp.getOutputStream();copyStreams(ins, outs);ins.close();outs.close();

} catch (IOException e) {e.printStackTrace();

}}

}

/*** Copy from stream to stream*/private void copyStreams(InputStream ins, OutputStream outs)

Chapter 7. HTTP services, servlets and Java server pages 211

Page 228: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

throws IOException {int maxRead = 1024;byte[] buffer = new byte[1024];int bytesRead;for (;;) {

bytesRead = ins.read(buffer);if (bytesRead <= 0) {

break;}outs.write(buffer, 0, bytesRead);

}}

/*** @see javax.servlet.http.HttpServlet#void

(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)*/public void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {doGet(req, resp);

}

/*** @see javax.servlet.GenericServlet#void ()*/public void init() throws ServletException {

super.init();

//load properties file//if it doesn't exist create it with default valuesFile pf = new File(PROPERTIES);if (!pf.exists()) {

Properties p = createDefaultProperties();save(p);

}properties = load();

//Resolve Database serviceServiceReference dbRef =

context.getServiceReference(ITSORentalsDatabaseService.class.getName());

if (dbRef != null) {databaseService = (ITSORentalsDatabaseService)

context.getService(dbRef);System.out.println("Found Database service!");

//initialize - passing properties to configure service

212 WCTME: Application Development and Case Study

Page 229: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

databaseService.init(properties);}

//Resolve MQe serviceServiceReference mqRef =

context.getServiceReference(ITSORentalsMQeService.class.getName());

if (mqRef != null) {mqeService = (ITSORentalsMQeService) context.getService(mqRef);System.out.println("Found MQe service!");

//initialize - passing properties to configure servicemqeService.init(properties);

}

//Initialize the Web ServiceflightInfoWebserviceClient = new ITSORentalsWebServiceClientImpl();flightInfoWebserviceClient.init(properties);

// //Resolve Device Management service// ServiceReference dmsRef =//context.getServiceReference(ITSORentalsDeviceManagementService.class.getName());

// if (dmsRef != null) {// dmService = (ITSORentalsDeviceManagementServiceImpl) context.getService(dmsRef);// System.out.println("Found Device Management service!");

// //initialize - passing properties to configure service// dmService.init(properties);// }

}

/** * Load the properties file * @return */public Properties load(){

//load properties filetry {

properties = new Properties();properties.load(

new BufferedInputStream(new FileInputStream(PROPERTIES)));} catch (Exception e) {

System.out.println(e);

Chapter 7. HTTP services, servlets and Java server pages 213

Page 230: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

}

return properties;}

/** * Save the properties in a file * @param p * @return */public boolean save(Properties p) {

FileOutputStream file = null;try {

file = new FileOutputStream(PROPERTIES);p.store(file, "");

} catch (IOException e) {System.out.println("Exception during properties save! " + e);

} finally {try {

file.close();} catch (IOException e) {

//whatever!}

}return true;

}

public Properties createDefaultProperties() {

Properties p = new Properties();//properties for database and syncp.setProperty("itso.database.standalone","true");

// syncdriver=com.ibm.mobileservices.isync.db2e.jni.DB2eISyncProviderp.setProperty("syncprotocol","isync:db2e:");p.setProperty("server.url","http://your_db2sync_server:80");

// p.setProperty("target.db.driver","");// p.setProperty("target.db.url","");

p.setProperty("isync.user", ""); p.setProperty("isync.password", "");p.setProperty("isync.timeout", "60"); p.setProperty("isync.trace", "default");p.setProperty("path","ITSODatabase");p.setProperty("jdbcsuburl",".");p.setProperty("filesubdir",".");

// p.setProperty("target.db.user","db2admin");// p.setProperty("target.db.password","=db2admin");

//properties for MQep.setProperty("itso.mqe.standalone", "true");

214 WCTME: Application Development and Case Study

Page 231: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

p.setProperty("itso.mqe.QMIPAddress", "your_MQe_Server");p.setProperty("itso.mqe.QMPort", "8086");p.setProperty("itso.mqe.QMName", "Transponder");p.setProperty("itso.mqe.DeviceQMName", "ITSOQueues");

//properties for Web Servicesp.setProperty("itso.webservice.standalone", "true");p.setProperty("itso.webservice.sleeptime", "30000");p.setProperty("itso.webservice.endpoint_address_property",

"your_web_service_server:80");

//properties for Device Managementp.setProperty("itso.devicemanagement.standalone", "true");p.setProperty("itso.devicemanagement.keyAddr",

"http://your_device_management_server:80/dmserver/SyncMLDMServletAuthRequired");

p.setProperty("itso.devicemanagement.keyServerPW", "");p.setProperty("itso.devicemanagement.keySSLKeyRing", "");p.setProperty("itso.devicemanagement.keySSLKeyRingPassword", "");p.setProperty("itso.devicemanagement.polling", "false");

return p;}

15.Save the file.

16.Open the MANIFEST.MF file. Scroll down to Import Packages.

17.Expand the section Import Package and select Add...

18.Select the packages:

– com.itso.flightInfo.client– com.itso.rentals– com.itso.rentals.mqe– com.itso.rentals.database

Click OK.

Tip: To help remove unresolved compiler errors, right-click in the source and select Source →Organize Imports. If prompted, choose the FileInputStream and FileOutputStream classes in the java.io package.

Note: Some of the code included above is commented out. In a later chapter, that device management code will be uncommented and used.

Chapter 7. HTTP services, servlets and Java server pages 215

Page 232: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

19.Expand the section Import Services and select Add...

20.Select the services com.itso.rentals.database.ITSORentalsDatabaseService and com.itso.rentals.mqe.ITSORentalsMQeService and click OK.

21.Save the file.

22.Expand the project down to the folder WebContent. Select the file name CheckIn and double-click.

23.In the CheckIn.jsp window that opens, replace the entire document with the code in Example 7-4.

Example 7-4 Checkln.jsp code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<HTML><HEAD><%@ page import="java.util.Vector, com.itso.rentals.Customer, com.itso.flightInfo.client.ITSORentalsWebServiceClientImpl"language="java"contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%><META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><META name="GENERATOR" content="IBM WebSphere Studio"><META http-equiv="Content-Style-Type" content="text/css"><LINK href="theme/Master.css" rel="stylesheet" type="text/css"><TITLE>ITSO Vehicle Rental App</TITLE></HEAD><BODY><FORM method="post" action="/ITSORentals/CheckInAndSync"><IMG

border="0" src="Logo.jpg" width="176" height="69">

<TABLE width="240"><TBODY>

<TR><TD align="left"><%

/* Look for any sync messages that might need displaying */

Note: The packages might already have been added automatically, or you can press the Compute button to fill in the list.

This bundle does not require Extension Services for DB2 Everyplace, MQ Everyplace and Web Services. It does however, need to import the packages in other bundles that do use these services.

216 WCTME: Application Development and Case Study

Page 233: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

String syncMessage = (String) request.getAttribute("SyncMessage");if (syncMessage != null) {%> <%=syncMessage%> <%}%></TD>

<TD align="right" valign="middle"><INPUT type="submit"name="SyncButton" value="Sync"></TD>

</TR><TR>

<TD align="left" valign="bottom"><B>Arriving Customers</B></TD><TD align="right" valign="middle"><INPUT type="submit"

name="UpdateButton" value="Device Update"></TD></TR>

</TBODY></TABLE>

<TABLE width="240" border="2" cellpadding="0" cellspacing="0"><TBODY>

<TR bgcolor="#c0c0c0"><TD><B>Name</B></TD><TD align="center"><B>Photo</B></TD><TD align="center"><B>Flight<BR>Info</B></TD><TD align="center" width="55"><B>Arrived</B></TD>

</TR><%

/* Get a web client for displaying the latest flight info status */ITSORentalsWebServiceClientImpl webServceClient =

new ITSORentalsWebServiceClientImpl();/* Display the vector of all the pending customers/contracts here*/Vector pending = (Vector) request.getAttribute("PendingCustomers");if (pending != null) {

/*if we have any pending, list them*/int count = 0;int size = pending.size();if (size > 0) {

for (int j = 0; j < size; j++) {Customer customer = (Customer) pending.elementAt(j);count++;%>

<TR><TD><%=customer.getLastName()%>, <BR><%=customer.getFirstName()%></TD><TD align="center" valign="middle"><IMG border="0"

src="/ITSORentals/CheckInAndSync?Blob=<%=customer.getCustomerID()%>"width="75" height="75"></TD>

<%String updatedFlightInfo =webServceClient.getFlightInfoAsHTMLTableData(customer.getFlightInfo());%>

<%=updatedFlightInfo%><TD align="center" valign="middle"><INPUT type="checkbox"

name="check_in_<%=customer.getContractID()%>" value="true"></TD></TR>

Chapter 7. HTTP services, servlets and Java server pages 217

Page 234: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

<%} //end of for loop%><%} else { //end of if (size)%><TR>

<TD>-none-</TD><TD></TD><TD></TD><TD></TD>

</TR><%}%><%} else { //end if (!null)%><TR>

<TD>Error receiving list</TD><TD></TD><TD></TD><TD></TD>

</TR><%}%>

</TBODY></TABLE>

<TABLE width="240"><TBODY>

<TR><TD align="left" valign="bottom"><B>On Bus</B></TD><TD align="right" valign="middle"><INPUT type="submit"

name="CheckButton" value="Refresh / Submit"></TD></TR>

</TBODY></TABLE>

<TABLE width="240" border="2" cellpadding="0" cellspacing="0"><TBODY>

<TR bgcolor="#c0c0c0"><TD><B>Name</B></TD><TD align="center"><B>Vehicle<BR>Location</B></TD><TD align="center" width="55"><B>Exited</B></TD>

</TR><%

/* Display the vector of all the arrived customers/contracts here*/Vector arrived = (Vector) request.getAttribute("ArrivedCustomers");if (arrived != null) {

/*if we have any arrived, list them*/int count = 0;int size = arrived.size();if (size > 0) {

for (int j = 0; j < size; j++) {Customer customer = (Customer) arrived.elementAt(j);count++;%>

218 WCTME: Application Development and Case Study

Page 235: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

<TR><TD><%=customer.getLastName()%>, <BR><%=customer.getFirstName()%></TD><TD align="center"

valign="middle"><%=customer.getVehicleLocation()%></TD><TD align="center" valign="middle"><INPUT type="checkbox"

name="check_out_<%=customer.getContractID()%>" value="true"></TD></TR><%} //end of for loop%><%} else { //end of if (size)%><TR>

<TD>-none-</TD><TD></TD><TD></TD>

</TR><%}%><%} else { //end if (!null)%><TR>

<TD>Error receiving list</TD><TD></TD><TD></TD>

</TR><%}%>

</TBODY></TABLE><INPUT type="submit" name="ResetButton" value="Reset Demo"> <INPUT

type="submit" name="ConfigButton" value="Config"> <INPUT type="submit"name="LogoutButton" value="Logout"></FORM>

</BODY></HTML>

24.Save the file.

The complete Web application also calls two other jsp files. One to perform a login and the other to configure the demo. Add these to the Web application.

25.Expand the project down to the folder WebContent. Select WebContent, right-click and select New → JSP File or New → Other →Web → JSP File if you are not still in the Web Perspective.

26.Enter the file name Login and click Finish.

27.In the Login.jsp window that opens, replace the entire document with Example 7-5 on page 220:

Chapter 7. HTTP services, servlets and Java server pages 219

Page 236: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Example 7-5 Login.jsp code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<HTML><HEAD><%@ page import="java.util.Properties"language="java"contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%><META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><META name="GENERATOR" content="IBM WebSphere Studio"><META http-equiv="Content-Style-Type" content="text/css"><LINK href="theme/Master.css" rel="stylesheet"

type="text/css"><TITLE>ITSORentals Login</TITLE></HEAD><BODY><%/* add comment here */Properties p = (Properties) request.getAttribute("Properties");if (p == null) p = new Properties();%><FORM method="post" action="/ITSORentals/CheckInAndSync"><IMG border="0" src="Logo.jpg" width="176" height="69"><%/* add comment here */String loginMessage = (String) request.getAttribute("LoginMessage");if (loginMessage != null) {%><P><%=loginMessage%> <%}%>

<TABLE border="0"><TBODY>

<TR><TD><B>Userid</B></TD>

</TR><TR>

<TD><INPUT type="text" name="userid" size="20" maxlength="20" <%String userid = p.getProperty("isync.user");if (userid != null) {

%>value="<%=userid%>"<%}%>>

</TD></TR><TR>

<TD><B>Password</B></TD></TR><TR>

220 WCTME: Application Development and Case Study

Page 237: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

<TD><INPUT type="password" name="password" size="20" maxlength="20" <%

String password = p.getProperty("isync.password");if (password != null) {

%>value="<%=password%>"<%}%>>

</TD></TR>

</TBODY></TABLE>

<BR><INPUT type="submit" name="LoginButton" value="Login"></FORM></BODY></HTML>

28.Save the file.

29.Again expand the project down to the folder WebContent. Select WebContent, right-click and select New → JSP File.

30.Enter the file name Configure and click Finish.

31.In the Configure.jsp window that opens, replace the entire document with the code in Example 7-6.

Example 7-6 Configure.jsp code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<HTML><HEAD><%@ page import="java.util.Properties"language="java"contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%><META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><META name="GENERATOR" content="IBM WebSphere Studio"><META http-equiv="Content-Style-Type" content="text/css"><LINK href="theme/Master.css" rel="stylesheet"

type="text/css"><TITLE>Demo Configure</TITLE></HEAD><BODY><%/* add comment here */Properties p = (Properties) request.getAttribute("Properties");

Chapter 7. HTTP services, servlets and Java server pages 221

Page 238: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

if (p == null) p = new Properties();%><FORM method="post" action="/ITSORentals/CheckInAndSync"><H2>Demo Configuration</H2><P/>For demonstration purposes the following services can be configured to operate with a server or in stand-alone mode.<TABLE border="1">

<TBODY><TR bgcolor="#c0c0c0">

<TD><B>Service</B></TD><TD align="center"><B>Stand-alone <BR>mode enabled</B></TD>

</TR><TR>

<TD><B>Database Sync</B></TD><TD align="center"><INPUT type="checkbox" value="true"

name="itso.database.standalone" <%String database = p.getProperty("itso.database.standalone");if ((database != null) && database.equalsIgnoreCase("true")) {

%>checked<%}%>>

</TD></TR><TR>

<TD><B>MQe</B></TD><TD align="center"><INPUT type="checkbox" value="true"

name="itso.mqe.standalone" <%String mqe = p.getProperty("itso.mqe.standalone");if ((mqe != null) && mqe.equalsIgnoreCase("true")) {

%>checked<%}%>>

</TD></TR><TR>

<TD><B>Web Service</B></TD><TD align="center"><INPUT type="checkbox" value="true"

name="itso.webservice.standalone" <%String webservice = p.getProperty("itso.webservice.standalone");if ((webservice != null) && webservice.equalsIgnoreCase("true")) {

%>checked<%}%>>

</TD></TR><TR>

<TD><B>Device Management</B></TD><TD align="center"><INPUT type="checkbox" value="true"

name="itso.devicemanagement.standalone" <%String dms = p.getProperty("itso.devicemanagement.standalone");if ((dms != null) && dms.equalsIgnoreCase("true")) {

%>checked<%

222 WCTME: Application Development and Case Study

Page 239: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

}%>></TD>

</TR></TBODY>

</TABLE><BR/>Modify the application/services property settings as necessary:<TABLE border="1">

<TBODY><TR>

<TD bgcolor="#c0c0c0"><B>DB2e sync host and port with the format &quot;http://host_name:port_number&quot;

</B></TD></TR><TR>

<TD><INPUT type="text" name="server.url" size="30" <%String syncHost = p.getProperty("server.url");if (syncHost != null) {

%>value="<%=syncHost%>"<%}%>>

</TD></TR><TR>

<TD bgcolor="#c0c0c0"><B>MQe server host name</B></TD></TR><TR>

<TD><INPUT type="text" name="itso.mqe.QMIPAddress" size="20" <%String mqHost = p.getProperty("itso.mqe.QMIPAddress");if (mqHost != null) {

%>value="<%=mqHost%>"<%}%>>

</TD></TR><TR>

<TD bgcolor="#c0c0c0"><B>MQe server host port</B></TD></TR><TR>

<TD><INPUT type="text" name="itso.mqe.QMPort" size="6" <%String mqPort = p.getProperty("itso.mqe.QMPort");if (mqPort != null) {

%>value="<%=mqPort%>"<%}%>>

</TD></TR><TR>

<TD bgcolor="#c0c0c0"><B>Device's queue name</B></TD></TR><TR>

<TD><INPUT type="text" name="itso.mqe.DeviceQMName" size="20" <%

Chapter 7. HTTP services, servlets and Java server pages 223

Page 240: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

String qName = p.getProperty("itso.mqe.DeviceQMName");if (qName != null) {

%>value="<%=qName%>"<%}%>>

</TD></TR><TR>

<TD bgcolor="#c0c0c0"><B>Flight information (web service) server host and port with the format &quot;host_name:port_number&quot;</B></TD>

</TR><TR>

<TD><INPUT type="text" name="itso.webservice.endpoint_address_property" size="20" <%

String address = p.getProperty("itso.webservice.endpoint_address_property");

if (address != null) {%>value="<%=address%>"<%

}%>></TD>

</TR><TR>

<TD bgcolor="#c0c0c0"><B>Local web service thread sleep time in milliseconds.</B><BR>

(How often the local web service calls the server-side web service to retreive updated flight information.)</TD>

</TR><TR>

<TD><INPUT type="text" name="itso.webservice.sleeptime" size="8" <%String sleeptime = p.getProperty("itso.webservice.sleeptime");if (sleeptime != null) {

%>value="<%=sleeptime%>"<%}%>>

</TD></TR><TR>

<TD bgcolor="#c0c0c0"><B>Device Management server URL with theformat

&quot;http://host_name:port_number/dmserver/SyncMLDMServletAuthRequired&quot; </B></TD>

</TR><TR>

<TD><INPUT type="text" name="itso.devicemanagement.keyAddr" size="35" <%

String dmsHost = p.getProperty("itso.devicemanagement.keyAddr");if (dmsHost != null) {

%>value="<%=dmsHost%>"<%}%>>

</TD></TR>

224 WCTME: Application Development and Case Study

Page 241: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

</TBODY></TABLE><B>Note:</B>If you change the MQe server host information, you should deleted the local directory &quot;&lt;Device's queue name&gt;&quot; before saving changes!<BR><B>Note:</B>If you delete the database directory &quot;ITSODatabase&quot; you will have to reset the DB2e user on the sync host.<BR><INPUT type="submit" name="SetButton" value="Save Changes"><INPUT type="submit" name="CancelSetButton" value="Cancel"><BR><H2>Demo Data</H2>To insert sample data into the database:<BR><INPUT type="submit" name="CreateButton" value="Create Sample Data"><BR>To insert local pictures &quot;demo-images\\Image1.jpg&quot;, etc into the database:<BR><INPUT type="submit" name="InsertButton" value="Insert Local Pictures"></FORM></BODY></HTML>

32.Save the file.

7.4.2 Extending the Tester bundleBecause the new bundle version of the Web application is the running sample application, we do not need to extend the tester bundle any more.

You can uninstall it from the runtime, if it is still present because we will no longer be using it.

7.4.3 Web application reviewWe created a new dynamic Web application project that represents a mock-up of the completed sample application, then ran it within the WebSphere Test Environment.

We converted the mock-up to a Web application bundle and ran it in with the Extension Services Local Server. It was still just a mock-up, but it was now running as a bundle in our SMF runtime.

Note that with our modular design, we use the customer, database, messaging and Web services bundles created and tested in previous chapters and that the Web application does not know very much about the details of those services or how they are implemented. The services are all hidden behind their interfaces.

Chapter 7. HTTP services, servlets and Java server pages 225

Page 242: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

We updated the imports section of the Web application’s manifest file to record our dependencies on those bundles and Java classes.

After updating the servlet logic to connect to the bundles, the same code from our tester bundle, to see the init() method, and to access the other bundles appropriately when the application’s buttons are selected, see doGet(), and then adding the login and configure panels, we have a completed sample application in stand-alone mode.

7.5 Running the completed Web applicationYou can now run the completed sample application. Navigate into the ITSORentalsWebApplicationBundle project and select the CheckInAndSync.java file, right-click and select Run on Server....

See section 2.2, “Running the sample application” on page 25 on steps for running the sample application.

Note: The steps to synchronize the application’s local database tables with the sync server will be added in Chapter 10, “DB2e synchronization” on page 271. The implementation of the device management service will not be covered until Chapter 11, “Device management” on page 317.

7.6 TroubleshootingThis section covers various tips on how to handle some problems you might run into, as well as ways to extend the testing of the application.

If when you start the sample application the Web paged does display, make sure you select the Java servlet file CheckInAndSync when you select Run on Server. The web application URL is:

http://localhost:(port)/ITSORentals/CheckInAndSync

For a PocketPC, use this Web address:

http://127.0.0.1/ITSORentals/CheckInAndSync

To avoid conflicts, make sure to stop any other Web servers, bundle servers and runtimes that might be competing for the same ports.

When running the application, the console will display any exception that the application might throw. For example; before the first sync or creation of sample

226 WCTME: Application Development and Case Study

Page 243: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

data, the getPendingCustomers() and getArrivedCustomers() calls will throw exceptions because the database tables do not exist yet.

Chapter 7. HTTP services, servlets and Java server pages 227

Page 244: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

228 WCTME: Application Development and Case Study

Page 245: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Chapter 8. WCTME application configuration for a target platform

This chapter describes how to configure system bundles, the deployable java runtime environment, and the Service Management Framework for a target platform using the WebSphere Studio tool.

This chapter contains the following:

� Customizing the Java Class Library and System Services in an application for deployment

� Using the Service Management Framework (SMF) features and manifest to customize application bundles

8

© Copyright IBM Corp. 2005. All rights reserved. 229

Page 246: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

8.1 OverviewWhen deployed, an application consists of a customizable Java Class Library (JCL) and JVM, the SMF environment, System application services, bundles and the application bundles themselves.

8.1.1 Configuring the Java Class Library (JCL)The JCL profiles, which include the IBM J9 JVM, allow the developer of a micro environment application to customize the java platform to include only the features that are needed by the system and application bundles. For applications that require the java powered brand and standard, the Studio tool continues to offer developers the options of choosing J2ME profiles since WCTME tooling includes all the tooling capabilities of WebSphere Studio Device Developer.

8.1.2 Configuring the bundle application using the SMFThe SMF environment and the application services are deployed as bundles on top of the JVM. As illustrated in Figure 1-1 of Chapter 1, “Introduction to Workplace Client Technologies” on page 1, the SMF adds many configuration capabilities to the java platform for mobile environments.

The SMF environment can be configured to run many applications or services, unlike a stand-alone JVM which can only run one application. This is carried out by applications being installed as bundles that have zero or many services. These services can be administered using the SMF environment. Unlike the closed container in a J2EE environment, the SMF environment allows the sharing of services amongst other bundle applications. It implements this feature using a manifest where the services and bundle exports and imports are declared. The SMF also administers the life cycle of these bundles.

8.1.3 Adding system application servicesThe list of system services that a custom application can use does vary, depending on the WCTME platform profile. All of the services that WCTME makes available to the java application take the form of a service bundle such as the DB2 Everyplace ISync Client. Even the SMF environment is a mandatory application service bundle.

The following chapter describes how to use the platform builder to include additional SMF application services, custom services and to expose the bundle services to other bundles. The platform builder can also be used to create a custom Java class library containing the features that the bundles need so that the restricted resources of a mobile environment are used most efficiently.

230 WCTME: Application Development and Case Study

Page 247: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

8.2 Customizing the Java Class Library (JCL) and application services

When creating an application for a given platform, the WCTME tooling platform gives the user an option of choosing from multiple custom platform options. With these options, the user can customize the Java class library and include the application services that will be used by the application. The user has the following options for the JCL, which takes the form of two sections: profiles that include and do not include extension services.

� Extension Services Default JRE (5.7.0)� Extension Services Java Class Library Max� Extension Services Java Class Library Foundation � Extension Services Java Class Library Min� Eclipse Default JRE� Java Class Library Max� Java Class Library Foundation � Java Class Library Min

After choosing the appropriate platform profiles, the user chooses the WCTME services that will be included in the application. Every profile supports a different combination of services. The rule of thumb here would be to choose a profile that supports only the services your application would need.

8.3 Including system services in your projectThe following steps guide you through creating an extension services project and picking the server profile options along with the system extension services appropriate for your project.

1. Select File →New →Other.

2. From the New Project type dialog box select Extension Service from the left pane and the appropriate extension services project from the right pane. After entering the project name in the dialog box, the platform profile dialog pictured in Figure 8-1 on page 232 can be used to choose the appropriate platform profile.

The Studio tool stores these platform profile in a XML-based platform profile descriptor file. The user can define her own Platform Profile by creating a platform profile descriptor file and adding it to the tools through the platform profile extension point.

Chapter 8. WCTME application configuration for a target platform 231

Page 248: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 8-1 Platform profile

The platform choice involves picking a profile depending on whether the application will have extension services features or application features. The DB2 application aervice would be an example of a extension services feature. The choice is dependent on which application services will be required. It would be optimal to select the smallest platform profile (listed in descending order of size above) that would offer all application services you would use.

232 WCTME: Application Development and Case Study

Page 249: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

The next few panes offer the user the choice of creating a default bundle activator and whether the manifest should automatically manage import package key in the bundle manifest.

Table 8-1 describes the application services that are a part of WCTME along with the functionality it will add to your application.

Table 8-1 WCTME application services

Application Service Description Bundles

Core OSGI Interfaces The SMF environment OSGI SMF system

Web Application Servlet 2.3 and JSP 1.2 Web Application Support

Web ContainerWeb HTTP ServiceWeb ApplicationServlet 2,3

Xerces XML Parser IBM XML 4J Xerces XML parser XML4J ParserXML Parser API’s

Micro XML Micro SAX1/DOM1 non validating XML Parser MicroXML XML ParserAPI’s

The OSGI Configuration Admin ServiceThe OSGI Managed Service & FactoryThe OSGI device ServiceThe OSGI Driver ServiceThe OSGI Driver locator & Selector Service

A Device service represents some form of a device. It can represent a hardware device, but that is not a requirement. Device services differ widely: some represent individual physical devices and others represent complete networks. Several Device services can even simultaneously represent the same physical device at different levels of abstraction.

OSGi-SPR3 ServiceInterfaces

ConfigurationAdmin

DeviceManager

The OSGI HTTP Service

Legacy support for Servlet 2.1 web applications.

Servlet2.1HttpService

The OSGI log ServiceThe OSGI log Reader Service

The Log Service provides an interface allowing bundles to log information.

OSGi-SPR3 ServiceInterfaces

LogService

Chapter 8. WCTME application configuration for a target platform 233

Page 250: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

The OSGI Perference Service

The Preferences Service interface allows a bundle to create or obtain a Preferences tree for system properties, as well as a Preferences tree for each user of the bundle. It allows for implementations where the data is stored locally on the service platform or remotely on a backend system.

OSGi-SPR3 ServiceInterfaces

PreferencesService

The OSGI Service Tracker

The Service Tracker utility class supports tracking the registration, modification, and unregistration of services. This utility significantly reduces the complexity of tracking services in the service registry.

OSGi-SPR3-ServiceTracker

The OSGI Start level Service

The Start Level service enables a management agent to control the relative starting and stopping order of bundles.

osgiSMF System Bundle

The OSGI User Admin Service.

The User Admin service supports authentication and authorization of the users of an OSGi platform.

OSGi-SPR3 ServiceInterfaces

UserAdmin

The Cloudscape and Cloudscape Isync client

IBM Cloudscape provides developers a small footprint, standards-based Java database that can be tightly embedded into any Java based solution.The Sync Client Java-API allows developers to build applications that synchronize data bi-directionally between DB2 Everyplace and enterprise relational databases. It works in conjunction with the DB2 Everyplace Sync Server to simplify the synchronization of relational data and files.

JDBC2.0IBM Cloudscape 5.1IBMCloudscapeSyncClient

Application Service Description Bundles

234 WCTME: Application Development and Case Study

Page 251: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

The DB2 and DB2 Isync client

DB2 Everyplace is a relational database and enterprise synchronization server that enables enterprise applications and enterprise data to be extended to mobile devices such as personal digital assistants (PDAs) and smart phones.

DB2 Everyplace can also be embedded into devices and appliances to increase their functionality and market appeal.

DB2 Everyplace can be used as a local independent database of the mobile device or query information about remote servers when a connection is available.

JDBC2.0DB2EveryplaceClientDB2EveryplaceClientSync

WebSphere MQ EveryplaceWebSphere MQ Everyplace using JMSWebSPhere MQ Telemetry Transport

WebSphere MQ Everyplace is a member of the IBM WebSphere MQ family of business messaging products. It exchanges messages with various applications, providing once and once-only assured delivery. WebSphere MQ Everyplace is designed to integrate well with other members of the WebSphere MQ family, and other components of the WebSphere MQ Everyplace Server.

WebSphere MQ Everyplace is designed to satisfy the messaging needs of lightweight devices, such as sensors, phones, Personal Digital assistants (PDAs), and mobile computers. It supports mobile environments and is suitable for use over public networks, supporting requirements that arise from the use of fragile communication networks. As many WebSphere MQ Everyplace applications run outside the protection of an Internet firewall, it also provides security capabilities.

MQeBundleMQeJMS BundleJMS1.1MQTelemetryTransport

SyncML/DM OSGi Agent

The SyncML/DM OSGi Agent enables you to update local configurations and software, both native and Java, from a Device Manager Server (DMS).

OSGiAgent

Application Service Description Bundles

Chapter 8. WCTME application configuration for a target platform 235

Page 252: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

8.3.1 Using the properties tab to change platform profilesand application services

After the choices are made and during the development of the application, these properties could be changed by right-clicking the project, choosing the properties option, then choosing Extension Services on the left panel of the pop-up window.

8.4 Using the Manifest file to configure the applicationThe actions of creating an application profile, choosing application services, and using the wizard to create an extension services project generates a manifest for the project that already contains the options that were chosen during that process. However, editing the manifest could achieve a greater degree of customization.

The manifest contains the following components:

� OSGI bundle settings

The SynchML4J Framework

SyncML is an open standard for data synchronization (DS) and device management (DM). SyncML has been designed with the requirements of the wireless world in mind. SyncML tries to minimize the use of network bandwidth and tackles problems like low network reliability and high network latency. SyncML4J is a client-side Java implementation of the SyncML protocols keeping the very same constraints in mind. SyncML4J is based on the 1.1.1 DS and 1.1.2 DM protocols.

SyncML4J

Web Services using Generated Stub ClassesWeb Services using proxy Services

Web Services using generated Stub classes provides the runtime classes necessary for an application to use the stub and other generated classes from the Web Services Toolkit for Mobile Devices plug-in.

Web Services using Proxy services provides the runtime classes and services necessary for an application to use the interface and other generated classes from the Web Services Toolkit for Mobile Devices plug-in.

WebServicesMEWebServices Gateway

Application Service Description Bundles

236 WCTME: Application Development and Case Study

Page 253: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

� User-defined Manifest items� Import and export of packages and bundles� Native Code clauses

Of note in this list is the bundle version. The bundle server updates bundles that have a newer version when deployed.

Even though WebSphere Studio adds relevant details to the manifest automatically, editing and changing the manifest using the tool is also possible.

Figure 8-2 illustrates the framework for imported, exported and private classes.

Figure 8-2 Framework

8.5 Extension Services and J2ME profiles differences

The difference between the extension services platform builder and a J2ME environment are the additions of the SMF environment functionality and the ability to customize the Java class library. For building applications for platforms such MID Profile cellphones the J2ME environment has to be used. Adding the SMF environment or in application services terms, the core OSGI interfaces, adds more functionality than the J2ME profiles. It also requires more resources from the host platform. Therefore, if the host platform cannot support these

ExportedClasses

PrivateClasses Framework

ExportedClasses

PrivateClasses

ImportedClasses

ImportedClasses

Chapter 8. WCTME application configuration for a target platform 237

Page 254: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

additional resource demands, the J2ME profiles, midlevel and foundation profiles, can be used with the IBM J9 JVM.

8.6 Platform builder troubleshootingWhen using the platform builder to put a collection of custom bundles together, the bundles are started in alphabetical order. This can cause problems if one bundle depends on another for services. The correct solution to this problem is to use a service tracker so that the dependent bundle is notified when the needed bundle becomes active.

238 WCTME: Application Development and Case Study

Page 255: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Chapter 9. Deploying a WCTME Application

This chapter describes deploying applications bundles that have been created using the WebSphere Studio tool.

This chapter contains the following topics:

� Overview of the deployment options� How to export bundles and web application bundle (WAB) files� Creating a Platform Builder Project and performing a build� How to manually deploy the sample application to a Pocket PC

9

© Copyright IBM Corp. 2005. All rights reserved. 239

Page 256: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

9.1 OverviewThe WebSphere studio tool allows the user to create all the artifacts necessary to deploy to a list of platforms that are supported by the tool or to a custom platform. The following platforms in Table 9-1 are supported by the WebSphere Studio tool.

Table 9-1 Platform types

If you need to support platforms and operating systems that are not included in this matrix, you could use the custom option. The custom option requires the location of an external JVM operating on the chosen Operating system processor combination.

The creation of the application in a format that is ready to deploy involves several steps:

1. Exporting application bundles.2. Exporting web application bundles, if necessary.3. Creating a Platform Builder Project

a. Configuration settingsb. Adding application bundlesc. Resolving required bundlesd. Performing the build

After you have created a platform builder project and performed a build, if any bundles need updating, then remove the old bundles. Lastly, add in the replacement bundles and perform another build.

Platform Type Operating System

Processor

PocketPC WindowsCE ARM

Zaurus Linux ARM

PC Red Hat Linux x86

PC Windows 2000 x86

PC Windows XP x86

Custom MacOS, Solaris.....

ARM, Alpha, Power,....

Note: You can then add custom files to a builder project, because our sample application needs to run in stand-alone mode.

240 WCTME: Application Development and Case Study

Page 257: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Once a project has been deployed to a client it, can be updated remotely as described in Chapter 11, “Device management” on page 317.

The output of a platform build is a zip file (or .ipk, or .tar file) that contains two system directories, JVM and SMF, and any additional custom directories. The JVM directory contain all the Java class library specific components while the SMF directory contains the SMF system and application bundles.

9.2 Exporting your application from WebSphere StudioIn the previous chapters we developed and tested all the application and tester bundles inside the Studio IDE. To deploy to an environment outside WebSphere Studio you must export the bundles and create a Platform Builder Project.

9.2.1 Exporting application bundlesIn this section we cover the process of exporting application bundles to a directory that will be used later to perform a platform build.

To export the application bundles, perform the following steps:

1. Create a sub-directory on your development system to hold the exported files. Name it C:\ITSORentalsPC.

2. In the Studio workbench, SMF Perspective, select the application bundles you want to export, right-click and select SMF, then Submit → Bundle.

– FlightInfoWebServiceBundle

– FlightInfoWebServiceClientBundle

– ITSOCustomerBundle

– ITSORentalsDatabaseServiceBundle

– ITSORentalsDeviceManagementServiceBundle (Not completed until Chapter 11, “Device management” on page 317)

– ITSORentalsMQeServiceBundle

See Figure 9-1 on page 242.

Chapter 9. Deploying a WCTME Application 241

Page 258: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-1 Selecting bundles to export

3. On the next panel (Figure 9-2 on page 243) check the boxes next to Submit Jar and Replace Bundles and then select Add Directory...

242 WCTME: Application Development and Case Study

Page 259: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-2 Creating a new export directory

4. Navigate to the directory created above, C:\ITSORentalsPC and click OK.

5. Now select the directory you just added and click Finish. SeeFigure 9-3 on page 244.

Chapter 9. Deploying a WCTME Application 243

Page 260: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-3 Exporting bundles to the new directory

The bundles are exported to that directory.

9.2.2 Exporting Web application bundlesIn this section we will cover the process of exporting a Web application to the same directory we created in the last section.

The Web application bundle that we created in Chapter 7, “HTTP services, servlets and Java server pages” on page 183 cannot be submitted the same way that the other application bundles were in the last section. A WAB file needs to be created. This WAB file is similar to a WAR file, but appropriate for the SMF environment.

To export Web application bundles, perform the following steps:

244 WCTME: Application Development and Case Study

Page 261: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

1. In the Studio workbench, SMF Perspective, select the Web application bundle you want to export, ITSORentalsWebApplicationBundle, right-click and select Export. See Figure 9-4.

Figure 9-4 Exporting a Web application

2. As in Figure 9-5 on page 246, select WAB file, then Next.

Chapter 9. Deploying a WCTME Application 245

Page 262: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-5 Exporting to a WAB file format

3. Fill in the destination name C:\ITSORentalsPC\ITSORentalsWebApplicationBundle.wab and click Finish.

See Figure 9-6 on page 247.

246 WCTME: Application Development and Case Study

Page 263: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-6 Entering a destination for the WAB file

The WAB file should have been added to the directory with the other bundles.

Now that the application has been exported, you can now proceed to create a Platform Builder Project.

9.2.3 Exporting bundles from the SMF Bundle ServerIf you want to add other system bundles to the build, you can export them from the SMF Bundler Server, or copy them from the bundlefiles directories where the tools were installed.

In Chapter 11, “Device management” on page 317 we cover the installation of an IFix. Once installed, those bundles can be exported from the bundle server and included in the platform build as custom bundles.

Chapter 9. Deploying a WCTME Application 247

Page 264: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

9.3 Creating a platform builder project This section discusses how the bundles exported in the previous section can be organized into a package that runs on a selected platform.

To create a platform builder project, execute the following steps:

1. In the Studio workbench, SMF Perspective, Select File →New →Other.

2. Select Extension Services →Platform Builder and click Next. See Figure 9-7.

Figure 9-7 Creating a platform builder project

3. Enter the name of the Project ITSO Rentals PC Platform Build, then click Next. See Figure 9-8 on page 249.

Attention: In later chapters, an update to an existing bundle will be made and a new bundle created. You can still follow the steps in this chapter, but please note that these screen shots do include those new and modified bundles.

248 WCTME: Application Development and Case Study

Page 265: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-8 Naming the platform builder project

4. As in Figure 9-9 on page 250, select the Device Type, Windows XP. In the an Output location field, you can use same directory created in the previous section, C:\ITSORentalsPC and click Next. See Figure 9-9 on page 250.

Chapter 9. Deploying a WCTME Application 249

Page 266: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-9 Selecting the build type and output directory

5. On the next screen (Figure 9-10 on page 251) you can configure some of the J9 settings for the platform build. Click Next.

250 WCTME: Application Development and Case Study

Page 267: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-10 Configuring the J9

6. On the next screen (Figure 9-11 on page 252) you can configure some of the startup options for the platform build. Click Next.

Chapter 9. Deploying a WCTME Application 251

Page 268: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-11 Configuring the startup options

7. On the next screen you can select languages for the build. Click Next.

8. On the Customer Bundles panel (Figure 9-12 on page 253), we will add all the bundles exported in the previous section. Select the Add button. Navigate to the directory where the bundles have been exported and select each bundle, then click Open.

252 WCTME: Application Development and Case Study

Page 269: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-12 Selecting the bundles to add to the build

9. The selected bundles are added to the build. See Figure 9-13 on page 254.

Note: This screen shot includes bundles installed by a required IFix. See 11.4.1, “Interim Fix 1 and IFix instructions” on page 335.

If you have not yet created the ITSORentalsDeviceManagementService bundle from Chapter 11, “Device management” on page 317, do not create them at this time. The list of required bundles will be shorter if you are not included all services.

The bundles provided in the IFix should be copied into the deployment directory for inclusion into your platform build with your custom bundles. In other words, treat the IFix bundles as custom bundles not system bundles.

Chapter 9. Deploying a WCTME Application 253

Page 270: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-13 Computing the bundles dependencies

10.Select the Compute button to resolve any dependencies that might be required by the included bundles. These dependencies are found by inspecting the MANIFEST.MF files in the bundles. See Figure 9-14 on page 255.

Note: We have also included the optional OSGi Agent Servlet (SAMPLE) for demonstration purposes. This can be used to debug the device management bundle. It is not required and can be removed.

254 WCTME: Application Development and Case Study

Page 271: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-14 Resolving the nested dependencies

11.Select the appropriate services, noting that some services might be implemented by multiple bundles. For example Web Services is a subset of Web Services Gateway, but we need the complete Web Services Gateway for our sample application. Then click Resolve... to see what these services now require. See Figure 9-15 on page 256.

Note: Again if you have not completed later chapters, then your list of required bundles will be shorter.

In Figure 9-14, notice that in some instances some bundles were not selected. In those cases, multiple bundles provide the required package or service and we have selected the one appropriate for our sample application. If you selected all the bundles and their was a duplicate, a later panel will allow you to chose between the bundles that offer the same package and service.

Chapter 9. Deploying a WCTME Application 255

Page 272: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-15 Resolving the dependencies for the sample application

12.Repeat this process until all dependencies are resolved.

If you select multiple bundles that expose the same exported package, then you will be prompted to select the one to include. For example, if you did not delete the SampleAgentExt bundle as part of the IFix, you will see that two bundles are available to resolve the dependency of the required package. See Figure 9-16 on page 257.

256 WCTME: Application Development and Case Study

Page 273: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-16 Resolving a conflict when two bundles provide the same package

13.Repeat this process until all duplicate packages, if any, are resolved and you see the message displayed in Figure 9-17.

Figure 9-17 All dependencies resolved

Chapter 9. Deploying a WCTME Application 257

Page 274: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

14.Select OK, then Next to view the system bundles. Optionally you can Add... other system bundles such as DB2 Everyplace Client, if not it is present, to your platform build.

Other bundles that can be useful for testing and debug purposes are:

– SMF Administrator (SAMPLE) (smfadmin.jar) accessed with

http:\localhost\smfadmin

– File Administrator (SAMPLE) (fileadmin.jar) accessed with

http:\\localhost\fileman

15.If you select any additional services (Figure 9-18 on page 259), repeat the Compute/Resolve cycle until all dependencies are resolved. Several cycles might be required as each new bundle’s dependencies are included. Click Next.

Note: Java classes referenced dynamically will not be picked-up automatically by this process. You need to add their bundles manually.

In Figure 9-15 on page 256, notice that DB2 Everyplace Client has been resolved. If you did not add DB2e synchronization as described in Chapter 10, “DB2e synchronization” on page 271, the DB2 Everyplace Client Sync bundle will not be there to reference the DB2 Everyplace Client bundle and you will have to Add... it manually on the next panel, Figure 9-18 on page 259.

258 WCTME: Application Development and Case Study

Page 275: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-18 The system bundles required by the sample application

16.The summary panel is displayed, as in Figure 9-19 on page 260. Click Finish.

Chapter 9. Deploying a WCTME Application 259

Page 276: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-19 The build summary

17.When the build is performed, see the build details in the console. A platform.zip file is placed in the output directory.

18.Navigate to the output directory, then unzip the platform.zip file. Explore the JVM and SMF directories. They represent everything your application should need, and could be determined by the tooling.

Platform build reviewTo create a platform build appropriate for the target device, you completed the following steps.

1. Submitted the sample application’s bundles to a directory.

2. Exported the Web application to the same directory. You also included any other bundles as necessary in that directory.

260 WCTME: Application Development and Case Study

Page 277: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3. Created a platform builder project, setting configuration properties, adding the sample application’s bundles and resolving required system bundles.

4. Performed the build.

9.3.1 Rebuilding the platform after changesIf you update and reexport your application bundles, you will need to remove and re-add them to the build definition then perform a rebuild.

Figure 9-20 Opening the Extension Services Platform Builder editor

1. Expand the platform build project down to the eswe.properties files (Figure 9-20) and double-click. This opens the Extension Services Platform Builder editor. See Figure 9-21 on page 262.

Chapter 9. Deploying a WCTME Application 261

Page 278: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-21 The Extension Services Platform builder editor

2. Select the Custom Bundles tab at the bottom. See Figure 9-22 on page 263.

262 WCTME: Application Development and Case Study

Page 279: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-22 The editor showing the custom bundles

3. Select the bundles you want to remove, and click Remove.

4. Select Add to re-add the updated bundles. Use Compute to resolve any dependencies as before.

5. Optionally you can also add and remove system bundles from the Systems Bundles tab. Again use Compute to resolve any dependencies, if you add anything.

6. Save the changes.

7. From the Package Explorer, select the builder project, right-click, select Extension Services → Build Platform... See Figure 9-23 on page 264.

Chapter 9. Deploying a WCTME Application 263

Page 280: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-23 Rebuilding a platform after changes

8. Verify the output location and click Finish.

The platform is rebuilt with the updated bundles.

9.3.2 Adding custom files to the platform buildFor our sample program to run stand-alone without a database server, the photos of the ITSO Rentals company customers, the authors of this book, have to be added manually to the build definition.

See the Additional Materials appendix to see how to download example photos for inclusion into the sample applications build.

We need to add these files to the custom/files directory of the platform build tree.

264 WCTME: Application Development and Case Study

Page 281: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

1. In the SMF perspective, expand the platform build project to the custom/files directory, as in Figure 9-24.

Figure 9-24 Adding custom files to the platform build to be included in the build output

2. Add the appropriate folders by right-clicking then New →Folder. Import by right-clicking, then selecting Import... to import the necessary files into the folders created.

3. Perform a rebuild to update the platform.zip output file.

Note: For a PC build, sample photo files must be in the custom/files/smf/demo-images directory. For a PocketPC build they should be in the custom/files/demo-images directory

Chapter 9. Deploying a WCTME Application 265

Page 282: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

9.4 Running the platform buildIn this section we run the application you just built.

Stop all servers and SMF runtimes running within the studio tool before trying to run SMF from the command line, or you might have port conflicts.

1. Navigate to the C:\ITSORentalsPC directory, created previously. Expand the platform.zip file if you have not done so already.

2. Navigate to the smf subdirectory and run StartSMF.bat.

The application bundles should all start automatically. Type “ss” (for short status) to see if all bundles have started correctly. See Figure 9-25.

Figure 9-25 Short Status showing active bundles

Type help to see a list of commands valid in the console. Later use exit to terminate the SMF environment.

3. Open Internet Explorer and point it to the sample application http://localhost/ITSORentals/CheckInAndSync. See Figure 9-26 on page 267.

Note: If any bundle is listed in a state other than ACTIVE, then some dependency has not been resolved, or an exception might have occurred. Type log at the SMF prompt for more information, if the log service is running.

266 WCTME: Application Development and Case Study

Page 283: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-26 Login panel

You are now running the sample application. See section 2.2, “Running the sample application” on page 25 on steps for running the sample application.

9.5 Deploying the sample application to a Pocket PCTo deploy the sample application to a Pocket PC, perform the following steps:

1. Repeat the platform build steps described in the previous section, but select PocketPC as the output type. See Figure 9-9 on page 250. Put the output into a separate directory, ITSORentalPPC.

2. Once you have created the platform.zip file, you need to deploy the application to the PocketPC.

3. Unzip the contents of the platform.zip file. There should be directories for smf and jvm (and demo-images). Copy these two directories to the Mobile Device/PocketPC and Active Sync will deliver the files to the device. See Figure 9-27 on page 268.

Chapter 9. Deploying a WCTME Application 267

Page 284: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 9-27 Platform.zip file contents copied to a PocketPC

4. Once the files have been copied to the PocketPC, you can launch the SMF Runtime by selecting the StartSMF shortcut and double-clicking it.

The SMF console will start. Type ss (for short status) and a listing of the bundle status will display. See Figure 9-28.

Figure 9-28 Sample application running on a PocketPC

268 WCTME: Application Development and Case Study

Page 285: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

5. Start Pocket IE and point the browser to http://127.0.0.1/ITSORentals/CheckInAndSync. The sample application should display. See section 2.2, “Running the sample application” on page 25 on steps for running the sample application.

Chapter 9. Deploying a WCTME Application 269

Page 286: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

270 WCTME: Application Development and Case Study

Page 287: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Chapter 10. DB2e synchronization

This chapter describes the architecture, configuration steps, and programming code necessary to perform a database synchronization using DB2 Everyplace in Workplace Client Technology Micro Edition (WCTME) and server side DB2 in a WebSphere Everyplace Access.

10

© Copyright IBM Corp. 2005. All rights reserved. 271

Page 288: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

10.1 IBM DB2 Everyplace overviewIBM DB2 Everyplace is a solution for pervasive computing that allows mobile users to have access to the necessary information to perform their jobs from any place, at any time. With DB2 Everyplace, users can access and update enterprise data from a database in their mobile device and keep this data synchronized to other data sources in their enterprises.

DB2 Everyplace consists of two main components:

� DB2 Everyplace database� DB2 Everyplace Sync Server

DB2 Everyplace database is the database engine installed on the mobile device. DB2 Everyplace Sync Server carries out bidirectional synchronization of data between the database on the mobile device and the source database on the server. DB2 Everyplace synchronization is controlled by DB2Everyplace Sync server.

For synchronization of the relational database from the server to the mobile device, the selected data is replicated periodically to a mirror, or mid-tier, database, which acts as a temporary data repository. A subset of the mirror data is moved to the database on the mobile device. For synchronization from the mobile device to the server, data is also moved into the mirror database first, then it is replicated to the server periodically.

Figure 10-1 shows the main DB2 Everyplace components.

Figure 10-1 DB2 Everyplace components

10.2 DB2 Everyplace in WCTMEDB2 Everyplace is a key component of the Workplace Client Technology Micro Edition (WCTME) solution, providing a relational database and enterprise synchronization system for mobile devices. As part of the WCTME solution, the

DB2 Everyplace (Database Engine)

Mobile Device

DB2 UDB/ Others

DB2 Everyplace Sync Server

Mid-tier System

Source System

272 WCTME: Application Development and Case Study

Page 289: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

DB2 Everyplace Sync client is incorporated into WCTME. The DB2 Everyplace Sync server is integrated as part of the WEA server.

10.2.1 DB2 Everyplace Sync ServerDB2 Everyplace Sync Server has been integrated into WebSphere Everyplace Access as a separate application server named IBMDB2eServer. The service is deployed in the application server as a J2EE Enterprise Application containing several servlets.

DB2e Sync Server is HTTP-based. Mobile devices can establish either a wireless or wired connection to synchronize data over the Internet, a wireless network, intranet, local area network (LAN), or wide area network (WAN).

10.2.2 DB2 Everyplace SDKEveryplace SDK is a set of tools to develop mobile device applications using the DB2 Everyplace Database and the DB2 Everyplace Sync Server.

10.3 ArchitectureThe diagram shown in Figure 10-2 on page 274 depicts the DB2 Everyplace architecture for relational database synchronization in a WebSphere Everyplace Access environment.

Chapter 10. DB2e synchronization 273

Page 290: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 10-2 DB2 Everyplace in WebSphere Everyplace Access environment

On the server side, IBM HTTP Server handles incoming HTTP requests, and passes those destined for WebSphere Application Server with a plug-in. WebSphere Everyplace Access rides on top of the WebSphere Application Server. It provides administration portlets to manage portlets as well as users and groups.

User and group information is stored within LDAP. Users and group information is accessed by DB2Everyplace server through Everyplace Access Services, specifically through the User and Group service.

Depending the type of subscription selected, DB2 Everyplace Synchronization Server periodically replicates the back-end databases to mirror databases on the server. Refer to Section 10.4, “Types of subscription” on page 275 for more details about synchronization subscriptions.

DB2 Everyplace Mobile Devices Administration Center (MDAC), together with WebSphere Everyplace Access, provides the complete administration

Note: The User and Group Web service is deployed into the WebSphere_Portal application server instance.

LDAPDirectory Services

IBM HTTP Server

Port 80

DB2e SyncBundle

WCTME

DB2e Database

DB2 Everyplace

Mobile Devices Administration

Center (MDAC)

Users and Groups

Subscription Set and

Subscriptions

DB2 Database(LDAP Data)

Source Database

(e.g. DB2 UDB)

IBM WebSphere Everyplace Access

DB2e Sync Server (Servlet)

Replication

Synchronization

MirrorDatabase

(DB2)

274 WCTME: Application Development and Case Study

Page 291: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

functionalities for DB2 Everyplace Sync Server. MDAC stores its configuration information in a DB2 database (DSYCTLDB).

When synchronization is initiated at the client, the device sends the request to the IBM HTTP Server. The user is authenticated against the user registry in LDAP. Once the user is authenticated, the DB2 Everyplace Sync Server is invoked and data synchronization is performed between the client and the mirror databases. Conversely, data can be inserted directly to the source database, depending the type of subscription used.

10.4 Types of subscriptionA subscription specifies the manner in which a source database will be replicated to the target database.

For relational database tables, there are three possible types of subscriptions:

� JDBC Subscription� DataPropagator™ subscription� Upload subscription

In addition there are two more types of subscriptions:

� File subscription is used to provide access to files.

� Custom subscription is used to customize the adapters provided by default or to use an adapter provided by a third party.

10.4.1 JDBC subscriptionJDBC subscription provides users with access to data in any source database with a JDBC interface. Triggers are inserted into the source database. The diagram shown in Figure 10-3 on page 276 depicts the relational database synchronization environment for JDBC subscription types.

Chapter 10. DB2e synchronization 275

Page 292: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 10-3 DB2 Everyplace synchronization for JDBC subscriptions

10.4.2 DataPropagator subscriptionDataPropagator subscription is used only to replicate DB2 back-end data sources with mirror DB2 database. The DB2 data source is left intact, but separate steps must be taken to enable replication between source and mirror databases. Figure 10-4 on page 277 illustrates this process.

LDAPDirectory Services

IBM HTTP Server

Port 80

DB2e SyncBundle

WCTME

DB2e Database

DB2 Everyplace

Mobile Devices Administration

Center (MDAC)

Users and Groups

Subscription Set and

Subscriptions

DB2 Database(LDAP Data)

Source Database(e.g. DB2)

JDBCJDBC

JDBC

JDBCSubscription

IBM WebSphere Everyplace Access

DB2e Sync Server (Servlet)

Replication

Synchronization

MirrorDatabase

(DB2)

276 WCTME: Application Development and Case Study

Page 293: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 10-4 DataPropagator subscription in a WebSphere Everyplace Access

Creating DataPropagator subscriptions is different for each version of DB2 installed. By default, WebSphere Everyplace Access comes with DB2 UDB.

For other resources of how to configure DataPropagator subscription, refer to the WebSphere Everyplace Access Infocenter. Navigate to the DB2Everyplace → Administering →Subscriptions →DataPropagator section.

10.4.3 Upload subscriptionThe upload subscription process, as the name suggests, is one way only. It allows the client to insert rows into the source database, but not the other way around. The source table can reside on any database that supports JDBC. There is no mirror database involved in the upload subscription process, illustrated in

Restriction: Do not create a DataPropagator subscription on tables that have referential-integrity constraints or triggers. Otherwise, replication would fail and would be unrecoverable.

LDAPDirectory Services

IBM HTTP Server

Port 80

DB2e SyncBundle

WCTME

DB2e Database

DB2 Everyplace

Mobile Devices Administration

Center (MDAC)

Users and Groups

Subscription Set and

Subscriptions

DB2 Database(LDAP Data)

Source Database

(DB2)

JDBC

JDBC

MirrorDatabase

(DB2)

IBM WebSphere Everyplace Access

DB2e Sync Server (Servlet)

Replication

Synchronization

DPropRSubscription

DPropR

Chapter 10. DB2e synchronization 277

Page 294: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 10-5. In this sample scenario, a DB2 back-end database is used as the source database.

Figure 10-5 Upload subscription: sample scenario

10.5 Filtering data from data sourcesDB2 Everyplace Sync Server includes several filtering options for horizontal, vertical, and user-based filtering methods. Data filtering is essential to reduce traffic and optimize mobile device storage.

For details on how to configure these filters, refer to the WebSphere Everyplace Access Infocenter. Navigate to the DB2Everyplace → Administering → Filters section.

LDAPDirectory Services

IBM HTTP Server

Port 80

DB2e Syncbundle

WCTME

DB2e Database

DB2 Everyplace

Mobile Devices Administration

Center (MDAC)

Users and Groups

Subscription Set and

Subscriptions

DB2 Database(LDAP Data)

Source Database

(DB2)

IBM WebSphere Everyplace Access

DB2e Sync Server (Servlet)

Synchronization

UploadSubscription

No Mirror DatabaseNo Replication Required

JDBC

278 WCTME: Application Development and Case Study

Page 295: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

10.6 Synchronization with remote DB2 databasesIn an enterprise environment, the databases are often stored on separate machines from the DB2 Everyplace server. You can synchronize with remote DB2 databases by cataloging the remote database using the DB2 CATALOG command or the Client Configuration Assistant. Once the remote database is cataloged, the procedure to create subscriptions is the same as that for local DB2 databases.

10.7 Debug and tracingIn this section, we include some useful information that you might need for problem determination when synchronizing DB2 Everyplace data in a WEA environment.

As a convention, we refer to <WebSphere_Install_Dir> as the directory where WebSphere Everyplace Access has been installed.

10.7.1 Application server logs filesThe log files for the DB2Everyplace application server are located in:

WebSphere_Install_Dir\DB2Everyplace\Server\logs\IBMDB2eServer

10.7.2 Enable tracingTo turn on tracing for DB2 Everyplace Sync Server, perform the following tasks:

1. Open and edit the file:

WebSphere_Install_Dir\DB2Everyplace\Server\properties\com\ibm\mobileservices\DSYGdflt.properties

2. Modify the key Trace.Level to:

Trace.Level = *

Tip: Keep your filters as simple as you can. A very complex filter could create excessive work for your database server and cause reliability issues. If you need a too complex filter, using the remote query and stored procedure adapter could be a better option. Refer to the WebSphere Everyplace Access Infocenter and review the DB2Everyplace →Synchronizing →The remote query and stored procedure adapter section.

Chapter 10. DB2e synchronization 279

Page 296: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3. Restart Everyplace Synchronization Server in the WebSphere Application Server Administrative Console. For information about start and stop WEA services refer to IBM WebSphere Everyplace Access V5 Handbook for Developers and Administrators Volume I: Installation and Administration, SG24-6462.

10.7.3 Trace filesThe trace files for DB2 Everyplace synchronization are named:

WebSphere_Install_Dir\DB2Everyplace\Server\logs\IBMDB2eServer\dsyXXXX.trace

In this file naming convention, XXXX=0000,0001, 0002....n. Depending on the trace file size set in DSYGdflt.properties, when the first trace file (dsy0000.trace) hits the limit, a new trace file (dsy0001.trace) is generated, and so on.

10.7.4 DB2 Everyplace control databaseAll the information configured in MDAC is stored in a control database (DSYCTLDB) in DB2. If the control database gets corrupted, it can be dropped and recreated using the batch file:

WebSphere_install_dir\WebSphere_Install_Dir\DB2Everyplace\Server\bin\dsyctldb.bat

10.8 DB2 Everyplace sample scenarioThe sample scenario consists of a database synchronization for the ITSO Rentals company sample. Figure 10-6 on page 281 illustrate the scenario components.

280 WCTME: Application Development and Case Study

Page 297: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 10-6 DB2 sample scenario components

For this scenario, the host server stores in DB2 UDB database the information about all the customers the company has. The bus driver’s hand-held device holds, in a DB2e database, all the customers arriving in the near future. The application will be able to sync that information with the use of Sync button to interact with DB2e Sync server. The driver will use this button periodically to send locally stored updates to the server and to collect any updates from the server

The following configurations will:

1. Create a database on the host server with information about customers.2. Configure a relational database synchronization on the host server.3. Create an application in the hand-held device that allow synchronization with

the server.

10.8.1 First stepsBefore you start configuring and testing relational database synchronization, it is important to make sure IBM DB2 Everyplace Server (IBMDB2eServer) and Everyplace Access Services server are running without error. Do the following:

1. Open a command line window. Navigate to WebSphere_Install_Dir\AppServer\bin and enter the following command:

Note: In this sample scenario, we refer to <WebSphere_Install_Dir> as your directory where WebSphere Everyplace Access has been installed.

Hand-held Device

HTTP

DB2e Database

ITSO Rentals Application WEA Server

DB2e Sync Server

Source Database

(DB2)

Host Server

Chapter 10. DB2e synchronization 281

Page 298: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

serverStatus -all -user <was_admin_user> -password <was_admin_password>

The Admin server user (wpsbind by default) is <was_admin_user> and <was_admin_pass> is the password for that user. Verify at least the Portal and DB2e servers have been started as shown in Figure 10-7.

Figure 10-7 Verifying the status of the servers

2. To verify the DB2Everyplace Sync service is running, open a browser and type the following into the address box:

http://db2e_server_hostname/db2e/db2erdb

Where <db2e_Server_hostname> is the name of the server where DB2 Everyplace resides. Enter the login information when prompted. In this case, you can use the WebSphere Everyplace Access administrator user. You should see the page shown in Figure 10-8, which displays information about the sync service.

Figure 10-8 DB2 Everyplace sync service

When you see this page, you are ready to proceed.

282 WCTME: Application Development and Case Study

Page 299: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3. If this page is not shown, check the following:

a. Verify the servers have been started. b. Review the log files for DB2Everyplace server, located by default at:

WebSphere_Install_Dir\DB2Everyplace\Server\logs\IBMDB2eServer directory

10.8.2 Server configurationThis section describes the necessary steps to create and configure the source database and the relational database synchronization.

In order to set up a synchronization in DB2 Everyplace, the following entities must be defined beforehand:

� Group� User� Subscription set� Subscription

A user must belong to a group. A subscription must belong to at least one subscription set. A group subscribes to one or more subscription sets for data synchronization.

For relational database synchronization, the server configuration and management activities are handled in two places: user and group management is done in WebSphere Portal, while subscription and subscription sets are managed by the Mobile Devices Administration Center (MDAC).

Creating the source databaseFor this scenario, it is necessary to create a database containing the information about the customers of the ITSO Rentals company.

� Database name: ITSORENT

� Tables:

– CUSTOMERS: contains the information about the ITSO Rentals customers.

• CUSTOMERID (Not null, primary key)• FIRSTNAME• LASTNAME• PHOTO

– CONTRACTS: contains information about the rental contracts.

• CONTRACTID (Not null, primary key)• CUSTOMERID• FLIGHT

Chapter 10. DB2e synchronization 283

Page 300: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

• STATUS• LOCATION

For synchronization purposes, it is necessary to create a mirror database used for DB2 Everyplace Sync server as a temporary repository for the data. The name of this mirror database is M_IRENT.

Run the ITSORENT.ddl file provided for this sample scenario to create and populate the database:

1. Open a DB2 Command window in Start →Programs →IBM DB2 →Command Line Tools →Command Window.

2. Execute the command db2 -vtf <ddl_path>\ITSORENT.ddl, where ddl_path is the directory where the ddl file is located.

3. Verify if the command execution was successful.

The ITSORENT.ddl contains the following SQL sentences in Example 10-1.

Example 10-1 ITSORENT.ddl

CREATE DATABASE ITSORENT;

UPDATE DB CONFIG FOR ITSORENT USING APPLHEAPSZ 2048;UPDATE DB CONFIG FOR ITSORENT USING LOGFILSIZ 1000;

CONNECT TO ITSORENT;

CREATE SCHEMA DSYITSORENT;

DROP TABLE DSYITSORENT.CUSTOMERS;DROP TABLE DSYITSORENT.CONTRACTS;

CREATE TABLE DSYITSORENT.CUSTOMERS (CUSTOMERID CHAR(15) NOT NULL PRIMARY KEY, FIRSTNAME VARCHAR(20), LASTNAME VARCHAR(25), PHOTO LONG VARCHAR FOR BIT DATA);

CREATE TABLE DSYITSORENT.CONTRACTS (CONTRACTID VARCHAR(10) NOT NULL PRIMARY KEY, CUSTOMERID VARCHAR(15), FLIGHT VARCHAR(10), STATUS VARCHAR(15), LOCATION VARCHAR(10));

INSERT INTO DSYITSORENT.CUSTOMERS VALUES('374906','Jeffrey','Martin',null); INSERT INTO DSYITSORENT.CUSTOMERS VALUES('GHJ453','David','Reich',null);INSERT INTO DSYITSORENT.CUSTOMERS VALUES('JW3G56','Gianfranco','Rutigliano',null);INSERT INTO DSYITSORENT.CUSTOMERS VALUES('DI4F56','Joel','Wickham',null);INSERT INTO DSYITSORENT.CUSTOMERS VALUES('XT345G','Sid','Perera',null);INSERT INTO DSYITSORENT.CUSTOMERS VALUES('FT3H78','Guillermo','Villavicencio',null);INSERT INTO DSYITSORENT.CUSTOMERS VALUES('JK34S5','Juan','Rodriguez',null);

284 WCTME: Application Development and Case Study

Page 301: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

INSERT INTO DSYITSORENT.CONTRACTS VALUES('1','374906','ITSO 4678','pending','?');INSERT INTO DSYITSORENT.CONTRACTS VALUES('2','GHJ453','ITSO 1982','pending','?');INSERT INTO DSYITSORENT.CONTRACTS VALUES('3','JW3G56','ITSO 329','pending','?');INSERT INTO DSYITSORENT.CONTRACTS VALUES('4','DI4F56','ITSO 6','pending','?');INSERT INTO DSYITSORENT.CONTRACTS VALUES('5','XT345G','ITSO 107','pending','?');INSERT INTO DSYITSORENT.CONTRACTS VALUES('6','FT3H78','ITSO 1245','pending','?');INSERT INTO DSYITSORENT.CONTRACTS VALUES('7','JK34S5','ITSO 11','pending','?');

COMMIT;CONNECT RESET;

CREATE DATABASE M_IRENT;UPDATE DB CONFIG FOR M_IRENT USING APPLHEAPSZ 2048;UPDATE DB CONFIG FOR M_IRENT USING LOGFILSIZ 1000;

4. To insert the pictures into the database execute the following instruction in a command line window: java ITSORentalDB. The pictures must be located in a subdirectory named demo-images.

The ITSORentalDB.class file is provided for this sample scenario and contains the code shown in Example 10-2 to convert a file to BLOB format and insert the converted file into the database.

Example 10-2 Converting a file to BLOB format

import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;

public class ITSORentalDB {

private static Connection con;private static String driver = "jdbc:db2:ITSORENT";private static Statement st;private static ResultSet rs;

Chapter 10. DB2e synchronization 285

Page 302: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

private static Object syncLock = new Object();

public static void main(String[] args){storeBlob("374906", "demo-images\\Image1.jpg");storeBlob("GHJ453", "demo-images\\Image2.jpg");storeBlob("JW3G56", "demo-images\\Image3.jpg");storeBlob("DI4F56", "demo-images\\Image4.jpg");storeBlob("XT345G", "demo-images\\Image5.jpg");storeBlob("FT3H78", "demo-images\\Image6.jpg");storeBlob("JK34S5", "demo-images\\Image7.jpg");

}

public static boolean storeBlob(String customerID, String filename) {FileInputStream fis = null;int size = 0;try {

fis = new FileInputStream(filename);size = fis.available();

} catch (IOException e) {System.out.println("Picture store (file = "+ filename +") for

customerID = "+ customerID + " failed because " + e.getMessage());}if (fis != null) {

PreparedStatement pstmt = null;synchronized (syncLock) {

try {Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");con = DriverManager.getConnection(driver);byte[] indata = new byte[size];// create a stream to read the fileDataInputStream in = new DataInputStream(fis);try {

in.readFully(indata);in.close();

} catch (IOException e1) {e1.printStackTrace();

} // Read file contents into array

pstmt = con.prepareStatement("UPDATE DSYITSORENT.CUSTOMERSSET PHOTO = ? WHERE CUSTOMERID = '" + customerID + "'");

pstmt.setBytes(1, indata);pstmt.executeUpdate();

} catch (SQLException sqlEx) {System.out.println("SQL EXCEPTION: ERROR CODE: " +

sqlEx.getErrorCode() + " state: " + sqlEx.getSQLState());sqlEx.printStackTrace();

} catch(ClassNotFoundException cnfe){System.out.println("ClassNotFoundException:

"+cnfe.toString());

286 WCTME: Application Development and Case Study

Page 303: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

} finally {try {

if (rs != null) rs.close();pstmt.close();con.close();

} catch (SQLException e1) {}

}}

} else {return false;

}return true;

}

}

Creating users and groupsDB2Everyplace supports multiple synchronization groups. Synchronization groups must be created using WebSphere Portal’s administration portlets. A user must be a member of a synchronization group in order to synchronize with the DB2 Everyplace Sync Server. When these synchronization groups are in use, their names are stored in the file DSYLDAP.properties, located at: WebSphere_Install_Dir\DB2Everyplace\Server\properties\com\ibm\mobileservices, under the key ‘SYNCGROUP’.

To use the relational database adapter, a special user and group configuration is required:

� Each group must have a prefix of DB2e (case-sensitive), such as DB2e_myemployees.

� DB2e groups should not be members of any synchronization group defined in the DSYLDAP.properties file.

� Relational Database synchronization users must be a member of one of the synchronization groups defined in the DSYLDAP.properties file.

� Relational Database synchronization users must also be a member of one group that begins with DB2e.

� Relational Database synchronization users can belong to only one DB2e group, but the user may belong to other groups in the Portal environment including other synchronization groups.

For this scenario the following groups and users will be created:

Chapter 10. DB2e synchronization 287

Page 304: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

� Synchronization group: SyncGroup� Relational database adapter group: DB2e_Sample� User: test01

The following steps demonstrate how to create groups and include users for relational database synchronization:

1. To create a synchronization group:

c. Log in to the WebSphere Everyplace Access server as an administrator, for example wpsadmin.

d. Select the Administration label.

e. Select the Access →Users and Groups option.

f. Click New Group. Enter SyncGroup as the group name as shown in Figure 10-9. Click OK.

Figure 10-9 Create synchronization group

The group should be created and a message such as User group created successfully! should appear.

g. Follow similar steps to create more synchronization groups.

288 WCTME: Application Development and Case Study

Page 305: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

After creating the desired synchronization groups, users who are expected to synchronize with the databases must be added to the synchronization groups.

2. To add users to synchronization groups, perform the following tasks:

a. Log in to the WebSphere Everyplace Access server as an administrator, for example wpsadmin.

b. Select the Administration label.

c. Select Access →Users and Groups.

d. Search to find the synchronization group.

e. Click the group name.

f. Click Add member.

g. Use the Search on field to search for users or groups.

h. Select the user test01 from the Search Results field.

i. Click OK.

You should see the new member added to the group.

As mentioned earlier, relational database synchronization users must belong to both synchronization groups and DB2e groups, the relational database adapter group.

Important: The IBM DB2 Everyplace Server uses the group SyncGroup by default. If you use a different name, for example AllSyncUsers, you will need to start up MDAC using your synchronization group, and then restart the IBM DB2Everyplace server.

The group name can be confirmed by looking at the last line of the following file:

WebSphere_Install_Dir\IBMSyncServer\db2e\Server\properties\com\ibm\mobileservices\DSYLDAP.properties

For example: SYNCGROUP=AllSyncUsers

We recommend having a parent synchronization group that contains all synchronization users, and to use this group when starting MDAC.

Tip: Use the cn attribute when search for groups.

Tip: Use the uid attribute when search for users.

Chapter 10. DB2e synchronization 289

Page 306: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3. To create a relational database adapter group:

a. Log in to the WebSphere Everyplace Access server as an administrator, for example wpsadmin.

b. Select the Administration label.

c. Select Access →Users and Groups.

d. Click New Group.

e. Enter a group name such as DB2e_Sample.

f. Click OK.

4. To add users to relational database adapter groups:

a. Log in to the WebSphere Everyplace Access server as an administrator, for example wpsadmin.

b. Select the Administration label.

c. Select Access →Users and Groups.

d. Search to find the synchronization group.

e. Click the group name.

f. Click Add member.

g. Use the Search on field to search for users or groups .

h. Select the user test01 from the Search Results field.

i. Click OK.

You should see the new member added to the group.

Note: By default the group name must begin with DB2e and be case-sensitive. You can change the user prefix in the DSYLDAP.properties file mentioned earlier, under the GROUP_PREFIX key.

Tip: After adding or removing users to a DB2e group, we recommend resetting that user in MDAC.

Tip: Use the cn attribute when search for groups.

Tip: Use the uid attribute when search for users.

290 WCTME: Application Development and Case Study

Page 307: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

For more information about creation of users and groups in WEA, refer to IBM WebSphere Everyplace Access V5 Handbook for Developers and Administrators Volume I: Installation and Administration, SG24-6462.

Creating subscription and subscription setSynchronization-related information for a relational database is defined as a subscription. Subscriptions are grouped into subscription sets to which the user groups can subscribe. We have our users and groups, so now we must define the necessary subscriptions and subscription sets to make the synchronization work.

The subscription and subscription set defined for this sample are:

� JDBC Subscription: ITSORENT_JDBC

– Source Database URL: jdbc.db2:ITSORENT

– Mirror Database URL: jdbc.db2:M_IRENT

– Subscription defined:

i. Source table: DSYITSORENT.CUSTOMERS

Target table: DSYITSORENT.CUSTOMERS

Access privileges: Delete, Insert, Select, Update

ii. Source table: DSYITSORENT.CONTRACTS

Target table: DSYITSORENT.CONTRACTS

Access privileges: Delete, Insert, Select, Update

– Subscription set: ITSORENT_SubSet

� Subscription Set: ITSORENT_SubSet

– Subscriptions: ITSORENT_JDBC

– Groups: DB2e_Sample

To create a JDBC subscription, perform the following steps:

1. Click Start →Programs → IBM DB2 Everyplace →Start Mobile Device Administration Center.

The DB2 Control Center automatically opens. As the MDAC retrieves the users and groups information from LDAP, a WebSphere Portal Server LDAP Logon window pops up and asks for the necessary information to retrieve data from LDAP. See Figure 10-10 on page 292.

Note: For relational database synchronization to work, users must exist in both synchronization groups and one relational database adapter group.

Chapter 10. DB2e synchronization 291

Page 308: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

2. Enter the LDAP administrator’s user name and password, and specify the synchronization groups defined through WebSphere Portal Server. We suggest having a parent group that contains all synchronization users. However, multiple synchronization groups can be entered and separated by semicolons. Click OK.

Figure 10-10 WebSphere Portal Server LDAP Logon window

Remember, The Sync group name is case-sensitive.

3. If you are using DB2 v8 as your database server you will see a warning message as show in Figure 10-11. MDAC has been built on the DB2 v7 Control Center, so all the Control Center functions not related to DB2 Everyplace will be disabled. Click Close.

Figure 10-11 Warning about the DB2 MDAC support

Note: Mobile Devices Administration Center starts the DB2 Control Center when starting. Therefore you might be prompted for a DB2 administrator ID and password the first time you launch the Mobile Devices Administration Center. This is most likely to occur when the WebSphere Application Server database is configured as a remote database. You can enter the login information, or cancel the dialog until it disappears.

292 WCTME: Application Development and Case Study

Page 309: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

4. You might see a message about performing a check on existing JBDC subscriptions for needed indexes. If this is the first time you use the MDAC after installation, there are no subscriptions to analyze. So for this time click No or Ask again later.

The Mobile Devices Administration Center launches, as in Figure 10-12.

Figure 10-12 Mobile Device Administration Center

5. Click the Groups and Users folders to check that the DB2e groups and users are imported into the MDAC.

6. Right-click Subscription →Create →Table Subscription →JDBC Subscription.

The Create JDBC Subscription wizard opens. See Figure 10-13 on page 294.

Note: JDBC Subscription is used in this scenario. Other types of subscription will be covered in later sections.

Chapter 10. DB2e synchronization 293

Page 310: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 10-13 Create JDBC Subscription wizard

7. Enter the name of the subscription and, optionally, a description. In this sample the name is ITSORENT_JDBC. Click the Source tab.

8. In the Source tab, the source database information should be provided.

a. In the Database URL field, enter the source database URL, for example jdbc:db2:ITSORENT. Or you can also use the ... button besides this field to browse and choose the source database. This is only for DB2 databases.

b. In the Driver field, use the down arrow to choose the desired JDBC driver from the list.

c. In the User ID field, provide the user ID that can be used to access this database.

d. In the Password and Verify Password fields, enter the password.

e. Click Test Connection to verify the connection to the database.

Figure 10-14 on page 295 shows the source database configured.

294 WCTME: Application Development and Case Study

Page 311: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 10-14 Create JDBC Subscription: define source database

9. When you are finished done, click the Mirror tab.

In this tab, the mirror database information should be provided.

a. In the Database URL field, enter the mirror database URL, for example jdbc:db2:M_IRENT. Or you can also use the ... button besides this field to browse and choose the source database.

b. In the User ID field, provide the user ID that can be used to access this database.

c. In the Password and Verify Password fields, enter the password.

d. Click Test Connection to verify connection to the database.

e. When you are finished, click the Identification tab.

Figure 10-15 on page 296 shows the configured mirror database.

Chapter 10. DB2e synchronization 295

Page 312: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 10-15 Create JDBC Subscription: define mirror database

10.On the Identification tab, click the Define subscription button.

a. The Define Replication Subscription window is shown (Figure 10-16). Click Add.

Figure 10-16 Create JDBC Subscription: define subscription

b. The Add Table window is displayed. See Figure 10-17 on page 297.

296 WCTME: Application Development and Case Study

Page 313: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 10-17 Create JDBC Subscription - define subscription - add table

c. Select the table to be synchronized. In this sample select DSYITSORENT.CUSTOMERS. The Target schema and Target table fields are filled in automatically. Accept the default or change it to anything desirable.

d. Click the appropriate Access Privileges. In this sample select Delete, Insert, Select and Update. Click Add.

e. Add DSYITSORENT.CONTRACTS table and configure in the same way as DSYITSORENT.CUSTOMERS table. When you are finished, click Close.

Chapter 10. DB2e synchronization 297

Page 314: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

The tables have been added to the subscription now. See Figure 10-18 on page 298.

Figure 10-18 Create JDBC Subscription: define subscription

f. Click the Timing button to adjust the replication frequency (Figure 10-19).

Figure 10-19 Adjust replication frequency

g. Click OK and OK to return to the Create JDBC Subscription wizard.

11.Click the Subscription sets tab. See Figure 10-20 on page 299.

298 WCTME: Application Development and Case Study

Page 315: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 10-20 Create JDBC subscription: define subscription set

a. Choose from the available subscription sets in the left pane and click > to put it into the right pane. The subscription sets shown in the right pane will include this newly created subscription.

b. You can also choose to create a new subscription set by clicking the Create button. The Create Subscription Set wizard will be covered later.

12.Now all the information has been gathered for the subscription. Click OK.

13.The new subscription should appear in the right pane when clicking the Subscriptions folder. It can always be altered by right-clicking the subscription and choosing Edit.

To create a subscription set, perform the following steps:

1. With MDAC open, right-click Subscription sets →Create...

The Create Subscription Set wizard opens. See Figure 10-21 on page 300.

Chapter 10. DB2e synchronization 299

Page 316: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 10-21 Create Subscription Set wizard

2. On the Identification tab, enter the name and description for this subscription set. In this sample the name is ITSORENT_SubSet. Click the Subscriptions tab.

3. As in Figure 10-22, choose ITSORENT_JDBC from the available subscriptions in the left pane and click > to include it in this subscription set.

Figure 10-22 Create Subscription Set : select to include subscription

4. You can also click the Create button to create a new subscription, following the steps described in the previous section.

300 WCTME: Application Development and Case Study

Page 317: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

5. When you are finished, click the Groups tab. See Figure 10-23.

6. Choose DB2e_Sample from the available groups in the left pane and click > to subscribe it to this subscription set.

Figure 10-23 Create Subscription Set - select groups

7. Enough information has been collected to create a subscription set. Click OK.

8. The newly created subscription set should appear in the right pane of MDAC when you click the Subscription sets folder. It can be easily modified or examined by right-clicking the subscription set and choosing Edit.

9. Now click the Groups folder. In the right pane, for each group, the number appearing in the Subscription sets column indicates the number of subscription sets to which a group subscribes. See Figure 10-24 on page 302.

Chapter 10. DB2e synchronization 301

Page 318: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 10-24 MDAC groups

10.The association with the subscription sets can be easily changed by right-clicking the group and choosing Edit. Select or deselect subscription sets in the Subscription sets tab (Figure 10-25).

Figure 10-25 MDAC groups: change subscription sets

Binding LDAP and MDACAs discussed in previous sections, users and groups are created in WebSphere Portal and maintained in LDAP. The Mobile Devices Administration Center or MDAC retrieves this information from LDAP and keeps a copy in its control database, DSYCTLDB.

302 WCTME: Application Development and Case Study

Page 319: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

In MDAC, it is possible to refresh this binding if any changes take place in WebSphere Portal.

� To refresh group information, right-click the Groups folder and select Refresh WPS LDAP groups.

� To refresh user information, right-click the Users folder and select Refresh WPS LDAP users.

By refreshing, any added new users or groups will be brought into the MDAC and its control database.

If any user is removed from the sync group in WebSphere Portal, upon refreshing the LDAP users, MDAC warns you of the inconsistency and prompts you to delete the user from MDAC’s control database. Click Yes to delete the user from MDAC and click OK to confirm the deletion.

If any DB2e group is removed from WebSphere Portal, upon refreshing the Portal Server LDAP groups, MDAC warns you of the inconsistency and prompts you to delete the group from MDAC’s control database. Click Yes to delete the group from MDAC and click OK to confirm the deletion.

Optional server configuration testUsing the DB2 Everyplace Client in your device, you can test if the server configuration is working appropriately. To do that, follow these steps:

1. Install and configure the DB2 Everyplace Client in your device.

2. Start a database synchronization with DB2 Everyplace Sync server.

3. When the synchronization ends, review the logs in your device to obtain information about the synchronization session.

4. You can verify the synchronization results in your device using the DB2eCLP tool to connect to the device database and query the customer and contract tables. DB2eCLP is a tool that comes with DB2 Everyplace:

Note: For more information about DB2 Everyplace client and the DB2eCLP tool, refer to these IBM Redbooks:

� IBM WebSphere Everyplace Access V5 Handbook for Developers and Administrators Volume I: Installation and Administration, SG24-6462

� IBM WebSphere Everyplace Access V5 Handbook for Developers and Administrators Volume III: E-Mail and Database Synchronization, SG24-6676.

Chapter 10. DB2e synchronization 303

Page 320: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

10.8.3 Programming database synchronization using WCTMEIn Chapter 4, “Database” on page 83 we created a database bundle that managed the access to the local DB2e database. We included the interface for the database sync, but not the full implementation. In this section we will add the code necessary to complete a database synchronization with the host server.

DescriptionIn this section, we add a class to the database service bundle that provides the sync functionality with the host database server.

The class ISyncSample.java comes directly from the DB2e SDK, with only a few modifications to make it appropriate for our sample application.

These modifications include:

� Add a package statement to fit our bundle model.

� Change the runSample method parameter to use our sample application’s properties object instead of creating its own. We have included all of the parameters required by the ISyncSample code into the sample application’s properties file.

� Change the runSample method signature to return a String that represents the results of the sync, instead of a void.

� Comment out the Class.forName() call since it is not needed in the SMF bundle environment.

Procedure

First we need to update the database bundle to hold the sync class.

1. If WebSphere Studio Site Developer is not running, click Start → Programs → IBM WebSphere Studio →Site Developer 5.1.x.

2. Open the SMF Perspective. Select Window → Open Perspective →SMF.

Note: We could have simplified or removed more of the code from the original ISyncSample.java taken from the DB2e SDK, file but have left it in for reference.

Note: Make sure you have completed the steps necessary to configure your development environment to find the DB2e ISync drivers. See the complete steps necessary in the Procedure section of Chapter 4, “Database” on page 83.

304 WCTME: Application Development and Case Study

Page 321: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3. Make sure you are on the Package Explorer tab. Select the ITSORentalsDatabaseServiceBundle project, right-click and select Properties, then select Extension Services.

4. Verify that the check boxes next to DB2 Everyplace and DB2 Everyplace ISync Client are selected. Click OK.

5. Open the ITSORentalsDatabaseServiceBundle and navigate to the package com.itso.rentals.database.

6. Select the package com.itso.rentals.database, and right-click. From the pop-up menu select New → Class.

7. Enter the name ISyncSample and then click Finish.

8. Replace the class contents with the following code in Example 10-3.

Example 10-3 ISynchSample code

package com.itso.rentals.database;

/************************************************************************ * * Licensed Materials - Property of IBM * Program Name: IBM DB2Everyplace Sync Client GUI * (c ) Copyright IBM Corp. 1999-2003. All Rights Reserved. * * US Government Users Restricted Rights * Use, duplication or disclosure restricted by GSA ADP Schedule * Contract with IBM Corp. Licensed Materials - Property of IBM * * IBM grants you ("Licensee") a non-exclusive, royalty free, license to * use Sample Code. This software is provided as-is and without any * warranties, whether EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED * WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NON-INFRINGEMENT. IBM AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY * DAMAGES SUFFERED BY LICENSEE THAT RESULT FROM YOUR USE OF THE SOFTWARE. * IN NO EVENT WILL IBM OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, * PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE * THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE * SOFTWARE, EVEN IF IBM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGES. ************************************************************************* *//************************************************************************ * * File Name:ISyncSample.java * Description:Sample application to demonstrate the ISync Java Client API *

Chapter 10. DB2e synchronization 305

Page 322: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

************************************************************************ */

import java.lang.*;import java.sql.*;import java.util.*;

/*Import the ISync Java Client Package

*/import com.ibm.mobileservices.isync.*; import com.ibm.mobileservices.isync.event.*;

/**<p>This is a sample application to demonstrate the ISync Java Client API.</p>

<p>Usage: java ISyncSample &lt;property file&gt;e.g java ISyncSample isyncdb2e</p>

<p>You must specify a .properties file specific to each provider that contains the synchronization parameters.

DB2:isyncdb2DB2e:isyncdb2eDB2j:isyncdb2j

</p>

<p>Required ISync libraries:

DB2/DB2j: db2jisync.jarDB2e: isync4j.jar + native libraries

</p>*/

public class ISyncSample implements ISyncListener{

// Synchronization objectsprivate ISyncProvider provider;private ISyncService service;private ISyncConfigStore config;private ISyncDriver syncer;

// Synchronization parameters

private static PropertyResourceBundle configProps;

306 WCTME: Application Development and Case Study

Page 323: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

private Properties userProps = new Properties();private ISyncSubscriptionSet ssArr[] = null;

/*Implement the eventIssued() method in the ISyncListenerinterface if you are interested in event notification (optional)

*/

public int eventIssued(ISyncEvent evt) {

int evtType = evt.getEventType();int evtCode = evt.getEventCode();switch(evtType) {

// Display event statuscase ISync.EVTTYPE_INFO: case ISync.EVTTYPE_ERROR:

System.out.println ("*********************");System.out.println ("SubsSet: " +

evt.getSubscriptionSetName());System.out.println ("Subs: " + evt.getSubscriptionName());System.out.println ("SubsType: " + evt.getSubscriptionType());System.out.println ("Event Type: " + evtType);System.out.println ("Event Code: " + evt.getEventCode());System.out.println ("Progress: " + evt.getSyncProgress());System.out.println ("**********************\n");return ISync.RTNCB_DONE;

case ISync.EVTTYPE_RETRY:

System.out.println ("*********************");System.out.println("Retry...");System.out.println ("*********************");return ISync.RTNCB_REPLY_YES;

case ISync.EVTTYPE_CONFLICT:

if (evtCode == ISync.EVT_CFT_REJECT) {

System.out.println ("*********************");System.out.println("Conflict detected!");System.out.println ("*********************");

ConflictReader cr = (ConflictReader)evt.getEventInfo();processRejectedData(cr);return ISync.RTNCB_DONE;

}

Chapter 10. DB2e synchronization 307

Page 324: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

break;

case ISync.EVTTYPE_QUERY:

// Local data encryption case - DB2e only (optional)if (evtCode == ISync.EVT_QUE_LOGIN){

String login[] = (String [])evt.getEventInfo();System.out.println("Querying login for local encryption.");System.out.println("Subscription: " + login[0]);

login[1] = userProps.getProperty("target.db.user");login[2] = userProps.getProperty("target.db.password");return ISync.RTNCB_DONE;

}else if (evtCode == ISync.EVT_QUE_SUBSCRIPTION_TARGET){

// Specify multiple directories for sync (optional)int subsType = evt.getSubscriptionType();String login[] = (String [])evt.getEventInfo();

if (subsType == ISync.SUBSTYPE_FILE)login[0] = userProps.getProperty("filesubdir");

elselogin[0] = userProps.getProperty("jdbcsuburl");

System.out.println("Sample set subs " + login[0]);return ISync.RTNCB_DONE;

}

break;

// Ignore other event typesdefault:

break;}

// Let sync engine take default actionreturn ISync.RTNCB_DEFAULT;

}

// Sample processes INSERT and UPDATE operations onlyprivate void processRejectedData(ConflictReader cr) {

int op;ResultSet pkrs = null;ResultSet rs = null;String cmsg;

308 WCTME: Application Development and Case Study

Page 325: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

if (cr == null) return;

try{

op = cr.getOperation();cmsg = "Conflicts detected in Table: " + cr.getTableName();System.out.println (cmsg);if (op != ISync.OP_DELETE){

rs = cr.getRejectedRows();processResultSet(rs);

}else

System.out.println ("A deleted row was rejected");}catch (ISyncException iex) {

iex.printStackTrace();System.out.println (iex.getCode());

}catch (SQLException sqlex){

sqlex.printStackTrace();while(sqlex != null){

System.out.println("SQLERROR: \n" + sqlex.getErrorCode() + ", SQLState: " + sqlex.getSQLState() + ", Message: " + sqlex.getMessage() +", Vendor: " + sqlex.getErrorCode());

sqlex = sqlex.getNextException();}

}

System.out.println("");} // processRejectedData

private void processResultSet(ResultSet rs) throws SQLException {

ResultSetMetaData rsmd = rs.getMetaData();int numCols = rsmd.getColumnCount();String name;int type;int i = 0;

while (rs.next()) {

i = 1;

Chapter 10. DB2e synchronization 309

Page 326: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

while (i <= numCols) {

name = rsmd.getColumnName(i);type = rsmd.getColumnType(i);System.out.print (name + ":");

//BLOB - use getBytes()if (type == Types.LONGVARBINARY){

byte[] data = rs.getBytes(i);

if (data == null) {

System.out.print(" ( " + type + " ) ");System.out.print(" [ NULL ] ");

}else {

System.out.print(" ( " + type + " ) ");System.out.println(" [ BLOB:" + data.length + " ] ");

}}//Sample uses getString() for other typeselse {

String s = rs.getString(i);

if (s == null) {

System.out.print(" ( " + type + " ) ");System.out.print(" [ NULL ] ");

}else {

System.out.print(" ( " + type + " ) ");System.out.print(" [ " + s + " ] ");

}}

i++;

} //while numCols

} //while rs.next

rs.close();

} //processResultSet

310 WCTME: Application Development and Case Study

Page 327: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

private void readProperties(String propFile){

// Required properties for sampletry{

configProps = (PropertyResourceBundle) ResourceBundle.getBundle(propFile);

userProps.put("syncdriver", configProps.getString("syncdriver"));userProps.put("syncprotocol", configProps.getString("syncprotocol"));userProps.put("server.url", configProps.getString("server.url"));userProps.put("target.db.driver",

configProps.getString("target.db.driver"));userProps.put("target.db.url",

configProps.getString("target.db.url"));userProps.put("isync.user", configProps.getString("isync.user"));userProps.put("isync.password",

configProps.getString("isync.password"));userProps.put("isync.timeout",

configProps.getString("isync.timeout"));userProps.put("isync.trace", configProps.getString("isync.trace"));userProps.put("path", configProps.getString("path"));userProps.put("jdbcsuburl", configProps.getString("jdbcsuburl"));userProps.put("filesubdir", configProps.getString("filesubdir"));

}catch (MissingResourceException mre){

throw mre;}

// Optional properties for sampletry{

if (configProps.getString("target.db.user") != null)userProps.put("target.db.user",

configProps.getString("target.db.user"));if (configProps.getString("target.db.password") != null)

userProps.put("target.db.password", configProps.getString("target.db.password"));

}catch (MissingResourceException mre){}

} //readProperties

// public void runSample(String propFile)public String runSample(Properties p)

Chapter 10. DB2e synchronization 311

Page 328: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

{String results = "Sync failed. Look for exception in log.";

try {

int rc = 0;

// Read properties file// readProperties(propFile);

userProps = p;

// Load sync driver// Class.forName(userProps.getProperty("syncdriver"));

// Get an instance of synchronization service from the manager

provider = ISyncManager.getISyncProvider(userProps.getProperty("syncprotocol"));

service = provider.createSyncService(userProps.getProperty("server.url"), userProps);

// Get an instance of the configuration store

config = service.getConfigStore(userProps.getProperty("path"));

// Get an instance of the sync driver to perform synchronization

syncer = config.getSyncDriver();

// Set the listener object for event notification from the syncer object

// during synchronization (optional)

syncer.setSyncListener(this);

// Perform synchronization on all enabled subscription sets

rc = syncer.sync();

switch (rc) {

case ISync.RTN_SUCCEEDED:System.out.println("Synchronization succeeded");results = "Synchronization succeeded";break;

case ISync.RTN_CANCELED:System.out.println ("Synchronization canceled");results = "Synchronization canceled";

312 WCTME: Application Development and Case Study

Page 329: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

break;

default: System.out.println ("Synchronization failed");results = "Synchronization failed";break;

}

ssArr = config.getSubscriptionSets();

for (int i=0; i < ssArr.length; i++) {

System.out.print ("Subscription Set: " + ssArr[i].getName() + " Status: ");

switch(ssArr[i].getStatus()){

case ISync.STATUS_READY:System.out.println("READY");break;

case ISync.STATUS_COMPLETED:System.out.println ("COMPLETED");break;

case ISync.STATUS_CANCELED: System.out.println ("CANCELED");break;

default: System.out.println ("FAILED");break;

}}

}catch (ISyncException ie){

System.out.println("Exception code: " + ie.getCode());results = "Synchronization failed with code: " + ie.getCode();

// ie.printStackTrace();}catch (Exception e) {

results = "Synchronization failed with exception: " + e.getMessage();// e.printStackTrace();

} finally {

Chapter 10. DB2e synchronization 313

Page 330: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

try {

// Close and free allocated resources by the syncer objectif (syncer != null){

syncer.close();syncer = null;

}

// Close and free allocated resources by the config objectif (config != null) {

config.close();config = null;

}

// Close and free allocated resources by the service objectif (service != null) {

service.close();service = null;

}}catch(ISyncException ie2){

System.out.println("Exception code: " + ie2.getCode());ie2.printStackTrace();

}} //finally

return results;} //runSample

public static void main (String[] args) {

if (args.length == 1) {

ISyncSample sample = new ISyncSample();// sample.runSample(args[0]);

}else

System.out.println("Usage: java ISyncSample property_file");}

} //class ISyncSample

9. Save the file.

314 WCTME: Application Development and Case Study

Page 331: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Now that we have the sync code in our bundle, we need to call it when the application’s Sync button is selected.

10.Open the file ITSORentalsDatabaseImpl.java and find the following code in the sync method (Example 10-4).

Example 10-4 Sync code

return "Not implemented yet!";

11.Replace that code with the following:

//only allow one thread to access DB2esynchronized (syncLock) {

ISyncSample i = new ISyncSample();return i.runSample(userProps);

}

12.Save the file.

13.Submit the updated bundle to the bundle server and install into your runtime environment.

10.8.4 Synchronization review To complete a sync with a real sync server you need to have installed and configured the sync server, created sync user ID and passwords, created the host side database tables, mirror tables and subscriptions and started all services on the host sync server.

You also need to go to the configuration page of the sample application and disable Database Sync stand-alone mode, then configure the properties for DB2e sync host and port, using the format:

http://sync_server_hostname.your_company.com:80

10.9 Hints and tipsHere are some best practices to make your project go more smoothly:

� It is always a good idea to test your connection when defining subscriptions.

Note: The stand-alone, demonstration data in the local database tables will be overridden by the server’s data during the first sync. After that first sync, any updates will be exchanged during future syncs.

Chapter 10. DB2e synchronization 315

Page 332: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

� Note that by default, DB2 8 Workgroup Edition comes with a number of maximum active database parameter configured to 8. You should change this parameter depending of the number of active database in your installation.

� After defining a subscription, check in the MDAC under Logs →Replication if there is any replication activity started and ended successfully for the newly defined mirror database. If there is not, the subscription is probably not configured properly and you will need to delete it then define it again.

� When the database is large, make sure to configure a big enough log file size for the mirror database, because all the records are processed in a single transaction. Otherwise, replication can fail.

� When the database is large and replication takes a much longer time, make sure to leave enough time between each replication. Otherwise, replication can fail.

� After a successful sync of the client with the sync server, if you delete the local database directory on the device, you will need to reset, on the sync server, the sync user ID that your are using before you can sync again. To reset a user, right-click in the particular user and choose Reset.

� After a successful sync of the client and the sync server, if you change the sync user ID that the sample application uses, you will need to reset, on the sync server, the sync user ID that was previously used, because both cannot be registered to the same device at the same time. To reset a user, right-click in the particular user and choose Reset.

� When synchronization fails with no apparent reasons, try resetting the user in MDAC by right-clicking the particular user and choose Reset.

316 WCTME: Application Development and Case Study

Page 333: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Chapter 11. Device management

This chapter describes the architecture, configuration steps and programming code necessary to manage OSGi devices using Workplace Client Technology Micro Edition (WCTME) and Device Manager in a WebSphere Everyplace Access environment.

11

© Copyright IBM Corp. 2005. All rights reserved. 317

Page 334: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

11.1 Device management overviewThe increasing number of mobile devices on the market and the growing complexity of the software in these devices are the biggest barriers to overcome in the adoption of mobile and wireless data services.

Device Manager offered by WebSphere Everyplace Access provides the ability for an Enterprise to administrate a wide range of pervasive devices as personal digital assistants, handheld PCs, workstations, notebook computers, cellular phones and other devices for pervasive computing. Device Manager can be used for device configuration, inventory collection, software distribution and removal, and initial provisioning of devices.

Device Manager supports industry standards as the Open Mobile Alliance Device Management (OMA DM) and the Open Service Gateway Initiative (OSGi).

OSGi (Open Service Gateway Initiative) is a standard way to manage devices, such as automotive devices (telematics), smart home devices (home appliances, security systems, energy management systems), and mobile devices (cellular phones, and PDAs). Software for OSGi devices is distributed as OSGi bundles. The OSGi bundle contains all the interfaces, classes, a manifest file, and resource files in a JAR file.

Device Manager server is basically constituted by a collection of servlets, including a device plug-in for each class of managed device, running on an application server and a relational database to store device management data. Managed devices require an agent to interact with the server.

To manage an OSGi device, the plug-in and the device agent for OSGi devices are needed. The plug-in is programmed as a servlet and resides on the Device Manager server. The OSGi plug-in is installed with Device Manager. The plug-in interfaces with the Device Manager server to handle the running of jobs and to manage the state of each session. The plug-in and the device agent communicate with each other using the SyncML DM protocol over HTTP or HTTPS to perform system management tasks.

Device Manager is leveraging the SyncML DM stack and OSGi functions for the Windows 32-bit device agent and plug-in. In addition, the SyncML DM protocol is extended to support added function not defined by the SyncML DM standard, such as automatic bundle prerequisite loading and tuning for the prerequisite resolution for OSGi bundles.

318 WCTME: Application Development and Case Study

Page 335: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

11.2 ArchitectureFigure 11-1 shows the different components of the device management services in WebSphere Everyplace Access. In this section each component is briefly explained.

Figure 11-1 WebSphere Everyplace Access Device Manager

11.2.1 Device ManagerThe Device Manager is a set of servlets executing in the application server. Device Manager executes the management tasks or jobs on the connected devices.

Device Management Server includes a DM servlet that ensures that the device is enrolled with the server. For enrolled devices, the DM servlet checks if there are any pending jobs for the device and processes them after prioritizing the jobs. The DM servlet processes the jobs using the device plug-ins that interact with the device.

Device plug-ins are responsible for device identification, communication with the device, processing jobs on the device, and high-level management of tasks. A plug-in is provided for different classes of devices and is extensible to support new devices types. The following plug-ins are provided in the Device Manager:

WebSphere Application Server

WinCEOSGi Device

Portal Server

Device ManagerAdmin Portlets

EveryplaceAccess

ConfigurationManager

DeviceManagerConsole

JobsDevice Specific Information

DeviceManagerServer

OtherPlug-ins

WinCEOSGiPlug-in

OSGiPlug-in

GenericOSGi

Device

HTTPServer

JDBC

DB2

Chapter 11. Device management 319

Page 336: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

� OSGi plug-in � WinCEOSGi plug-in � SyncML DM plug-in � Nokia OMA DM plug-in � Palm OS plug-in � Sharp Linux Zaurus plug-in � Sony Ericsson P900 plug-in � Windows CE plug-in � Windows 32-bit plug-in

The available job types for OSGi devices consist of the following types:

� Bundle control performs actions on OSGi bundles as start, stop, uninstall or update bundles.

� Command script runs SyncML commands to perform operations on target devices or to return device information.

� Custom command builds a free-form command.

� Device configuration changes device configuration parameters.

� Inventory collection:collects hardware and software information from devices.

� Node discovery finds all subnodes on the target device from a starting node in the SyncML DM tree.

� Software distribution distributes OSGi bundles to target devices.

� Software list update provides a list of available software that is registered in the Device Manager database.

� Software removal removes OSGi bundles form target devices.

11.2.2 OSGi AgentThe OSGi Agent resides on the device. The OSGi Agent is responsible for executing the commands sent by the Device Management Server. The Client connects and interacts with the Device Management Server using the SyncML/DM protocol and is part of the WCTME framework. The OSGi Agent need not be connected to the server all the time. When the agent connects, the server identifies the client and executes the jobs pending for this device.

11.2.3 Device Manager databaseThe Device Manager database is a relational database that stores all the device management information. This database stores device-specific information, including the jobs for the devices. The Device Manager database is created with all the necessary tables, views and queries.

320 WCTME: Application Development and Case Study

Page 337: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

11.2.4 Device Management portletsDevice Management portlets are installed with the WebSphere Everyplace Access core services. They provide a simplified user interface to create software installation and removal jobs. For the complete set of options you have to use the Device Manager Console.

11.2.5 Device Manager ConsoleThe Device Manager console is a Java program that you can use to administer and monitor the Device Management Server. The console provides functionality to register and view devices, create jobs for viewing or modifying device or software properties, view the status of the jobs, and so on.

The Device Manager console can be downloaded from the Device Management Server and installed on any system. This allows administrators of the devices to control devices from various terminals and not necessarily on the server. The Device Manager console requires a DB2 database client for connecting to the Device Management database.

The first time the Device Manager console is started, it must be able to connect to the Device Management Server to login and retrieve the properties file. Device Manager console creates a backup of the properties file and subsequent start up will not need to connect to the Device Management Server for login and will connect directly to the Device Manager database for administration.

11.3 OGSGi device sample scenarioThis sample scenario shows how to distribute software to OSGi devices using Workplace Client Technology Micro Edition (WCTME) framework and Device Manager provided by WebSphere Everyplace Access. In this section, we show you how to use Device Manager to configure software distribution and software removal jobs for OSGi devices, and the necessary program code to communicate ITSO Rentals application with Device Manager server to execute these jobs.

Before we begin with the scenario, certain configurations have to be completed:

1. WebSphere Everyplace Access server must be installed and configured, including Device Manager component.

2. A Device Manager administration group must exist.

Note: The Device Manager console connects to the WebSphere Everyplace Access Subscription Manager to authenticate the user.

Chapter 11. Device management 321

Page 338: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

a. Check if the user group dmadmins exists. This should have been created automatically during the installation of WebSphere Everyplace Access.

b. If not, create a user group with the name dmadmins. The name should be exactly the same. Otherwise, Device Management Services will not work.

c. Add the Portal administrator, usually wpsadmin, as a member of the group. When using Device Management Services, you must log in as the administrator who is a member of the dmadmins group

3. Download and start the Device Manager console. Login in the console as an administration user. The user must be a part of the dmadmins user group that you created.

11.3.1 Software distribution for OSGi bundlesDistributing software to devices is the most common application of device management. As we mentioned before, software for OSGi devices is distributed as OSGi bundles.

Distributing software requires you to:

1. Create the bundle distribution package2. Register the software with the Device Management Server3. Create a job for distributing it

Creating the bundle distribution packageAn OSGi bundle is comprised of Java classes and other resources which together can provide functions to device owners and provide services and packages to other bundles. A bundle is distributed generally as a JAR file.

An OSGi bundle contains the following resources and information:

� Resources to implement zero or more services

These resources can be class files for the Java programming language and other data, such as HTML files, help files, and icons.

� A manifest file describing the contents of the JAR file and providing information about the bundle

Note: Refer to IBM WebSphere Everyplace Access V5 Handbook for Developers and Administrators Volume I: Installation and Administration, SG24-6462 for more information about Device Management configuration in WebSphere Everyplace Access environment.

322 WCTME: Application Development and Case Study

Page 339: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

The manifest file uses headers to specify parameters that are needed to install and activate a bundle.

� The dependencies on other resources, such as Java packages, that must be available to the bundle before the bundle can run

The dependencies for these packages are resolved prior to starting a bundle.

� A special class in the bundle to act as the bundle activator

The class is instantiated and invoked to start and stop methods, which are used to start or stop the bundle. Clean-up operations can be performed when the bundle is stopped.

� Optional documentation of the JAR file or one of its subdirectories

The documentation must not be required to run the bundle. Once a bundle is started, the functions and services are exposed to other bundles.

Registering the software with the Device Management ServerAn administrator places the bundle on a content server, then uses the Device Manager console to register the software with Device Manager so that it is available for distribution to devices with a software distribution job. The content would be an HTTP Server. You will need to put the package there, then register it.

1. Open the Device Manager console and login as an administrator user (Figure 11-2).

Figure 11-2 Open Device Manager console

2. In the left panel (Figure 11-3 on page 324), right-click in Software and select New Software.

Chapter 11. Device management 323

Page 340: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 11-3 Select New Software option

3. In the New Software properties window (Figure 11-4 on page 325) enter the following:

– Software type: as we are distributing software for OSGi devices, select OSGi bundle.

– URL: Fully qualified URL for the content server where the OSGi bundle package is located.

– Click Fetch. The software name, version and description are retrieved from the manifest file as shown in Figure 11-4 on page 325. If not, you could edit these fields.

– Click Next.

324 WCTME: Application Development and Case Study

Page 341: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 11-4 New software properties

4. Select all the device class and job type combinations you require (Figure 11-5 on page 326). For this scenario select, at least, OSGi - Software Distribution. Click OK.

Chapter 11. Device management 325

Page 342: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 11-5 Available job types per device class

5. The software will be registered (Figure 11-6). To check it click the Software tab and select Return Anything.

Figure 11-6 Software registered

Creating a software distribution jobWith the Device Manager console, you can create jobs for specific devices, user groups, device classes, enrolled devices, and so on. For OSGi devices, you can create the following types of jobs:

� Bundle control� Command script� Custom command� Device configuration� Inventory collection� Node discovery� Software distribution

326 WCTME: Application Development and Case Study

Page 343: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

� Software list update� Software removal

We will create a software distribution job for all the OSGi devices to install a specific bundle.

To create a software distribution job, perform the following tasks:

1. In the Device Manager console, right-click Jobs and select Submit Job.

2. Select the following options in the Target Devices window (Figure 11-7):

– Device class: since this is a software distribution for OSGi devices, select OSGi.

– Query: for this example we will distribute the software to All OSGi devices

– Owner group: select an option if you want.

– Select if the job is for enrolling o already enrolled users. In this example is for both enrolling and currently enrolled.

– Click Next.

Figure 11-7 Target devices

Chapter 11. Device management 327

Page 344: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

3. In the Submit Job: Attributes pane, Figure 11-8, select Software Distribution as the job type. Enter adequate dates for activation and expiration fields, priority and a description for the package. Click Next.

Figure 11-8 Attributes

4. In the Submit Job: Job Parameters pane, Figure 11-9 on page 329, Click Add Group and select the software to be distributed (the OSGi bundle registered on Section , “Registering the software with the Device Management Server” on page 323). In Auto start option choose True if you want to automatically start the bundle in the target device, or False if not. Click Next.

328 WCTME: Application Development and Case Study

Page 345: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 11-9 Software to be distributed

5. Review the job summary and click Ok. See Figure 11-10.

Figure 11-10 Job summary

6. You will be shown a job submission status (Figure 11-11 on page 330). Click Close.

Chapter 11. Device management 329

Page 346: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 11-11 Job submission status

7. The job has been created successfully. To see the job, click Jobs (Figure 11-12), select Return Anything and click OK.

Figure 11-12 Job registered

Job progressTo check the progress of a job, perform the following steps:

1. To verify the status of your job, click Jobs. Click Target Device Class. Select Return anything with a device class that matches. Select OSGi and click OK.

2. You should be able see the job in your list. Right-click the job and select the View Job Progress Summary option. This will show the current status of the job as shown in Figure 11-13 on page 331.

330 WCTME: Application Development and Case Study

Page 347: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 11-13 Job progress summary

11.3.2 Software removal for OSGi bundlesWith the software removal job, you can remove software that was distributed as OSGi bundles and, optionally, remove any other bundles that only the recently unistalled bundled was using. This job does not update the device software inventory in the Device Manager server. To update the Device Manager server, you have to run an inventory collection job for this device.

In this section, we create a software removal job for all the OSGi devices that removes a specific bundle.

To create a software distribution job, perform the following steps:

1. In the Device Manager console, right-click Jobs and select Submit Job.

2. Select the following options in the Target Devices window:

– Device class: OSGi.

– Query: All OSGi Devices

– Owner group: select an option if you want.

– Select if the job is for enrolling or already enrolled users. This example is for currently enrolled devices.

– Click Next.

3. Select Software Removal as the job type. Enter adequate dates for activation and expiration fields, priority and a description for the package. Click Next. See Figure 11-14 on page 332.

Chapter 11. Device management 331

Page 348: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 11-14 Attributes

4. Click Add Step (Figure 11-15 on page 333), select Uninstall or Uninstall deep as Action. Then select the bundle to be removed (for this example, the OSGi bundle distributed in “Creating a software distribution job” on page 326). Click Next.

332 WCTME: Application Development and Case Study

Page 349: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 11-15 Software to be removed

5. Review the job summary. and click Ok.

6. You will be shown a job submission status. Click Close.

7. The job has been created successfully. To see the job, click the Jobs tab, select Return Anything and click OK. See Figure 11-16 on page 334.

Chapter 11. Device management 333

Page 350: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure 11-16 Job registered

11.3.3 Connecting the Device Manager server and WebSphere Studio Device Developer

The OSGi agent enables you to simulate an OSGi device connected to the Device Manager server. The OSGi agent and associated plug-in enables you to create software bundles, distribute the bundles using Device Manager, and perform other Device Manager jobs.

A GUI interface is provided to use the OSGi agent. The bundle containing the GUI is called OSGiAgentServlet and can be used to test the agent functionality from WebSphere Studio Device Developer. Use these steps as a guide to use this feature:

1. Start the Device Developer environment.

2. Start the Bundle Server and the Runtime server. Take note of the Runtime server HTTP port, 80 by default.

3. Install the following bundles from the Bundle server to the Runtime server:

– OSGiAgent provides the Device Manager agent.

– OSGiAgentServlet provides the GUI used to test the OSGi agent.

– OSGiAgentExt is used for supplying information about the device (device id, model, manufacture and resources.)

– OSGiAgentExtConfig must be implemented by customers that want to change the device class name.

334 WCTME: Application Development and Case Study

Page 351: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

4. Start the agent GUI by entering the following URL in a browser:

http://localhost:<runtime_port>/osgiagentservlet

For more information about features and startup options of the GUI, refer to the WebSphere Everyplace Access InfoCenter.

11.4 Device Manager sample scenarioIn the previous chapters of the book, we created a complete sample application for our ITSO Rentals company.

But when a new feature becomes available or a bug is fixed, how do you deploy the updated bundles?

This section adds a device management bundle to the sample application so that the client device can contact the device management server and let it and the local agent perform any necessary updates to the client.

11.4.1 Interim Fix 1 and IFix instructionsInstall these fixes using the instructions provided in the URLs above.

The rest of this chapter and some of the steps in Chapter 9, “Deploying a WCTME Application” on page 239 assume these fixes have been installed.

Important: For our example, we are using the Device Management server component of the WEA 5 server that has been our sample application host.

For connectivity between a WCTME 5.7.1 client and WEA 5 server, both a service side and client side update are required.

� Server side update: WEA Fix Pack 1 and Interim Fix 1 which includes PQ97443. See the following Web site:

http://www-1.ibm.com/support/docview.wss?rs=754&context=SSNM6Y&dc=DB550&uid=swg1PQ97443&loc=en_US&cs=utf-8&lang=en

� Client side update: See the following Web site:

http://www-1.ibm.com/support/docview.wss?rs=2016&context=SSQPWJ&uid=swg24009091

Chapter 11. Device management 335

Page 352: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

11.4.2 Device Manager scenario descriptionIn this section we follow the pattern we used for other bundles and create a new bundle for device management.

This bundle is not ITSO Rentals specific and contains only some configuration information and a call to the OSGi agent. The server side defines what jobs, if any, are performed by the agent.

Service InterfaceThis is the set of methods we want to implement with this bundle and expose as a service:

public void init(Properties properties);public String updateApplication();

Our sample application will call the agent with a screen button. Any jobs defined on the Device Management server will be run by the client side OSGi agent.

The properties that are passed to the bundle are used to configure the agent. This includes the destination address of the server and whether the service is operating in stand-alone mode.

The call to the agent starts a background process and returns immediately. Depending on the jobs defined on the server, some time might be required for the process to complete.

11.4.3 Device Manager bundle procedureFirst we need to create a Bundle Project to hold the device management classes.

1. If WebSphere Studio Site Developer is not running, click Start →Programs →IBM WebSphere Studio →Site Developer 5.1.x.

2. Open the SMF Perspective. Select Window →Open Perspective →SMF.

3. Make sure you are on the Package Explorer tab. Select File →New → Other.

4. Select Extension Services →Extension Services Bundle Project and click Next.

5. Enter the Project name ITSORentalsDeviceManagementServiceBundle and click Next.

6. In the Platform Profile field (Figure 11-17 on page 337), choose Extension Services: jclFoundation (5.7.0.).

336 WCTME: Application Development and Case Study

Page 353: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

7. Select the check box next to the application services SyncML/DM OSGi Agent. Click Next.

Figure 11-17 Selecting the OSGi Agent application service

8. Click Next.

9. Select the check box next to Create Default Bundle Activator. Click Finish.

10.If you see a panel indicating the folder has changed, click Yes.

Chapter 11. Device management 337

Page 354: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

11.From the Package Explorer tab of the SMF Perspective, select the ITSORentalsDeviceManagementServiceBundle Project you just created and right-click. From the pop-up menu select New →Package.

12.Enter the package name com.itso.devicemanagement and click Finish.

13.Select the package just created, right-click. From the pop-up menu select New → Interface.

14.Enter the name ITSORentalsDeviceManagementService and click Finish.

15.Into the ITSORentalsDeviceManagementService.java window that opens, copy the following:

public void init(Properties properties);public String updateApplication();

16.Save the file.

17.Select the package com.itso.devicemanagement, right-click. From the pop-up menu select New →Class.

18.Enter the name ITSORentalsDeviceManagementServiceImpl. Click the (Interfaces:) Add button, add the Interface ITSORentalsDeviceManagementService and click OK. then click Finish.

19.Replace the methods generated automatically with the code in Example 11-1.

Example 11-1 Device Manager bundle code

private boolean standAlone = true;

// Used to identify a set of settings for the OSGiAgent serviceprivate String accountName = "SampleAccount";private OSGiAgentService agentService;

/** * @param theAgentService */public ITSORentalsDeviceManagementServiceImpl (OSGiAgentService

theAgentService) {agentService = theAgentService;

}

/* (non-Javadoc) * @see

com.itso.rentals.device.ITSORentalsDeviceService#init(java.util.Properties) */

Tip: To help remove unresolved compiler errors, right click in the source and select Source →Organize Imports.

338 WCTME: Application Development and Case Study

Page 355: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

public void init(Properties properties) {

//allow properties to override defaultsif (properties != null) {

String standAloneString = properties.getProperty("itso.devicemanagement.standalone","true");

standAlone = standAloneString.equalsIgnoreCase("true");

Hashtable accountInfo = new Hashtable();// accountInfo.put("AccountID", accountName);

accountInfo.put(OSGiAgentConstants.keyAccountID, accountName);

// User name in the Device Manager Server // accountInfo.put("UserName", properties.getProperty("isync.user"));

accountInfo.put(OSGiAgentConstants.keyUserName, properties.getProperty("isync.user"));

// Password for the username// accountInfo.put("ClientPW", properties.getProperty("isync.password"));

accountInfo.put(OSGiAgentConstants.keyClientPW, properties.getProperty("isync.password"));

// The password is used when SyncML DM authorization is implemented. // I won't use this feature and it is ignored by the server

// accountInfo.put("ServerPW", properties.getProperty("itso.devicemanagement.keyServerPW"));

accountInfo.put(OSGiAgentConstants.keyServerPW, properties.getProperty("itso.devicemanagement.keyServerPW"));

/* This field is used for SSL communication between the OSGi device

and the DM Server. If SSL is not used, it is ignored.

The file name for the key ring file.Use a fully qualified path, including the file name. If the path

is not specified, the current working directory is used.A key ring file stores the public keys of colleagues and

associates in a single place for easy access and retrieval.

*/// accountInfo.put("KeyRing", properties.getProperty("itso.devicemanagement.keySSLKeyRing"));

accountInfo.put(OSGiAgentConstants.keySSLKeyRing, properties.getProperty("itso.devicemanagement.keySSLKeyRing"));

// This field is used for SSL communication between the OSGi device and the DM Server.

Chapter 11. Device management 339

Page 356: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

// If SSL is not used, it is ignored.// The password for the key ring

// accountInfo.put("KeyRingPassword", properties.getProperty("itso.devicemanagement.keySSLKeyRingPassword"));

accountInfo.put(OSGiAgentConstants.keySSLKeyRingPassword, properties.getProperty("itso.devicemanagement.keySSLKeyRingPassword"));

// Host name or IP address for the Device Manager server// accountInfo.put("Addr", properties.getProperty("itso.devicemanagement.keyAddr"));

accountInfo.put(OSGiAgentConstants.keyAddr, properties.getProperty("itso.devicemanagement.keyAddr"));

agentService.addAccount(accountName, accountInfo);// for our demo, turn off opollingString pollingString =

properties.getProperty("itso.devicemanagement.polling", "false");boolean polling = pollingString.equalsIgnoreCase("true");agentService.setPollingEnabled(polling);

}}

/* (non-Javadoc) * @see

com.itso.rentals.device.ITSORentalsDeviceService#updateApplication() */public String updateApplication() {

String results = "Configure server...!";

if (!standAlone) {

try {agentService.setDefaultAccountID(accountName);agentService.connectToManagementServer();results = "Update starting...";

} catch (BundleException e) {// TODO We should log this exception by using the LogTrackere.printStackTrace();results = "Update failed!";

}}

return results;}

20.Organize Imports and Save the file.

340 WCTME: Application Development and Case Study

Page 357: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

21.Open the ExtensionServicesBundleActivator.java file (in the default package) and add the following to the class:

private BundleContext context;private ServiceRegistration deviceService;

22.Add the interface Runnable to the class definition

23.Add the following code at the end of the start() method:

this.context = context;Thread t = new Thread(this);t.start();t.setName("Find OSGiAgentService Thread.");

24.Add the following code at the end of the stop() method:

deviceService.unregister();

This code unregisters the service when the bundle stops.

25.Add the following methods in Example 11-2 to the end of the class:

Example 11-2 Device manager class methods

private ServiceReference getServiceReference(BundleContext context) {

ServiceReference devServiceRef = context.getServiceReference(OSGiAgentService.class.getName());

return devServiceRef;}

/* (non-Javadoc) * @see java.lang.Runnable#run() */public void run() {

ServiceReference devServiceRef = getServiceReference(context);// make sure it resolveswhile (devServiceRef == null ) {

Note: The OSGiAgentConstants used in Example 11-1 beginning on page 338 are not exported in the 1.5.1 version of the agent, so the Strings references by the constants are included but commented out. In version 1.5.1.3, provided in the IFix (see 11.4.1, “Interim Fix 1 and IFix instructions” on page 335), the constants are accessible.

Chapter 11. Device management 341

Page 358: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

try {System.out.println("OSGiAgentService was not available yet!;

Trying again in 1 secs...");Thread.sleep(1000);

} catch (InterruptedException ie) {}devServiceRef = getServiceReference(context);

}

OSGiAgentService agentService = (OSGiAgentService) context.getService(devServiceRef);

deviceService = context.registerService(ITSORentalsDeviceManagementService.class.getName(),

new ITSORentalsDeviceManagementServiceImpl(agentService), null);

}

This code exposes the device management service to other bundles. Because the ServiceAgent reference will not be available immediately, we have created a thread that will look for this reference until it is available. It will be available when all the prerequisite bundles have been started. That should only take a second, if the bundles providing these services are available.

26.Save the file.

27.Opens the MANIFEST.MF editor. Scroll down to Export Services and select Add...

28.Select the service com.itso.devicemanagement.ITSORentalsDeviceManagementService and click OK.

29.Expand the section Export Packages and select Add...

30.Select the package com.itso.devicemanagement and click OK.

31.Save the file.

11.4.4 Update the sample application to use the new serviceFirst we need to update the projects build path and manifest file.

Tip: To help remove unresolved compiler errors, right-click in the source and select Source → Organize Imports.

342 WCTME: Application Development and Case Study

Page 359: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

1. Select the ITSORentalsWebApplicationBundle project, right-click and select Properties. Select Java Build Path.

2. From the Projects tab, select the check box next to ITSORentalsDeviceManagementServiceBundle. Click OK.

In Section 7.4.1, “Completing the sample application” on page 205, we included code to handle the Device Update button of the sample application. The code behind that button (in step number 14 on page 206) and references to the service created in this chapter were commented out.

3. Go back to the CheckInAndSync.java servlet and find the commented out code that points to the service we just created. Remove the comments.

For example, remove the line:

// private ITSORentalsDeviceManagementService dmService = null;

Uncomment this code and all the references to the dmService instance variable, to enable the code. Make sure to find all reference to dmService that are commented out to make that code active.

4. Organize Imports and save the updated servlet.

5. Open the MANIFEST.MF file. Scroll down to Import Packages.

6. Expand the section Import Package and select Add...

7. Select the package com.itso.devicemanagement and click OK.

8. Expand the section Import Services and select Add...

9. Select the service com.itso.devicemanagement.ITSORentalsDeviceManagementService and click OK.

10.Save the file.

11.4.5 Device manager bundle reviewWe created a new bundle that exposes a device management call for client updates. We updated the manifest file to export the new service.

Note: The package might already have been added automatically, or you can press the Compute button to fill in the list.

Note: The sample application’s login user ID and password are used to connect to the Device Management Server. Make sure that the user ID and password are valid on the server

Chapter 11. Device management 343

Page 360: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

We went back to the sample application servlet and updated its build path and manifest file to reference the new bundle and service. We then activated the commented out code in the sample application that references the new device management functionality.

The updated sample application can now be run.

11.4.6 Running the sample application with device management bundle

In order to test the new Device management bundle, perform the following steps:

1. If it is not running, start the SMF bundle server. For help see section 3.4, “Starting the SMF Bundle Server” on page 70.

2. Submit the ITSORentalsDeviceManagementServiceBundle to the bundle server. For help see section 3.8, “Submitting bundles to the SMF bundle server” on page 77.

3. Stop the SMF bundler server and SMF runtime, if they are running.

4. Navigate into the ITSORentalsWebApplicationBundle project and select the CheckInAndSync.java file, right-click and select Run on Server....

5. Because the OSGi agent classes are accessed dynamically, the OSGi agent bundles will not install automatically. Manually add the following bundles from the SMF bundle server to SMF runtime:

a. OSGiAgentExtb. OSGiAgentExtConfigc. OSGiAgentServlet (Optional)

6. Access the sample application as before and navigate to the config panel to set the Device Management server URL and disable Device Management stand-alone mode. Save the changes.

7. Select the Device Update button on the sample application’s main panel.

The OSGi agent will run in the background. the files OSGiAgentTree.bin and OSGIAgentTree.bin.bak are created on the device. These files maintain state for the OSGi agent and should only be deleted if the agent service needs to be reset.

11.4.7 Device TroubleshootingView the log on the device to see the outcome of the server defined jobs created and run on the client agent.

344 WCTME: Application Development and Case Study

Page 361: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Optionally, you can install the OSGi Agent servlet on the target device to be able to review the agent events and log. If installed it can be accessed with the URL http://localhost/osgiagentservlet.

11.5 Troubleshooting with Device ManagerThere could be situations where you might need to view the Device Management Server traces to check the status of the server and the jobs submitted. By default, the tracing is disabled. The trace log is primarily a development tool and should be enabled when troubleshooting. Enabling the trace log can affect your system performance. Extended use of trace logging can also consume large amounts of disk space. To manually enable tracing, do the following steps:

1. Go to the directory where WebSphere is installed and navigate to the subdirectory WebSphere\DMS16\dmserver\WEB-INF\classes. Locate the traceConfig.properties. You can change the trace level here. Near the bottom of the file are the trace flags for each of the Device Manager components. Set the appropriate flags on depending on the problem faced. For example if there is a problem with plug-ins you could set the traceEnabled.plugins to true. See Example 11-3.

Example 11-3 Flags for different components of Device Manager

#trace enabled for componentscomponent.console=falsecomponent.dmserver=falsecomponent.event=falsecomponent.notification=falsecomponent.plugins=falsecomponent.resultscollector=falsecomponent.twgapi=falsecomponent.database=falsecomponent.enrollserver=falsecomponent.datconverter=falsecomponent.mcollect=falsecomponent.notificationhandler=falsecomponent.api=false component.userservices=false

2. Save your changes.

3. Open a command window and navigate to the directory WebSphere\DMS\bin.

4. Run the command server -app dmserver -trace set. This will prompt the Device Manager to reread the trace settings and act on them.

5. Perform the device management tasks. To view the trace logs, navigate to WebSphere\AppServer\logs and open the file Stdout.log.

Chapter 11. Device management 345

Page 362: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

346 WCTME: Application Development and Case Study

Page 363: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Appendix A. Installing WCTME V5.7.1

The Workplace Client Technology, Micro Edition installation is really just a set of installations of different technologies. There are quite a few steps are involved in recreating a workshop machine environment. In this appendix, you will verify you have met the prerequisites, perform preinstallation tasks, and install all software needed to setup a workshop environment, including WebSphere Studio Device Developer Version 5.7.

A

© Copyright IBM Corp. 2005. All rights reserved. 347

Page 364: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

WCTME OverviewThe WCTME workshop development machine environment consists of an installation of WebSphere Studio Site Developer V5.1.2, WebSphere Studio Device Developer V5.7 as a plug-in to WebSphere Studio Site Developer, and the WebSphere Studio Device Developer plug-ins, such as SMF Bundle Development Kit, Extension Services, Application Tools for Extension Services, Web Services for MIDP, DB2e, and MQe.

The entire installation procedure should take between one to three hours. After that, you are ready to start developing WCTME applications for pervasive devices. The WebSphere Studio Device Developer component of IBM Workplace Client Technology, Micro Edition provides an integrated development environment that helps developers build, test, and deploy J2ME applications that run on server-managed clients and other pervasive devices.

For minimal configuration and customization you should follow the procedures below exactly, which will ease the installation process and allow the InstallShield to define default values. Refer to the WCTME Library for more information at the following HTTP address:

http://www-306.ibm.com/software/wireless/wctme_fam/

Installation prerequisitesThe WCTME development machine installations can be prone to failure if you don't meet the prerequisites. Also, in addition to the prerequisites listed below, for most up-to-date information about prerequisites visit:

http://www-306.ibm.com/software/wireless/wctme/sysreqs.html

Hardware prerequisitesThe following hardware is required;

� IBM-compatible PC: Intel® Pentium® III 500 MHz processor or equivalent (1.0 GHz recommended)

� Memory: 512 MB minimum (768 MB recommended)

� Hard drive: 1 GB free space

� CD-ROM drive

� Mouse or pointing device and keyboard

� 100 megabit Network Interface Card (NIC)

� Network Software: TCP/IP network software installed, configured, and running

348 WCTME: Application Development and Case Study

Page 365: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

� SVGA or better display resolution with at least 256 colors and 800 x 600 resolution

Software prerequisitesThe following operating systems are supported:

� Microsoft® Windows 2000, Windows XP,

� Red Hat Linux V8.0

� Windows Internet Explorer V5.5 with Service Pack 1, or later

Preinstallation proceduresBe certain you have the proper conditions in place before installing WCTME.

Verify ConfigurationVerify that your machine has all the applicable service packs (SP4 for Windows) and critical updates installed. You should also have some type of anti-virus software installed on your machine to help protect your machine from malicious code. Other useful programs to have installed include the following:

� Microsoft ActiveSync V3.7, which will allow syncing to a PocketPC device� WinZip� Adobe Acrobat Reader

Before beginning your installations, please check your network settings and verify that they are correctly configured for accessing the Internet. It will be required during installation of the plug-ins. If you need assistance with configuring your network, please contact your network administrator.

Machine installationsInstalling a complete development machine environment consists of the following four tasks:

1. WebSphere Studio Site Developer installation2. WebSphere Studio Device Developer installation3. WebSphere Studio Device Developer plug-in installation4. Verify installation

WebSphere Studio Site Developer installationFollow these steps to install WebSphere Studio Site Developer:

Appendix A. Installing WCTME V5.7.1 349

Page 366: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

1. Insert CD1 of WebSphere Studio Site Developer to run the Launch Pad. If the autorun does not start, you can manually start the Launch Pad by entering e:\launchpad.exe on a command line, where e:\ is the name of the drive where the CD resides). See Figure A-1.

2. Select Install IBM WebSphere Studio Site Developer. This will launch the InstallShield, which will guide you through the rest of the installation process.

Figure A-1 WebSphere Studio Site Developer installation

3. Wait for the InstallShield to completely load, then click Next on the Welcome panel.

4. Review the license agreement and select I accept the terms in the license agreement, and then click Next.

5. Accept the default installation directory of C:\Program Files\IBM\WebSphere Studio\Site Developer\v5.1.2 and click Next to continue.

6. In Figure A-2 on page 351, select the features for IBM WebSphere Studio Site Developer you would like to install and click Next. In most cases you will accept the defaults on this page. It is an Integrated Test Environment for WebSphere Application Server V5.1.

350 WCTME: Application Development and Case Study

Page 367: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure A-2 Product installation

7. Review the summary information and click Next to start the installation of WebSphere Studio Site Developer. The installation will take approximately 20 to 40 minutes. See Figure A-3.

Figure A-3 WebSphere Studio Site Developer installation in progress

8. Once the installation has completed successfully, click Finish.

Appendix A. Installing WCTME V5.7.1 351

Page 368: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

9. The Launch Pad will still be open, but is no longer needed. To close the Launch Pad, click the Exit button. You are now ready to install WebSphere Studio Device Developer as a plug-in to WebSphere Studio Site Developer, providing a rich development environment.

WebSphere Studio Device Developer installationNote: Be sure to select Yes when asked if you would like to add WebSphere Studio Device Developer V5.7 as a plug-in to WebSphere Studio Site Developer V5.1.2

1. Insert CD1 of WebSphere Studio Device Developer to run the Launch Pad. If the autorun does not start, you can manually start the Launch Pad by entering e:\launchpad.exe on a command line, where e:\ is the name of the drive where the CD resides.

2. Select Install IBM WebSphere Studio Device Developer. This will launch the InstallShield, which will guide you through the rest of the installation process.

3. Wait for the InstallShield to completely load, then click Next on the Welcome panel.

4. Review the license agreement (Figure A-4) and select I accept the terms in the license agreement, and then click Next.

Figure A-4 WebSphere Studio Device Developer installation

352 WCTME: Application Development and Case Study

Page 369: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

5. Accept the default installation directory of C:\Program Files\IBM\Device Developer\ and click Next to continue.

6. This is a very important step. WebSphere Studio Device Developer found a version of WebSphere Studio Site Developer installed on the system and has the ability to enable WebSphere Studio Device Developer’s functionality within WebSphere Studio Site Developer. Select Yes, enable it and click Next to continue. See Figure A-5.

Figure A-5 Enable WebSphere Studio Device Developer within Site Developer

7. Review the summary information and click Next to start the installation of WebSphere Studio Device Developer. The installation will take approximately 10 to 20 minutes. See Figure A-6 on page 354.

Appendix A. Installing WCTME V5.7.1 353

Page 370: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure A-6 WebSphere Studio Device Developer installation in progress

8. Once the installation has completed successfully, click Finish.

9. The Launch Pad will still be open, but is no longer needed. Click the Exit button to close the Launch Pad. You are now ready to install WebSphere Studio Device Developer plug-ins, which will provide the ability to develop SMF, ESWE, and Web Services applications.

WebSphere Studio Device Developer plug-in installationThe WebSphere Studio Device Developer component of Workplace Client Technology, Micro Edition V5.7 adds new productivity features to assist developers:

� Micro Environment Toolkit for WebSphere Studio can help development teams create Extension Services for Relational Data (DB2e), Messaging/Transactions (MQe), Web Services Simple Object Access Protocol (SOAP)

� An enhanced Services Management Framework (SMF) development toolkit facilitates the creation of server-managed applications deployed to the Services Management Framework, IBM's implementation of the OSGi Services Platform

� Enhanced integration for testing and deploying applications to PDAs

354 WCTME: Application Development and Case Study

Page 371: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Execute the following steps:

1. Open WebSphere Studio Site Developer. The first time you open WebSphere Studio Site Developer, it will ask you where you would like to have your workspace stored. Accept the default directory and select Use this workspace as the default and do not show this dialog box again and click OK.

2. Open the Update Manager perspective by clicking Help →Software Updates → Update Manager.

3. In the Feature Updates view, expand Sites to Visit.

4. Expand IBM Micro Environment Toolkit for WebSphere Studio.

5. Expand Extension Services for WebSphere Everyplace.

6. Click SMF Bundle Development Kit V5.7.0 (Figure A-7). Notice that a Preview window of the plug-in is shown on the right.

Figure A-7 SMF bundle development kit

7. Scroll to the bottom of the preview for SMF, and put a check by Install by adding to the Selected Updates under Group Updates. See Figure A-8 on page 356. You will be installing all of the plug-ins in a group, so that all dependencies are resolved automatically by WebSphere Studio Site Developer.

Appendix A. Installing WCTME V5.7.1 355

Page 372: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure A-8 Group updates

8. In the Features Update view, select Extension Services V5.7.0. Add this plug-in to the Selected Updates as you did on previous step.

9. In the Features Update view, select Extension Services Samples V5.7.0. Add this plug-in to the Selected Updates as you did on previous step.

10.In the Features Update view, select Application Tools for Extension Services V5.7.0. Add this plug-in to the Selected Updates as you did on previous step.

11.In the Features Update view, expand MIDP Extensions and select Web Services for MIDP V5.7.0. Add this plug-in to the Selected Updates as you did on previous step.

12.In the Features Update view, expand IBM WebSphere Everyplace Device Developer Technologies, expand Technologies, and select DB2e 8.1.4. Add this plug-in to the Selected Updates as you did on previous step.

13.In the Features Update view, select MQe 2.0.1. Add this plug-in to the Selected Updates as you did on previous step.

14.From the Install Configuration view, select the Selected Updates tab.

15.Right-click anywhere in the window and select Process All. See Figure A-9.

Figure A-9 Selecting Process All

16.The Update Tasks window will appear and show you a summary of all the plug-ins you are about to install. Review the information to make sure you have all the plug-ins selected, and click Next to continue.

356 WCTME: Application Development and Case Study

Page 373: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

17.Select I accept the terms in the license agreements and click Next to continue. See Figure A-10.

Figure A-10 Feature license

18.Click Finish to start the installation of the plug-ins.

19.You will be presented with a Jar Verification window for each plug-in (Figure A-11 on page 358), asking if you would like to install the plug-in even though it has not been digitally signed. Click Install on each of these windows.

Appendix A. Installing WCTME V5.7.1 357

Page 374: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure A-11 Feature verification

20.Once all of the plug-ins have been installed, WebSphere Studio Site Developer will require the workbench to be restarted for the changes to take effect. Click Yes to restart the WebSphere Studio Site Developer workbench.

Verify installationAfter the installation completes and you have rebooted the WebSphere Studio Workbench, you will want to verify that the installation procedures have been successfully completed. See Figure A-12 on page 359. This can be accomplished multiple ways:

� Review the Update Manager to make sure all updates have been applied. If you click an update that has already been applied, the install options will not be available.

� Check to see if the Devices menu has been added to the menu bar. This lets you know that the WebSphere Studio Device Developer plug-in has been successful, and will show up when you open a Java Perspective.

� You can also check the Launch Configuration window (Run →Run... from the menu. See Figure 3-17 on page 71 to see if Java on Device and MIDlet Suite are available, because these are WebSphere Studio Device Developer tools.

358 WCTME: Application Development and Case Study

Page 375: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

� Lastly, you can open the New Project Wizard (File →New → Other from the menu. See Figure 3-3 on page 52, and verify that J2ME projects, Extension Services projects, and SMF projects are listed.

Figure A-12 WebSphere Studio Device Developer successful install

Reviewing the installationYou have completed a successful installation of a workshop machine, which includes WebSphere Studio Device Developer V5.7. In this appendix, you have seen the many steps required to install a base WebSphere Studio Device Developer system. For further information about WebSphere Studio Device Developer, visit the WebSphere Studio Device Developer website at:

http://www-306.ibm.com/software/wireless/wsdd/

Appendix A. Installing WCTME V5.7.1 359

Page 376: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

360 WCTME: Application Development and Case Study

Page 377: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Appendix B. Using MIDlet applications to access Web Services

MIDlets are applications written to run on the MIDP (Mobile Information Device Profile) and the CLDC (Connected Limited Device Configuration), which is one of the device configurations of the J2ME specification. Because MIDP is designed for low-end devices, MIDlet applications can provide only limited functionality. Web Services are a good way to allow smaller devices and applications to use the processing power available on larger machines. The sections in this appendix describe how to create a MIDlet application to access a Web Service.

While in the grand scheme of our ITSO Car Rental scenario MIDP does not play a significant role, it is possible that you will want to incorporate application access from lower-end devices. To that end, we have provided this appendix to demonstrate how to use a MIDlet to access Web Services. It does not really fit in the case study described throughout the text, but is here as a guide to show you how to access Web Services from your MIDP applications.

Note: Please install the Delayed Flights Web Services EAR application (DelayedFlightsWSEAR.ear) before running the following steps to create the MIDlet application to access the Web Service.

B

© Copyright IBM Corp. 2005. All rights reserved. 361

Page 378: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Create the Web Services MIDletTo create the MIDlet, perform the following tasks:

1. Create a new project in the workbench. You will create a MIDlet Suite Project. Select File →New →Project →J2ME →MIDlet Suite. See Figure B-1.

Figure B-1 Create a MIDlet Suite project

2. On the next screen, Figure B-2 on page 363, give your project a name. We suggest AirlineStatus-WSMIDlet.

362 WCTME: Application Development and Case Study

Page 379: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure B-2 MIDlet Suite creation

3. On the Next panel, choose the IBM J9 VM configuration (for example ive-2.2) from the list of configured J9 VMs.

4. Press Finish.

5. Open the project. From the src directory, right-click and choose File → New →Other →Mobile Web Services Client →Mobile Web Services Client for MIDP. See Figure B-3 on page 364.

Appendix B. Using MIDlet applications to access Web Services 363

Page 380: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure B-3 Mobile Web Services Client for MIDP

6. On the next panel, Figure B-4 on page 365, verify that the source folder is correct. Add a package if desired. The WSDL location is the same as specified above. Make sure the Generate MIDlet option is checked.

364 WCTME: Application Development and Case Study

Page 381: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure B-4 Web Service client stub generator

7. Press Finish. Your MIDlet is generated. It is not optimized. The toolkit simply generates a user interface based on the methods and inputs defined in the WSDL. The next section shows you how to edit the MIDlet application and make it a more production-level solution.

Edit the Web Services MIDletTo edit the Web Services MIDlet, perform the following steps:

Appendix B. Using MIDlet applications to access Web Services 365

Page 382: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

1. Open the project MIDlet JAD file (AirlineStatus-MIDletSuite.jad) located under the project root directory using the MIDP JAD File Editor.

2. In the MIDlets in this Suite section, select AirlineStatus-WSMIDlet and press the Edit button. Select the your generated MIDlet Soap class (com.itso.ws.midp.DelayedFlightsSoap_Midlet). See Figure B-5.

Figure B-5 Edit MIDlet entry

3. Save and close the JAD file.

366 WCTME: Application Development and Case Study

Page 383: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

4. Open the DelayedFlightsSoap_Midlet.java class file using the Java Editor and replace the generated MIDlet code with the source code in Example B-1:

Example: B-1 MIDlet code

/** * com.itso.ws.midp.DelayedFlightsSoap_Midlet.java * Sample Midlet v.1.0 * * Generated on 12/20/04 9:15 PM * Based on WSDL at http://localhost:9080/DelayedFlightsWS/services/DelayedFlights/wsdl/DelayedFlights.wsdl */

package com.itso.ws.midp;

public class DelayedFlightsSoap_Midlet extends javax.microedition.midlet.MIDlet implements javax.microedition.lcdui.CommandListener { javax.microedition.lcdui.Form mainForm = new javax.microedition.lcdui.Form("AirlineStatus WebServices MIDlet"); javax.microedition.lcdui.TextField getDelayedFlightsFlightNoArrayField = new javax.microedition.lcdui.TextField("Enter Airline Flight Number:", "", 6, javax.microedition.lcdui.TextField.ANY); javax.microedition.lcdui.Command getDelayedFlightsCommand = new javax.microedition.lcdui.Command("Get Flight Status", javax.microedition.lcdui.Command.SCREEN, 1); javax.microedition.lcdui.StringItem resultField = new javax.microedition.lcdui.StringItem("", ""); com.itso.ws.midp.DelayedFlightsSoap_Stub stub = new com.itso.ws.midp.DelayedFlightsSoap_Stub();

public DelayedFlightsSoap_Midlet() { mainForm.append(getDelayedFlightsFlightNoArrayField); mainForm.addCommand(getDelayedFlightsCommand); mainForm.append(resultField);// stub.resultField = this.resultField; mainForm.setCommandListener(this); }

public void startApp() { javax.microedition.lcdui.Display.getDisplay(this).setCurrent(mainForm); }

public void pauseApp() { }

public void destroyApp(boolean unconditional) { }

Appendix B. Using MIDlet applications to access Web Services 367

Page 384: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

public void commandAction(javax.microedition.lcdui.Command c, javax.microedition.lcdui.Displayable d) { try { System.out.println("Processing command action"); if (c == getDelayedFlightsCommand) { resultField.setLabel("Flight Status = "); resultField.setText("working..."); java.lang.String[] parm0 = new java.lang.String[] {getDelayedFlightsFlightNoArrayField.getString()}; java.lang.String[] result = stub.getDelayedFlights( parm0 );

String resultString = processFlightStatus(result[0]);resultField.setLabel("Flight " + parm0[0] + " is ");resultField.setFont(javax.microedition.lcdui.Font.getFont(

javax.microedition.lcdui.Font.FACE_MONOSPACE,javax.microedition.lcdui.Font.STYLE_BOLD,javax.microedition.lcdui.Font.SIZE_LARGE));

resultField.setText(resultString); } } catch (Exception e) { e.printStackTrace(); resultField.setLabel("Error:"); resultField.setText(e.toString()); } }

private String processFlightStatus(String status) {

if (status.compareTo("O")==0) {status = "On Time";} else if (status.compareTo("D")==0) {status = "Delayed";} else if (status.compareTo("C")==0) {status = "Cancelled";}

return status;

}

}

5. The current MIDlet implementation refers to the WSDL file (DelayedFlights.wsdl) on the user’s local host. Open the DelayedFlightsSoap_Stub.java class file and change the javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY property value to the live Web Service URL on the host system.

Launch and test the Web Services MIDletTo launch the Web Services MIDlet application, perform the following steps.

368 WCTME: Application Development and Case Study

Page 385: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

1. Create a new run configuration by clicking Run → Run… from the WebSphere Studio Device Developer main workbench menu. When the run configuration dialog appears, create a new MIDlet Suite run configuration. Select the project and local MIDP emulator as your device to launch the MIDlet as shown in Figure B-6.

Figure B-6 Running the Web Service MIDlet application

2. Click the Add… button to invoke the build configuration dialog to create a new MIDP build. See Figure B-7 on page 370.

Appendix B. Using MIDlet applications to access Web Services 369

Page 386: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure B-7 Create a new MIDP build

3. Click the Add button and create the Generic JAR build type which will run on any platform and click Next. See Figure B-8 on page 371.

370 WCTME: Application Development and Case Study

Page 387: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure B-8 Build list

4. On the next panel, Figure B-9 on page 372, uncheck Remove Unused classes. This option will remove dynamically called classes using the SmartLinker, which can cause issues with MIDlets. Classes that are dynamically loaded might be removed as unused by the SmartLinker. Make sure the JAD file name is correct.

Appendix B. Using MIDlet applications to access Web Services 371

Page 388: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure B-9 General build settings

5. On the next panel, Figure B-10 on page 373, add the WebServicesMIDP.jar to your JAR file. This guarantees that the proper functions will be available because a device can have a JVM or JRE installed without having Web Services support. If your device platform already has a JVM installed with Web Services support, then you do not have to add the WebServicesMIDP.jar to the build. For the purposes of this exercise, you should play it safe and add the Web Services JAR just to make sure things run as easily as possible. You are not really concerned about the size and performance in this environment.

6. Press Finish, and then close the build panel. You return to the run configuration dialog.

7. Ensure that your newly created build is selected in the MIDlet Suite drop down list. Give your MIDlet Suite configuration a new name, accept the rest of the defaults and Apply your changes. Click Run to launch your MIDlet on the local MIDP emulator.

372 WCTME: Application Development and Case Study

Page 389: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

8. Your MIDlet should appear Figure B-10. It will have an input field to Enter Airline Flight Number for which you are requesting status update from the web service as defined in the WSDL file for the web service. Enter a sample flight number as show below and press the Get Flight Status button to contact the Web Service and receive an answer.

Figure B-10 Requesting a flight status

9. Whenever you first attempt to access the network, you will be asked if the MIDlet can use airtime. This is because the MIDlet security model has very stringent restrictions on what MIDlets can do by default. Press OK to allow it to proceed. Your answer should appear as show in Figure B-11 on page 374.

Appendix B. Using MIDlet applications to access Web Services 373

Page 390: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure B-11 Flight status received from Web Service

You have now created a MIDlet application to access a Web Service to obtain flight status information. Additional source code modifications can be made to improve the presentation of data on the MIDlet application.

As you can see, accessing Web Services from a MIDlet is not a complex task, and can add a large degree of accessibility to your applications. In this example, you saw how an existing Web Service, the airline flight status service, can be used for a completely different purpose: determining when renters would be arriving for ITSO Rentals. Services set up for one purpose can have other uses.

In different designs, you might also envision a service that provides the slot numbers for cars, given a renter name or frequent renter number, and the MIDlet access for such a service could be made available to the renters. Once renters arrive at an airport for example, they could access such a service to find out where their car is without having to look at a scrolling list.

The possibilities are limitless. While MIDP is not the cornerstone of the mobile Java space, it is a very lightweight access method into enterprise functions, and certainly has a place in the overall solution architecture.

374 WCTME: Application Development and Case Study

Page 391: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Appendix C. Sample server-side Web Service

This appendix shows the steps required to develop and deploy a Web Service based in a Web project and using WebSphere Studio Site Developer. To explain the tasks involved developing and deploying Web services, we will create a Web service that manages flight information as part of the ITSO Rentals sample scenario.

You will perform the following tasks:

1. Create a Web project that contains a class file to manage flight information.

2. Transform this Web project into a Web service using the available wizards in WebSphere Studio Site Developer.

3. Deploy the Web Service in WebSphere Application Server.

Note: The sample server-side Web Service shown in this appendix is used in conjunction with the sample scenario described in this redbook.

C

© Copyright IBM Corp. 2005. All rights reserved. 375

Page 392: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Create a Web projectWe will create a Web project named DelayedFlightsWS that contains a class to manage flight delay information. The project will be created using the Dynamic Web Project wizard. You will import a Java file that generates a list of flights status based in a list of flights.

1. If it is not already running, start the IBM WebSphere Studio Site Developer. Click Start →Programs →IBM WebSphere Studio →Site Developer 5.1.x.

2. Select File →New →Other, as in Figure C-1.

Figure C-1 New project creation

3. Select Web →Dynamic Web Project and click Next. See Figure C-2 on page 377.

376 WCTME: Application Development and Case Study

Page 393: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-2 Selection of Dynamic Web Project

4. As in Figure C-3 on page 378, enter DelayedFlightsWS for the Project name, select Configure advanced options and click Next.

Appendix C. Sample server-side Web Service 377

Page 394: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-3 New Dynamic Web project wizard

5. Click New (Figure C-4) for the EAR project and enter DelayedFlightsWSEAR (formerly DefaultEAR) in the New project name field. Click Finish.

Figure C-4 J2EE Settings Page

The DelayedFlightsWS project has been created. Now we will import a Java file that contains logic to manage flight status.

1. A Java file named DelayedFlights.java is provided for this sample scenario; follow these steps to import this Java file:

378 WCTME: Application Development and Case Study

Page 395: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

a. Select File →Import, select File system and click Next. See Figure C-5.

Figure C-5 Importing a file

b. In the Import File system window Figure C-6 on page 380, enter the following information:

i. From Directory: browse the directory where the file DelayedFlights.java is located and select it.

Note: You can download the sample code available as additional materials. See Appendix D, “Additional materials and how to obtain them” on page 403.

ii. Into folder: enter the following: DelayedFLightsWS/JavaSource/com/itso/flightInfo.

iii. Select Create selected folders only option.

iv. Click Finish.

Appendix C. Sample server-side Web Service 379

Page 396: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-6 Importing the provided Java file

2. If a package error appears, include the following instruction at the beginning of the Primes.java file, located in the /JavaSource/com/itso/flightInfo/ folder:

package com.itso.flightInfo;

Reviewing the imported Java class fileTo view the source code of DelayedFlights.java file, double-click the file name located in the /JavaSource/com/itso/flightInfo/ folder. The only available method in this file is getDelayedFlights() (Example C-1 on page 381). This method receives a list of flight numbers and returns a list containing each flight’s status. Each flight status is randomly generated and can take the following values:

380 WCTME: Application Development and Case Study

Page 397: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

� O means On time.� C means Cancelled.� D means Delayed.

Example: C-1 DelayedFlights.java: getDelayedFlights() method

package com.itso.flightInfo;

import java.lang.reflect.Array;import java.util.Random;

public class DelayedFlights {public String[] getDelayedFlights(String[] flightNoArray){

String[] statusArray = new String [flightNoArray.length];String flightNo;if (flightNoArray != null) {

String[] status = {"C","D","O","O","O"};Random generator = new Random();for (int i=0; i<flightNoArray.length; i++) {

flightNo = (String)Array.get(flightNoArray,i);Array.set(statusArray,i,status[generator.nextInt(5)]);

}}return statusArray;

}}

Create a Web serviceIn this section, you will create a Web service in the DelayedFlightsWS project using the wizards provided by WebSphere Studio Site Developer. Once created, you will test the Web service in a WebSphere Test Environment.

1. Select File →New →Other, as in Figure C-7 on page 382.

Appendix C. Sample server-side Web Service 381

Page 398: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-7 Starting creation of Portlet project

2. Select Web Services →Web Service and click Next. See Figure C-8 on page 383.

382 WCTME: Application Development and Case Study

Page 399: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-8 Selection of Web Service

3. Enter the following information in the Web Services window (Figure C-9 on page 384):

a. Web Service type: Java bean Web Service.b. Check the box Start Web service in Web project.c. Check the box Overwrite files without warning.d. Check the box Create folders when necessary.e. Optionally, you can select to generate a client proxy and configure its

options.

Click Next.

Appendix C. Sample server-side Web Service 383

Page 400: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-9 Web Service wizard

4. Click Edit in Server-Side Deployment Selection section (Figure C-10 on page 385) and select the following:

– Server: Server Types →WebSphere version 5.1 →WebSphere v5.1 Test Environment

– Web service runtime: IBM WebSphere V5.

Click Ok.

384 WCTME: Application Development and Case Study

Page 401: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-10 Service Deployment configuration

5. Click Next. See Figure C-11 on page 386.

Appendix C. Sample server-side Web Service 385

Page 402: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-11 Service Deployment configuration

6. In the Web Service Java Bean Selection window (Figure C-12), type com.itso.flightInfo.DelayedFlights as the Bean value. Click Next.

Figure C-12 Web Service Java Bean selection

7. In the Web Service Java Bean Identity window (Figure C-13 on page 387_:

a. Select the getDelayedFlights(java.lang.String []) method.

386 WCTME: Application Development and Case Study

Page 403: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

b. Leave the other options as default and click Next.

Figure C-13 Web Service Java Bean identity

8. In the Web Server Publication window (Figure C-14 on page 388), accept the defaults and click Finish to publish the Web Service. This process will take several minutes.

Appendix C. Sample server-side Web Service 387

Page 404: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-14 Web Service publication

At this time, the Web service is running on the WebSphere v5.1 Test Environment. If you want to test it, you can use the Web Services Explorer utility provided by WebSphere Studio Site Developer.

To use the Web Services Explorer utility follow these steps:

1. In the DelayedFlightsWS project, right-click on DelayedFlights.wsdl file and select Web Services →Test with Web Services Explorer.

Figure C-15 Selecting Web Services Explorer

2. In the Web Services Explorer window (Figure C-16 on page 389), click in the getDelayedFlights operation.

388 WCTME: Application Development and Case Study

Page 405: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-16 Selecting an operation

3. Enter a flight number value (Figure C-17 on page 390) in each line of the Values table. Click Add link to include new rows. Add all the flight numbers you want, then select the combo box at the left side of each value and click Go.

Appendix C. Sample server-side Web Service 389

Page 406: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-17 Invoking an operation

4. The flight status returned by the Web service appear in the Status frame, Figure C-18.

Figure C-18 Invoking an operation

390 WCTME: Application Development and Case Study

Page 407: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Deploy a Web service in WebSphere Application ServerIn this section you will deploy the DelayedFlightsWS Web services in a WebSphere Application Server v5.

1. Export the DelayedFlightsWSEAR project as an EAR file:

a. In WebSphere Studio Site Developer, click File →Export, select EAR file and click Next.

b. In the EAR Export window (Figure C-19):

• Chose DelayedFlightsWSEAR as Enterprise Application project name.

• Select the directory destination to which you want to export the EAR file.

• If you want, select Export source files and Overwrite existing files without warning options.

• Click Finish.

Figure C-19 EAR Export

2. Open the WebSphere Application Server Administrative Console. Select Start →Programs →IBM WebSphere →Application Server v5.0 →Administrative Console.

3. Login in the Administrative Console with an administrator user ID.

4. In the console navigation tree (Figure C-20 on page 392), select Applications →Install New Application. Specify the path name of the DelayedFlightsWSEAR.ear file and click Next.

Appendix C. Sample server-side Web Service 391

Page 408: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-20 Preparing for the application installation

5. Accept the defaults values and click Next. See Figure C-21 on page 393.

392 WCTME: Application Development and Case Study

Page 409: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-21 Preparing for the application installation

6. Now, the four steps of the Install New Application pages will be shown. Review and accept the defaults values showed in steps 1, 2 and 3. Click Step 4: Summary. See Figure C-22 on page 394.

Appendix C. Sample server-side Web Service 393

Page 410: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-22 Install New Application

7. Review the summary (Figure C-23 on page 395) and click Finish. If you want to change an option click Previous.

394 WCTME: Application Development and Case Study

Page 411: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-23 Install New Application summary

8. The installation can take several minutes. When you are finished, click Save to Master Configuration link, as in Figure C-24 on page 396.

Appendix C. Sample server-side Web Service 395

Page 412: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-24 End of the application installation

9. Click Save to update the master configuration with the changes. See Figure C-25 on page 397.

396 WCTME: Application Development and Case Study

Page 413: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-25 Updating the master repository

10.Now you need to update the Web server plug-in configuration. Select Environment →Update Web Server Plugin. Click OK to update the plugin configuration file and then restart the HTTP server. See Figure C-26 on page 398.

Appendix C. Sample server-side Web Service 397

Page 414: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-26 Updating Web server plugin configuration

11.Be sure the DelayedFlightsWSEAR enterprise application is started. If not, in the console navigation tree, select Applications →Enterprise Application, select DelayedFlightsWSEAR and click Start. See Figure C-27 on page 399.

398 WCTME: Application Development and Case Study

Page 415: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-27 Starting an application

At this time, the Web service is running on WebSphere Application Server v5. You can test if it is working properly using the Web Services Explorer utility provided by WebSphere Studio Site Developer:

1. Open the Web Services Explorer utility as you seen in step 1 on page 388

2. In the Web Services Explorer window:

a. Click Add in the Endpoints section. A new row will be added in the Endpoints table.

b. In this new row, type the complete URL to access the Web service located in the WAS server, for example:

http://wea5.itso.ral.ibm.com/DelayedFlightsWS/services/DelayedFlights

Appendix C. Sample server-side Web Service 399

Page 416: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

c. Click Go. A successful update endpoint message will appear in the Status frame. See Figure C-28.

Figure C-28 Adding a new endpoint

3. Click the getDelayedFlights operation. See Figure C-29 on page 401.

400 WCTME: Application Development and Case Study

Page 417: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-29 Selecting an operation

4. In the Invoke a WSDL Operation section:

– Select the just added endpoint.

– Enter a flight number value in each line of the Values table. Click Add link to include new rows. Add all the flight numbers you want.

– Select the box to the left side of each flight number value.

– Click Go. See Figure C-30 on page 402.

Appendix C. Sample server-side Web Service 401

Page 418: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure C-30 Invoking an operation

5. The flight status returned by the Web service will appear in the Status frame, as in Figure C-31.

Figure C-31 Invoking an operation

402 WCTME: Application Development and Case Study

Page 419: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Appendix D. Additional materials and how to obtain them

This redbook refers to additional material that can be downloaded from the Internet. This appendix describes those materials and how to download them.

D

© Copyright IBM Corp. 2005. All rights reserved. 403

Page 420: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Locating the Web materialThe Web material associated with this redbook is available in softcopy on the Internet from the IBM Redbooks Web server. Point your Web browser to:

ftp://www.redbooks.ibm.com/redbooks/SG246496

Alternatively, you can go to the IBM Redbooks Web site at:

ibm.com/redbooks

Select the Additional materials and open the directory that corresponds with the redbook form number, SG246496.

Using the Web materialThe additional Web material that accompanies this redbook includes the following files:

File name Descriptionsg246496.zip Zipped Code Samples

System requirements for downloading the Web materialThe following system configuration is recommended:

Hard disk space: 10 MB minimumOperating System: WindowsProcessor: 2 GHz or higherMemory: 1GB

How to use the Web materialCreate a subdirectory (folder) on your workstation, and unzip the contents of the Web material zip file into this folder.

Web material overviewThe additional materials zip file contains the files and directories shown in Table D-1 on page 405.

404 WCTME: Application Development and Case Study

Page 421: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Table D-1 Additional materials

Description

Logo.gif The logo for the ITSO Rentals sample application.

demo-images/Image1.jpgdemo-images/Image2.jpgdemo-images/Image3.jpgdemo-images/Image4.jpgdemo-images/Image5.jpgdemo-images/Image6.jpg

These are example photos for the sample application. Photos must be less than 10,000 bytes and should look good when presented at 75 x 75 (square) pixels.These can be loaded into the local DB2e database from the client system and used for stand-alone demos of the sample application.This is needed when running completed application in WebSphere Studio Site Developer (C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\demo-images) or off the default directory when running on a platform.

workspace/* Completed project bundles that can be imported into a WebSphere Studio Site Developer workspace

MQeServer/startMQeServer.batMQeServer/ITSOMQeServer.jar

Completed MQe Server implementation for running on a server and the source is included.

ITSORentalsPCPlatformBuild/platform.zip

A completed build appropriate for running on a (Windows) PC

ITSORentalsPPCPlatformBuild/platform.zip

A completed build appropriate for running on a PocketPC 2003

Database scripts/* The files necessary to create the database tables on the server, insert sample data and inserting the sample photos into the customer table

midletcode/WCTMERedbook_MIDletApp.zip

A sample midlet to access our Web Services server.

WebServices/* The Web Services server implementation.

Appendix D. Additional materials and how to obtain them 405

Page 422: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Procedure for using the Web materialThe Extension Services Bundle Projects created in the chapters of this book are included in the zip file. This section describes the steps necessary to import those projects into WebSphere Studio.

1. Download the zip file from the Additional Materials Web site and extract the workspace directory. The following projects are included:

– FlightInfoWebServiceBundle– FlightInfoWebServiceClientBundle– ITSOCheckInAndSyncWebProject– ITSOCustomerBundle– ITSORentalsDatabaseServiceBundle– ITSORentalsDeviceManagementServiceBundle– ITSORentalsMQeServiceBundle– ITSORentalsPC– ITSORentalsTesterBundle– ITSORentalsWebApplicationBundle

2. Copy them into your Studio workspace directory.

3. Start Studio and open the SMF Perspective. See Figure D-1.

Figure D-1 Starting with an empty workspace

4. Right-click in the Package Explorer view and select Import.... See Figure D-2 on page 407.

406 WCTME: Application Development and Case Study

Page 423: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure D-2 Importing the first project

5. As in Figure D-3, select Existing Project into Workspace, then Next.

Figure D-3 Import Existing...

6. Click Browse...

Appendix D. Additional materials and how to obtain them 407

Page 424: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure D-4 Browse to the workspace directory

7. As in Figure D-4, navigate to the workspace where you have already copied the project directories. Select the first project directory to import. See Figure D-5.

Figure D-5 Importing a existing project into the workspace

8. Click OK, then Finish.

9. Repeat this process until all projects have been imported.

When you have imported all the projects the workspace should look like Figure D-6 on page 409.

Note: It does not matter in what order you import the projects.

408 WCTME: Application Development and Case Study

Page 425: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Figure D-6 All projects imported into the workspace

10.If there are any errors in the workspace, it might be necessary to rebuild the projects. Select Project →Rebuild All. See Figure D-7.

Figure D-7 Rebuild all the projects

Appendix D. Additional materials and how to obtain them 409

Page 426: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Note: There is one broken link in the CheckIn.jsp file in the ITSOCheckInAndSyncWebProject. This is expected.

410 WCTME: Application Development and Case Study

Page 427: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Related publications

The publications listed in this section are considered particularly suitable for a more detailed discussion of the topics covered in this redbook.

IBM RedbooksFor information on ordering these publications, see “How to get IBM Redbooks” on page 412. Note that some of the documents referenced here may be available in softcopy only.

� Using WebSphere Studio Device Developer to Build Embedded Java Applications, SG24-7082

� IBM Replication Solutions for Pervasive Computing with DB2 Everyplace and DB2 Satellite Edition, SG24-6217

Other publicationsThese publications are also relevant as further information sources:

� IBM WebSphere Everyplace Access V5 Handbook for Developers and Administrators Volume I: Installation and Administration, SG24-6462

� IBM WebSphere Everyplace Access V5 Handbook for Developers and Administrators Volume II: Application Development, SG24-6463

� IBM WebSphere Everyplace Access V5 Handbook for Developers and Administrators Volume III: E-Mail and Database Synchronization, SG24-6676

� IBM WebSphere Everyplace Access V5 Handbook for Developers and Administrators Volume IV: Advanced Topics, SG24-6677

Online resourcesThese Web sites and URLs are also relevant as further information sources:

� IBM Pervasive Computing

http://www.ibm.com/pvc

� IBM Workplace Client Technology, Micro Edition

http://www.ibm.com/software/wireless/wctme_fam/

© Copyright IBM Corp. 2005. All rights reserved. 411

Page 428: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

� IBM Service Management Framework (SMF)

http://www.ibm.com/software/wireless/smf

� IBM WebSphere Studio Device Developer

http://www.ibm.com/software/wireless/wsdd

� IBM WebSphere Studio Plug-in Central

http://www.ibm.com/software/wsdd/downloads/plugin

� Eclipse

http://www.eclipse.org

How to get IBM RedbooksYou can search for, view, or download Redbooks, Redpapers, Hints and Tips, draft publications and Additional materials, as well as order hardcopy Redbooks or CD-ROMs, at this Web site:

ibm.com/redbooks

Help from IBMIBM Support and downloads

ibm.com/support

IBM Global Services

ibm.com/services

412 WCTME: Application Development and Case Study

Page 429: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Index

Aapplication code 4application deployment 3application management 6application model 2application platform 10ARM 240AWT 7, 23

Bback-end database 274beans 9bi-directional synchronization 272bundle activator 233Bundle Development Kit 43bundle manifest 233Bundle Project 89bundles 8

CC/C++ 6cellular modem 11CGI 184class loader 43CLDC 361Cloudscape 3, 86Common Gateway Interface 184communication protocol 157Connected Device Configuration 6Connected Limited Device Configuration 6, 361Connections 112Core Bundles

Configuration Admin Service 46Device Access 46HTTP Service 46Log Service 46Preferences Service 46Service Tracker 46System Bundle 46User Admin Service 46

core services 43cost of ownership 4

© Copyright IBM Corp. 2005. All rights reserved.

Ddata storage 6data synchronization 3Database 83

bundles 84Cloudscape 86–87database service bundle 88DB2 Everyplace 85DB2 Everyplace Client bundle 85DB2 Everyplace ISync Client bundle 85DB2 Universal Database 85DB2e 86IBM Cloudscape Client bundle 85IBM Cloudscape ISync Client bundle 85troubleshooting 108

Database bundlesDB2EveryplaceClient 84DB2EveryplaceClientSync 84IBM Cloudscape 5.1 84IBMCloudscapeSyncClient 84

DataPropagator subscription 276DB2

active database parameter 316CATALOG command 279Client Configuration Assistant 279Control Center 291

DB2 application aervice 232DB2 Everyplace 86

Binding LDAP and MDAC 302components 272creating subscription set 291creating subscriptions 291DB2 Everyplace database 272DB2 Everyplace SDK 273DB2 Everyplace Sync Server 272DB2eCLP 303Group 283mirror database 284Mobile Devices Administration Center 274Subscription 283Subscription set 283User 283

DB2e 3DB2e synchronization 271

413

Page 430: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Architecture 273configuration test 303control database 280Custom subscription 275DataPropagator subscription 275DB2 Everyplace database 272DB2 Everyplace Sync Server 272Debug 279Enable tracing 279File subscription 275Filtering data 278Hints 315horizontal filtering 278JDBC Subscription 275logs files 279remote DB2 databases 279Server configuration 283tips 315Trace files 280tracing 279Upload subscription 275user-based filtering 278vertical filtering 278

debug 68debug mode 68define subscription set 299development framework 5device 2device configuration 318Device Management 33, 317

Architecture 319Device Manager 319Device Manager Console 321Device Manager database 320distribution package 322DM servlet 319enrolled devices 319jobs 319management tasks 319Open Service Gateway Initiative 318OSGi Agent 320OSGi bundles 318OSGi devices 317OSGi plug-in 318portlets 321WebSphere Everyplace Access 317

Device Management Server 8Device Manager 319

Nokia OMA DM plug-in 320

OSGi plug-in 320Palm OS plug-in 320Sharp Linux Zaurus plug-in 320Sony Ericsson P900 plug-in 320SyncML DM plug-in 320WinCEOSGi plug-in 320Windows 32-bit plug-in 320Windows CE plug-in 320

device-centric model 2distributed application 2

EEclipse 1–2, 5Eclipse Default JRE 231Eclipse RCP 13Enterprise Java Beans 184eRCP 5, 23eSWT 5, 23Everyplace Access Services 274Extension Services 43

Default JRE 231Java Class Library Foundation 231Java Class Library Max 231Java Class Library Min 231

Extension Services BundlesCloudscape 47Cloudscape ISync Client 47DB2 Everyplace 47DB2 Everyplace ISync Client 47Web Services using generated Stub Classes 47Web Services using Proxy services 47WebSphere Everyplace using JMS 47WebSphere MQ Everyplace 47WebSphere MQ Telemetry Transport 47

Extension Services Local Server 225Extension Services Project 186

Ffirewall 110Foundation Profile 23framework 43

GGUI 7

HHints and tips 315

414 WCTME: Application Development and Case Study

Page 431: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

HTML 19HTTP Services 183

IIBM HTTP Server 274Internet 110Internet applet 7inventory collection 318IP 116ITSO Car Rentals 17

application flow 28application panels 25Application properties 31Creating the source database 283Creating users and groups 287data flow 21Data requirements 18Data synchronization 22database 20DB2 Everyplace 33Deploying to a Pocket PC 267Device Management 35messaging 22MQe messaging 35Running the platform build 266stand-alone operation 22tables 20user interaction 22Web Services 22, 35

JJ2EE 3–4, 6, 14J2ME 1, 6, 13J2ME Web Services Specification 159J2SE 6, 14J2SE applications 12J9 5JAR file 318Java 1Java 2 Micro Edition 6

Foundation Profile 6J2ME Configurations 6J2ME Profiles 6Mobile Information Device Profile 6Personal Profile 7

Java Abstract Window Toolkit 7Java APIs 6Java beans 184

Java Class Library 230Configuring 230Customizing 231

Java Class Library Foundation 231Java Class Library Max 231Java Class Library Min 231Java packages 44Java Server Pages 183–184Java Virtual Machine 5JDBC 23JDBC Subscription 293, 298JDBC subscription 275JSP 9, 184JSP 1.2 specification 185JSR169 14

LLAN 11LDAP 274–275lightweight devices 110Linux 240Listeners 112local networks 42

MMacOS 240maintenance 3Manifest file 236

components 236MDAC 283, 301, 303, 316Messages 111Messaging 109

Connections 111Listeners 111Messages 111Queue managers 111Queues 111Troubleshooting 153WebSphere MQ 110WebSphere MQ Everyplace 110

Micro Environment Toolkit 2middleware 2MIDlet applications 361MIDP 361MIDP devices 10, 20mirror database 38Mobile Devices Administration Center 283Mobile Information Device Profile 361

Index 415

Page 432: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Mobile Media APIs 14MQ Everyplace C class 111MQ Everyplace Java class 111MQe 3MQe gateway 22MQe messaging 33

Nnetworked model 2

OOpen Mobile Alliance Device Management 318Open Service Gateway Initiative 318operating system 9OSGi 4OSGi Agent 320OSGi Alliance 8OSGi bundles 322

bundle activator 323dependencies 323documentation 323manifest file 322resources 322Software distribution 322

OSGi devices 320Bundle control 320Command script 320Custom command 320Device configuration 320Inventory collection 320Node discovery 320Software distribution 320Software list update 320Software removal 320

Pparent synchronization group 289PC-based model 2PDAs 110Personal Basis Profile 6Personal Digital assistants 4, 110Personal Profile 6pervasive computing 318pervasive devices 2, 4Platform Builder Project 239PocketPC 196, 240program model 43

programming model 8programming techniques 3public networks 110

QQueue Managers 112Queues 112

asynchronous queue 112local 112remote 112synchronous queue 112

RRational Application Developer 14–15Rational Web Developer 15Red Hat Linux 240Redbooks Web site 412

Contact us xivrelational database 84, 272remote queue 112replication frequency 298Rich Client Platform 2, 5runtime 68

Sserver-based model 2service implementation 43service interface 43Service Management Framework 2, 7Service Management Framework Runtime 41

Core bundles 43, 46custom bundles 43Example 49Extension Service Bundle 67Installing bundles 79OSGi 42OSGi service platform 42Running 44Specific bundles 46Starting 73Stopping 76Troubleshooting 68Uninstalling bundles 81

service providers 42Service-Oriented Architecture 156

components 156loose coupling 156

416 WCTME: Application Development and Case Study

Page 433: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Service broker 156Service provider 156Service requestor 156

Services 156Servlet 2.3 specification 185Servlets 39, 183–184session 318Simple Object Access Protocol 158

encoding rules 158envelop 158remote procedure call 158

smart devices 42SMF 4SMF Bundle Server 70, 75

Removing bundles 80Starting 70Stopping 75Submitting 77

SMF Bundles 3SMF Perspective 50, 54SMF Specific Bundles

CDSBundleSupport 46DependencyAdmin 46FileAdmin 46Language bundles 46Meta Type Service 46Micro XML 46RemoteVmAdminAgent 46SessionService 46SMFAdmin 46Web Application 46Web Container 46Web HTTP Service 46XML parser APIs 46XML4J 46

SOA 156socket 24software distribution 318Solaris 240Standard Widget Toolkit 5SWT 5sync servlet 282SyncML DM 318system application aervices 230System Application Services

Customizing 231

Tthreads 44Transponder 144trigger 24

UUniversal, Description, Discovery and Integration 158Update Manager function 14Upload subscription 277

WWAR 184WCTME 1–4, 12WCTRE 12WEA 271Web application bundle 186, 239Web applications 9, 12, 184Web Archive file 184Web Container 3, 23Web Services 1, 33, 37, 155, 375

architecture 159Bundle Project 162HTTP 157JSR 101 158JSR 109 158JSR 110 159JSR 172 159JSR 173 159JSR 181 159JSR 208 159JSR 222 159JSR 224 159JSR 31 158JSR 67 158JSR 921 159JSR 93 158Service-Oriented Architecture 155SOAP 157Troubleshooting 182UDDI 158WCTME 155Web Service Client Interface 162Web Service Interface 161WSDL 158WSIL 158XML 157

Web Services Client

Index 417

Page 434: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

Create a Web Service 381Web Services Description Language 158Web Services Gateway 255Web Services Inspection Language 158WebSphere Application Server 184WebSphere Everyplace Access 271, 274, 318

core services 321Device Manager 321Subscription Manager 321

WebSphere Everyplace Custom Environment 2, 4WebSphere Everyplace Micro Environment 2, 4WebSphere MQ Everyplace 110

Building Messages 115forward queue 114home server queue 114local queue 113message 113Message Flow 112message listener 113Processing Messages 116queue manager 113remote queue 113store queue 114

WebSphere Portal 283, 292, 303WebSphere Studio Application Developer 184WebSphere Studio Device Developer 1, 6, 13, 184

installation 352plug-in installation 354

WebSphere Studio Site Developer 184installation 349

WebSphere Test environment 187WiFi 11Windows 2000 240Windows XP 240WindowsCE 240Workplace Client Technologies 1Workplace Client Technology Micro Edition 2, 4

Application configuration 229DB2 Everyplace 272Deploying an application 239Exporting application bundles 241Exporting web application bundles 244HTTP Services 185Installation prerequisites 348Installing 347Programming database synchronization 304SMF Bundle Server 247WebSphere Studio Device Developer installa-tion 349

WebSphere Studio Device Developer plug-in in-stallation 349WebSphere Studio Site Developer installation 349

workspace 34

XXML 158

ZZaurus 240

418 WCTME: Application Development and Case Study

Page 435: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.
Page 436: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

®

SG24-6496-00 ISBN 0738491071

INTERNATIONAL TECHNICALSUPPORTORGANIZATION

BUILDING TECHNICALINFORMATION BASED ONPRACTICAL EXPERIENCE

IBM Redbooks are developed by the IBM International Technical Support Organization. Experts from IBM, Customers and Partners from around the world create timely technical information based on realistic scenarios. Specific recommendations are provided to help you implement IT solutions more effectively in your environment.

For more information:ibm.com/redbooks

IBM Workplace Client Technology Micro Edition Version 5.7.1: Application Developmentand Case Study

Develop applications using WebSphere Studio Device Developer

Extend enterprise applications to mobile devices

Learn about SMF as an implementation of OSGi

This IBM Redbook covers end-to-end pervasive solutions and provides the implementation guidelines necessary for architects and application developers. Workplace Client Technology Micro Edition (WCTME) is an integrated platform for the extension of existing enterprise applications to server-managed client devices such as desktop and mobile computers, personal digital assistants (PDAs), and other mobile and pervasive devices.

This redbook provides an implementation of pervasive client functions and their interaction with corresponding servers. It also includes information about the use of tools for development and deployment of an end-to-end pervasive solution, including integration considerations and application scenarios between enterprise pervasive clients, pervasive middleware and corresponding server based applications. You will find information about using tools for implementation of functions that are essential in a pervasive solution for the whole architecture such as fundamentals of programming models, capabilities provided by WCTME tooling and runtime, tooling structure and flow, wizards and code generation, platform configuration and deployment.

A basic knowledge of Java programming, Java technologies and Java open standards such as OSGi is assumed.

Back cover

Page 437: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.

(0.5” spine)0.475”<

->0.875”

250 <->

459 pages

WCTM

E: Application Development and Case Study

Page 438: WCTME: Application Development and Case Study Customizing the Java Class Library (JCL) and application services. . . . 231 ... Application Development and Case Study. 1 1. The . 7.