Developing Applications With IBM FileNet P8 APIs
Developing Applications With IBM FileNet P8 APIs
Wei-Dong Zhu Bill Carpenter Tim Lai Wei Liao Michael Oland James S Pagadala Juan Saad
ibm.com/redbooks
International Technical Support Organization Developing Applications with IBM FileNet P8 APIs December 2009
SG24-7743-00
Note: Before using this information and the product it supports, read the information in Notices on page xiii.
First Edition (December 2009) This edition applies to Version 4, Release 5, of IBM FileNet Content Manager (product number 5724-R81) and Version 4, Release 5, of IBM FileNet Business Process Manager (product number 5724-R76)
Copyright International Business Machines Corporation 2009. All rights reserved. Note to U.S. Government Users Restricted Rights -- Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
Contents
Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiv Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv The team who wrote this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi Become a published author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviii Comments welcome. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviii Chapter 1. Platform and API overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 Platform overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.2 IBM FileNet API overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.2.1 Content Engine APIs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2.2 Process Engine APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.2.3 Records Manager Java API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.2.4 The eForms APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.2.5 Capture APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.2.6 Image Services Resource Adapter . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 1.3 Communication between applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Chapter 2. Setting up development environments. . . . . . . . . . . . . . . . . . . 13 2.1 Content Engine Java development setup . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.1.1 Required libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.1.2 Transport protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.1.3 Thick client versus thin client requirements . . . . . . . . . . . . . . . . . . . 15 2.1.4 Sample Content Engine Java API application setup in Eclipse . . . . 22 2.2 Process Engine Java development setup . . . . . . . . . . . . . . . . . . . . . . . . . 27 2.2.1 Required libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 2.3 .NET environment setup for CE and PE . . . . . . . . . . . . . . . . . . . . . . . . . . 29 2.3.1 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 2.3.2 Running the sample application supplied by IBM . . . . . . . . . . . . . . . 29 2.3.3 Configuring VisualStudio.NET 2005 . . . . . . . . . . . . . . . . . . . . . . . . . 30 2.4 PE REST API sample code development setup . . . . . . . . . . . . . . . . . . . . 33 2.5 ECM Widgets development setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Chapter 3. Introduction to Content Engine API programming . . . . . . . . . 39 3.1 Content Engine API class overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 3.1.1 Content Engine API class model. . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
iii
3.2 Making the initial connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 3.2.1 User authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 3.2.2 Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 3.2.3 .NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 3.3 Exception handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 3.4 Creating, retrieving, updating, and deleting objects . . . . . . . . . . . . . . . . . 52 3.4.1 Pending actions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 3.4.2 Creating objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 3.4.3 Working with properties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 3.4.4 Retrieving objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 3.4.5 Deleting objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 3.4.6 Retrieving content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 3.4.7 Working with property filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 3.5 getInstance() versus fetchInstance() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 3.6 Querying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 3.6.1 SearchSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 3.6.2 Search scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 3.6.3 Content searches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 3.6.4 Paging support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 3.7 Viewing documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 3.7.1 User tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 3.8 Batching and batch execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Chapter 4. Advanced Content Engine API programming . . . . . . . . . . . . . 87 4.1 Permissions and authorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 4.2 Versioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 4.3 Relationships. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 4.3.1 Object-valued properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 4.3.2 Filing in a folder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 4.3.3 Compound documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 4.4 Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 4.5 Subscriptions and event actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 4.6 Workflow subscriptions and workflow event actions . . . . . . . . . . . . . . . . 105 4.7 Metadata discovery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 4.8 Dynamic security inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 Chapter 5. Introduction to Process Engine API programming . . . . . . . . 111 5.1 Process Engine API overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 5.1.1 Functional groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 5.1.2 Available API functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 5.1.3 Naming conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 5.1.4 Core classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 5.1.5 Functional relationship . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
iv
5.2 Establishing a Process Engine session. . . . . . . . . . . . . . . . . . . . . . . . . . 119 5.2.1 Java API scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 5.2.2 PEWS API scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 5.2.3 REST API scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 5.3 Handling API exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 5.3.1 VWException object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 5.3.2 Steps to handle an exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 5.4 Launching a workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 5.4.1 REST API scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 5.5 Search work items. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 5.5.1 Query a roster . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 5.5.2 Workflow queues. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 5.5.3 Query event log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 5.6 Process work items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 5.6.1 Retrieve step element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 5.6.2 Get step element parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 5.6.3 Set step element parameter values . . . . . . . . . . . . . . . . . . . . . . . . 148 5.6.4 Complete work items. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 5.7 Work with process status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 5.7.1 Retrieve process history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 5.7.2 Retrieve process milestones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 Chapter 6. Advanced Process Engine API programming . . . . . . . . . . . . 167 6.1 Component Integrator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 6.1.1 CE_Operations component. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 6.1.2 Implementing a custom Java component . . . . . . . . . . . . . . . . . . . . 170 6.2 Application space, role, and workbasket . . . . . . . . . . . . . . . . . . . . . . . . . 187 6.2.1 Retrieve role list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 6.2.2 Retrieve role description and attributes. . . . . . . . . . . . . . . . . . . . . . 189 6.2.3 Retrieve workbasket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 6.2.4 Query work items from workBasket . . . . . . . . . . . . . . . . . . . . . . . . 194 6.3 Resource navigation in Process Engine REST API . . . . . . . . . . . . . . . . 199 6.4 ECM Widgets overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 6.4.1 ECM Widgets concepts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 6.4.2 ECM Widgets system architecture . . . . . . . . . . . . . . . . . . . . . . . . . 205 6.5 Building a custom Get Next In-basket widget . . . . . . . . . . . . . . . . . . . . . 206 6.5.1 Use case for the Get Next widget . . . . . . . . . . . . . . . . . . . . . . . . . . 207 6.5.2 Setup development environment . . . . . . . . . . . . . . . . . . . . . . . . . . 209 6.5.3 Code structure of the Get Next widget . . . . . . . . . . . . . . . . . . . . . . 210 6.5.4 Defining the Get Next widget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 6.5.5 Code skeleton for GetNext.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213 6.5.6 Rendering the Get Next widget user interface . . . . . . . . . . . . . . . . 215 6.5.7 Invoking PE REST service to fetch queue element . . . . . . . . . . . . 215
Contents
6.5.8 Invoking PE REST service to fetch role and In-basket list . . . . . . . 217 6.5.9 Deploying the widget. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 6.5.10 Building the solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 Chapter 7. Sample applications for Fictional Auto Rental Company A . 223 7.1 Introduction to sample applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 7.2 Business use cases. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 7.3 User view of the sample applications . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 7.3.1 User view: Reservation Web application. . . . . . . . . . . . . . . . . . . . . 226 7.3.2 User view: Kiosk application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 7.3.3 User view: Agent handheld application . . . . . . . . . . . . . . . . . . . . . . 232 7.3.4 User view: Fleet Status Manager Web application . . . . . . . . . . . . . 232 7.3.5 User view: Billing Report application . . . . . . . . . . . . . . . . . . . . . . . . 237 7.4 Data model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 7.4.1 Base classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 7.4.2 ITSOVechicle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 7.4.3 ITSOPhotoGallery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 7.4.4 ITSOThumbnail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 7.4.5 ITSOVehicleActivity. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 7.4.6 ITSOSingleton. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 7.4.7 ITSORentalActivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 7.4.8 ITSOMaintenanceActivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 7.4.9 ITSODisposalActivity. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 7.4.10 ITSOIdleActivity. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 7.4.11 ITSOCustomer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 7.4.12 ITSOCommentary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 7.4.13 ITSOFranchise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 7.4.14 ITSORole . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258 7.5 Security model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260 7.6 Workflows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 7.6.1 Isolated region configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 7.6.2 Component queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 7.6.3 Vehicle reservation workflow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 7.6.4 Vehicle maintenance workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 7.7 Internal architecture of sample applications . . . . . . . . . . . . . . . . . . . . . . 268 7.7.1 Architecture: Reservation Web application . . . . . . . . . . . . . . . . . . . 268 7.7.2 Architecture: Kiosk application . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 7.7.3 Architecture: Fleet Status Manager Web application . . . . . . . . . . . 272 7.7.4 Architecture: Billing Report application . . . . . . . . . . . . . . . . . . . . . . 274 7.8 Deployment instructions for sample applications . . . . . . . . . . . . . . . . . . 276 7.8.1 Application package structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278 7.8.2 Content Engine artifacts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 7.8.3 Process Engine artifacts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
vi
Deployment: Reservation Web application . . . . . . . . . . . . . . . . . . . 292 Deployment: Kiosk application . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 Deployment: Fleet Status Manager Web application . . . . . . . . . . . 296 Deployment: Billing Report application . . . . . . . . . . . . . . . . . . . . . . 299
Chapter 8. Logging and troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . 305 8.1 Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306 8.1.1 CE Java API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306 8.1.2 CE .NET API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 8.1.3 Content Engine Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 8.1.4 PE Java API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 8.1.5 Process Engine Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 8.1.6 PE REST Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 8.2 Troubleshooting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 8.2.1 log4j debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 8.2.2 Content Engine troubleshooting techniques . . . . . . . . . . . . . . . . . . 313 8.2.3 Process Engine troubleshooting techniques . . . . . . . . . . . . . . . . . . 313 8.2.4 Data must be gathered for troubleshooting . . . . . . . . . . . . . . . . . . . 314 Appendix A. Additional material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 Locating the Web material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 Using the Web material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 System requirements for downloading the Web material . . . . . . . . . . . . . 316 How to use the Web material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 Related publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 IBM Redbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 Online resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 How to get Redbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 Help from IBM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
Contents
vii
viii
Figures
1-1 Core engines and data storage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1-2 Core engines with additional applications . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1-3 Application communication between core engines and available applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1-4 .NET application communication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1-5 Typical Java application communication . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2-1 Content Engine Client libraries installation directory . . . . . . . . . . . . . . . . . 14 2-2 WebSphere 6.1 Application Client installation directory . . . . . . . . . . . . . . 16 2-3 Eclipse runtime configuration for WebSphere EJB transport JVM parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 2-4 Sample WebSphere sas.client.props entries . . . . . . . . . . . . . . . . . . . . . . 17 2-5 CE 4.5.0 CEWS transport installation directory . . . . . . . . . . . . . . . . . . . . 19 2-6 Eclipse runtime configuration for CEWS transport JVM parameters . . . . 20 2-7 Required .jar files for CE and CEWS transport . . . . . . . . . . . . . . . . . . . . . 23 2-8 ContentEngineDemo create cesample package . . . . . . . . . . . . . . . . . . . . 23 2-9 Imported demo Java classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 2-10 Java Application runtime profile for MainFrame.java . . . . . . . . . . . . . . . 24 2-11 Runtime JVM parameters for MainFrame.java . . . . . . . . . . . . . . . . . . . . 25 2-12 Demo application main page. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 2-13 Demo application: Test Server Connection. . . . . . . . . . . . . . . . . . . . . . . 26 2-14 Process Engine Client libraries installation directory . . . . . . . . . . . . . . . 27 2-15 Eclipse jar files for Process Engine development . . . . . . . . . . . . . . . . . . 28 2-16 Process Engine JVM parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 2-17 Adding a reference to the CE API DLL . . . . . . . . . . . . . . . . . . . . . . . . . . 31 2-18 Adding a Content Engine Web Service .NET Web Reference . . . . . . . . 32 2-19 Adding a Process Engine Web Service .NET Web Reference . . . . . . . . 33 2-20 Create New Web Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 2-21 Specify the Project Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 2-22 Code structure after you copy Dojo library . . . . . . . . . . . . . . . . . . . . . . . 35 2-23 Test page for PE REST API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 2-24 Export the project as WAR file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 3-1 Class relationships and general object flow . . . . . . . . . . . . . . . . . . . . . . . 43 3-2 Objects and properties returned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 3-3 Compiled SQL statement from Content Engine Query Builder . . . . . . . . . 73 4-1 VersionSeries object with multiple IndependentObjects . . . . . . . . . . . . . . 91 5-1 Primary Runtime API objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 5-2 Runtime API core classes calling sequences . . . . . . . . . . . . . . . . . . . . . 118 6-1 Java component association. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
ix
6-2 Run configuration for PEComponentQueueHelper . . . . . . . . . . . . . . . . . 183 6-3 Example for PEComponentQueueHelper parameters in Eclipse . . . . . . 184 6-4 Run configuration for Component Manager START . . . . . . . . . . . . . . . . 186 6-5 Example for Component Manager START parameters in Eclipse . . . . . 186 6-6 Example for Component Manager STOP parameters in Eclipse . . . . . . 187 6-7 My Work page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 6-8 Step Processor Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 6-9 Single Page application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 6-10 ECM Widgets system architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 6-11 Get Next In-basket Widget working with the other ECM Widgets . . . . . 207 6-12 Use case for the Get Next widget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 6-13 Create a new Web application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 6-14 Specify the project name. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 6-15 Code Structure of Get Next Widget. . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 6-16 The Get Next widget in the view mode . . . . . . . . . . . . . . . . . . . . . . . . . 215 6-17 The Get Next widget in the edit mode. . . . . . . . . . . . . . . . . . . . . . . . . . 215 6-18 Export sample Web application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 6-19 The Get Next widget in Business Space toolbox . . . . . . . . . . . . . . . . . 219 6-20 Create mashup page. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 6-21 Place the widgets in the mashup page . . . . . . . . . . . . . . . . . . . . . . . . . 220 6-22 Wire Get Next and Step Completion by Send Work Item Id and Receive Work Item Id events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 6-23 Wire Step Completion and Get Next by Send Work Item Id and Receive Work Item Id events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 6-24 Configure the Get Next widget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 7-1 Reservation Web application login panel . . . . . . . . . . . . . . . . . . . . . . . . 227 7-2 Reservation Web application registration panel . . . . . . . . . . . . . . . . . . . 227 7-3 Reservation Web application main data panel . . . . . . . . . . . . . . . . . . . . 228 7-4 Reservation Web application vehicle selection panel . . . . . . . . . . . . . . . 228 7-5 Reservation Web application credit card information collection panel . . 229 7-6 Reservation Web application rental reservation confirmation panel . . . . 230 7-7 Entering confirmation number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 7-8 Rental information dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 7-9 Vehicle return dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232 7-10 Fleet Status Dashboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234 7-11 Fleet Manager page to send vehicle for maintenance . . . . . . . . . . . . . 235 7-12 Maintenance queue page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 7-13 Maintenance worker page: route work item to workers work queue . . 236 7-14 Maintenance worker page: process work item . . . . . . . . . . . . . . . . . . . 236 7-15 Maintenance queue page for a different user . . . . . . . . . . . . . . . . . . . . 237 7-16 Process Administrator showing work items in roster. . . . . . . . . . . . . . . 237 7-17 Login dialog for Billing Report application . . . . . . . . . . . . . . . . . . . . . . . 238 7-18 Login failed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
7-19 7-20 7-21 7-22 7-23 7-24 7-25 7-26 7-27 7-28 7-29 7-30 7-31 7-32 7-33 7-34 7-35 7-36 7-37 7-38 7-39 7-40 7-41 7-42 7-43 7-44 7-45
Main window for Billing Report application . . . . . . . . . . . . . . . . . . . . . . 239 Model for ITSODocument and subclasses . . . . . . . . . . . . . . . . . . . . . . 240 Models for ITSOFolder, ITSOAnnotation, and subclasses . . . . . . . . . . 241 Model for ITSOCustomObject and subclasses . . . . . . . . . . . . . . . . . . . 242 ITSO vehicle reservation main workflow diagram . . . . . . . . . . . . . . . . . 265 ITSO vehicle maintenance main workflow diagram . . . . . . . . . . . . . . . 267 Program flow for Reservation Web application . . . . . . . . . . . . . . . . . . . 269 Program flow for Kiosk application . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 Program flow for Fleet Status Manager application . . . . . . . . . . . . . . . 273 Program flow for Billing Report application . . . . . . . . . . . . . . . . . . . . . . 276 Directory structure of sg247743-sample . . . . . . . . . . . . . . . . . . . . . . . . 278 CE import task. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 CE import helper panel Import Options. . . . . . . . . . . . . . . . . . . . . . . . . 282 CE import helper panel Import Items for metadata . . . . . . . . . . . . . . . . 283 CE import helper panel Import Items for instance data. . . . . . . . . . . . . 284 ITSOAutoRental and subfolders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 Stop all component manager instances . . . . . . . . . . . . . . . . . . . . . . . . 286 Ensure correct notification settings on Process Task Manager . . . . . . 286 Import isolated region configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 Set JAAS credentials on component queues . . . . . . . . . . . . . . . . . . . . 288 ITSOOperations.jar required library . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 ITSO_Operations JRE parameters sample. . . . . . . . . . . . . . . . . . . . . . 291 Component Manager started with no errors . . . . . . . . . . . . . . . . . . . . . 292 Importing the BillingReportApplication project into Eclipse . . . . . . . . . . 301 BillingReportApplication structure in Eclipse . . . . . . . . . . . . . . . . . . . . . 302 Run As Java Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 Billing application JVM requirements . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Figures
xi
xii
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 illustrate 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.
xiii
Trademarks
IBM, the IBM logo, and ibm.com are trademarks or registered trademarks of International Business Machines Corporation in the United States, other countries, or both. These and other IBM trademarked terms are marked on their first occurrence in this information with the appropriate symbol ( or ), indicating US registered or common law trademarks owned by IBM at the time this information was published. Such trademarks may also be registered or common law trademarks in other countries. A current list of IBM trademarks is available on the Web at http://www.ibm.com/legal/copytrade.shtml The following terms are trademarks of the International Business Machines Corporation in the United States, other countries, or both: FileNet IBM Rational Redbooks Redpaper Redbooks (logo) WebSphere
The following terms are trademarks of other companies: FileNet, and the FileNet logo are registered trademarks of FileNet Corporation in the United States, other countries or both. JBoss, and the Shadowman logo are trademarks or registered trademarks of Red Hat, Inc. in the U.S. and other countries. Java, and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both. Microsoft, Windows, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both. Intel, Intel logo, Intel Inside logo, and Intel Centrino logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States and other countries. Other company, product, or service names may be trademarks or service marks of others.
xiv
Preface
This IBM Redbooks publication can help you develop content and process management applications with IBM FileNet APIs. The IBM FileNet P8 suite of products contains a set of robust APIs that range from core platform APIs to supporting application APIs. This book focuses specifically on Content Engine and Process Engine APIs. The two core components of IBM FileNet P8 Platform are Content Engine and Process Engine. Content Engine handles content storage, indexing, and retrieval. In addition, it offers services for enabling active content through events and subscriptions, allowing code to be executed on an event-driven basis. Process Engine handles all workflow and process routing. The Content Engine and Process Engine APIs enable you to develop applications that can perform the Content Engine and Process Engine functions. In this book, we show you how to set up programming environments for Java, .NET, REST API, and ECM Widget development. We provide a class overview, a description of how to make connections to the engines, and examples of exception handling. Content Engine API topics that we discuss include creating, retrieving, updating, and deleting objects; querying and viewing documents; and batching and batch execution. We also explore more complex topics, including permissions and authorization, versioning, relationships, annotations, workflow subscriptions and event actions, metadata discovery, and dynamic security inheritance. Process Engine API topics that we discuss include launching a workflow, searching for and processing work items, and working with process status. The more complex topics we cover include, Component Integrator application space, role, workbasket, resource navigation in Process Engine REST API, ECM Widgets, and building a custom Get Next In-basket widget. To help you better understand programming with IBM FileNet APIs, we provide a sample application implemented for a fictional company. We include the data model, security model, workflows, and various applications developed for the sample. You can download them for your reference. In this book, we also teach you how to enable and interpret the various logging options for the IBM FileNet P8 Platform APIs. We point you to the technical troubleshooting articles and provide important data-gathering points when troubleshooting IBM FileNet programming issues.
xv
This book is intended for IBM FileNet P8 application developers. We recommend using this book in conjunction with the online ECM help.
xvi
Michael Oland is an IT Advisory Specialist with IBM Enterprise Content Management Lab Services in Washington, D.C. He has 10 years experience in enterprise content management, which includes Web content delivery and management, document and information management, and business process management. For the last six years, he has focused primarily on content migration, and developing tools for content migration. He holds a degree in Broadcasting from the University of Tennessee, Knoxville. James S Pagadala is a J2EE Enterprise Application Consultant from IBM India. He has more than seven years of experience in developing J2EE applications. His primary focus is supply chain management. He has managed and lead many J2EE applications in this domain. James has a Master of Computer Applications degree from the Karnataka Regional Engineering College, Surathkal, India. He joined IBM in 2001. Juan Saad is a Senior Architect for Enterprise Content Management solutions with an IBM Business Partner in Melbourne, Australia. Juan has nine years of experience with organizations, designing, implementing, and maintaining Business Process Management and Content Management solutions based on the IBM FileNet P8 Platform. Juan has been involved in all phases of a system development life cycle, both functionally and technically, including client interface, business process analysis and modeling, application design and development, and system testing and research methods. He is a Certified Administrator and Developer for several IBM FileNet P8 products such as Business Process Manager, Content Manager, Records Manager, Email Manager, and Forms Manager. Thanks to the following people and groups for their contributions to this project: Patrick Doonan William Lobig Mike Winter Quynh Dang Evangeline Fink Robert Mariano Mike Marin Lauren Mayes Himanshu Shah Darik Siegfried IBM Software Development Lab in Costa Mesa, California Dave Perman IBM Software Development Lab in Vancouver, B.C., Canada
Preface
xvii
Comments welcome
Your comments are important to us! We want our books to be as helpful as possible. Send us your comments about this book or other IBM Redbooks publications in one of the following ways: Use the online Contact us review Redbooks form found at: ibm.com/redbooks Send your comments in an e-mail to: [email protected] Mail your comments to: IBM Corporation, International Technical Support Organization Dept. HYTD Mail Station P099 2455 South Road Poughkeepsie, NY 12601-5400
xviii
Chapter 1.
Ready-to-use Applications (Workplace XT, Enterprise Manager) Content Engine Process Engine
Data Storage
The CE handles content storage, indexing, and retrieval. In addition, the CE offers services for enabling active content through events and subscriptions, allowing code to be executed on an event-driven basis. The PE handles all workflow and process routing. The applications that are ready for use include Workplace XT and IBM FileNet Enterprise Manager. In addition to the core engines, a number of add-on products offer additional functionality and are built on the core engines. Some of these applications include IBM FileNet Records Manager and IBM FileNet Capture. See Figure 1-2 on page 3.
Records Manager
Capture
Content Engine
Process Engine
Data Storage
Figure 1-2 Core engines with additional applications
possible when both the client application and the CE server are running on Microsoft Windows. The .NET API communicates with the CE server over the Web Services transport.
properties, and update operations. The IBM FileNet Content Manager product documentation describes how these pieces interrelate, but we recommend you also read the developer documentation for the Java or .NET API to get an additional understanding of how the things mentioned in the WSDL were intended to be used. A common question for CEWS developers is what the XML actually looks like for various requests. The official specification, of course, is the WSDL, and any XML generated by your client must comply with that. The simplest way to obtain samples of actual XML is to use either the .NET or Java API with CEWS transport and use a network tracing tool to capture the data from the interactions. You will see both the requests and responses. Because of the rich variety of possible interactions in CEWS, IBM support does not have a set of ready-made XML samples. Note: As of release 4.5.0, CE supports three Web services endpoints. The difference is in their handling of content attachments. The SOAP endpoint (FNCEWS40SOAP) uses inline content and carries significant performance costs. It should therefore be avoided. Support for the Direct Internet Message Encapsulation (DIME) endpoint (FNCEWS40DIME) is documented as deprecated and will eventually be removed. Therefore, all new code should be written for the Message Transmission Optimization Mechanism (MTOM) endpoint (FNCEWS40MTOM), and existing DIME code should be migrated to MTOM as soon as possible.
Any new Microsoft environment development should be done by using the IBM FileNet Content Manager 4.x .NET API because all new features will be incorporated into the 4.x APIs. The COM Compatibility Layer API is only mentioned in this Redbooks publication in terms of how to configure the environment. There will be no discussion on COM Compatibility Layer programming.
for image acquisition (for example, scanning and document upload), batching, advanced document recognition (ADR), and others. This API set is not covered in this book.
Application Engine and Workplace XT Enterprise Manager .NET WSI Java API Java API
Content Engine
Java API
Process Engine
Figure 1-3 Application communication between core engines and available applications
For custom applications, the communications path used depends on both the API used and which transport is selected for use. Figure 1-4 shows the typical communication path for .NET-based applications.
.NET
PE/WSI
Content Engine
Process Engine
Figure 1-5 on page 11 shows the typical communication path for Java-based applications. Although a J2EE application can use Web services transport to communicate with the CE, doing so is unusual. After an application is inside an application server, the EJB protocol has advantages in performance and ease of integration.
10
Java
Process Engine
In the remaining chapters of this book, we describe how to set up development environments and provide detailed discussions about the CE and PE APIs with a sample use case application.
11
12
Chapter 2.
13
14
programming on page 39 discusses more details of the transport protocols and the Uniform Resource Identifiers (URIs) to use for each.
WebLogic JBOSS
Figure 2-2 on page 16 shows the WebSphere 6.1 Application Client installed directories.
15
In addition to the application server .jar files, the Java virtual machine (JVM) parameters listed in this section are required for thick client applications: For EJB transport with WebSphere (Figure 2-3 on page 17): -Dcom.ibm.CORBA.ConfigURL=<WebSphereHome>\properties\sas.client.prop s -Djava.ext.dirs=<WebSphereHome>\java\jre\lib\ext;<WebSphereHome>\lib ;<WebSphereHome>\plugins -Djava.security.auth.login.config=c:\Program Files\FileNet\CEClient\config\samples\jaas.conf.WebSphere Where, <WebSphereHome> refers to the WebSphere Application Client home directory, for example, c:\Program Files\IBM\WebSphere\AppClient.
16
Figure 2-3 Eclipse runtime configuration for WebSphere EJB transport JVM parameters
Note: The CE server host name you use in your connection URI and the sas.client.props must be resolvable through DNS from your client machine. For WebSphere, the host name and port specified in your client application must match the host name and port number specified in the BOOTSTRAP_ADDRESS parameter in the WebSphere Administration Console. In sas.client.props, set the following properties (see Figure 2-4): com.ibm.CORBA.securityServerHost=ceServerName com.ibm.CORBA.securityServerPort=2809 com.ibm.CORBA.loginSource=none
17
Note that the port numbers assume default application server ports. Change them as needed for your specific environments.
Figure 2-5 on page 19 shows the CEWS installation directory where wasp.jar can be obtained.
18
Starting with CE 4.5.1, Systinet libraries are no longer used. Instead, three new IBM libraries are required for CEWS transport as listed in Table 2-3.
Table 2-3 Thick client CEWS transport library requirements for CE 4.5.1 and beyond Application server Applies to all application servers Required .jar files stax-api.jar xlxpScanner.jar xlxpScannerUtils.jar
As mentioned earlier, the CEWS transport requirements are the same for any application server. For the CEWS transport in CE 4.0 to 4.5.0, two JVM parameters are required (Figure 2-6 on page 20): -Dwasp.location=c:\Program Files\FileNet\CEClient\wsi -Djava.security.auth.login.config=c:\Program Files\FileNet\CEClient\config\samples\jaas.conf.WSI
19
Figure 2-6 Eclipse runtime configuration for CEWS transport JVM parameters
For the CEWS transport in CE 4.5.1 and beyond, the only JVM parameter required is the java.security.auth.login.config file, thereby eliminating the requirement to define the wasp.location parameter.
20
One way to troubleshoot connectivity issues is to deploy WorkplaceXT on the client application server. If WorkplaceXT can connect to CE successfully, you can then focus on configuring your custom application in the same fashion.
21
Table 2-4 Thin client CEWS transport library requirements for CE 4.0 to 4.5.0 Application server Applies to all application servers Required .jar files wasp.jar jaxrpc.jar jetty.jar runner.jar saaj.jar wsdl_api.jar activation.jar builtin_serialization.jar These eight .jar files can be obtained from the c:\Program Files\FileNet\CEClient\wsi\lib directory. See Figure 2-5 on page 19.
For CE 4.5.1 and later, there are no requirement differences between a thick client stand-alone application and a thin client application. The three .jar files that are still required for a thin client application using CEWS transport are listed in Table 2-5.
Table 2-5 Thin client CEWS transport library requirements for CE 4.5.1 and beyond Application server Applies to all application servers Required .jar files stax-api.jar xlxpScanner.jar xlxpScannerUtils.jar
With the 4.5.1+ implementations, the only required JVM parameter is: -Djava.security.auth.login.config=c:\Program Files\FileNet\CEClient\config\samples\jaas.conf.WSI
22
Download the Demo_Java.zip package. Use the following steps to configure and run this demonstration application in Eclipse: 1. Extract the Demo_Java.zip to a folder on your development environment. We refer to this folder where Demo_Java.zip is extracted to as <DEMO_HOME>. 2. Create a Java project in Eclipse. For the demo application, we use the project name ContentEngineDemo. 3. Add all the required CE .jar files as listed in 2.1.1, Required libraries on page 14. This demonstration is an example of a thick client application. Figure 2-7 shows the required .jar files for CE.
4. For the demonstration (Demo) application, we use the CEWS transport. Add the .jar file listed in 2.1.3, Thick client versus thin client requirements on page 15. Figure 2-7 shows the required .jar file for thick client CEWS transport. 5. Create a package called cesample under the src folder in Eclipse. See Figure 2-8.
6. Import all the classes from the folder <DEMO_HOME>/src/cesample as shown in Figure 2-9 on page 24.
23
7. Create a Java application runtime profile in Eclipse for the MainFrame.java class. See Figure 2-10.
8. Add all the required JVM parameters as listed in 2.1.3, Thick client versus thin client requirements on page 15. See Figure 2-11 on page 25.
24
9. Run the Java class MainFrame.java as a Java Application from Eclipse. See Figure 2-12.
25
10.Enter the following input values to test the CE connectivity. For this example, we use the CEWS transport to connect to CE: CE URI as: http://<server-name>:<port-number>/wsi/FNCEWS40MTOM JAAS Stanza as FileNetP8WSI Valid user name Password of user 11.After entering the input values, click Test Connection. The demo application connects to CE and retrieves the domain name along with a list of existing object stores. Figure 2-13 shows a successful connection and lists the COLL, and E2E object stores.
12.You can now click the other tabs of the Demo application such as Create Doc, Get Doc, and Create Folder, to test each feature. A Readme.doc file accompanies the Demo application. Refer to it for further information about using the Demo application.
26
27
When the PE Java development project has the WcmApiConfig.properties file in a directory as part of the classpath, there is no need to add the filenet.pe.bootstrap.ceuri parameter. This setting is taken from the WcmApiConfig.properties values (see Example 2-1 on page 29 for using with EJB transport with WebSphere and Example 2-2 on page 29 for using with CEWS transport with WebSphere).
28
2.3.1 Prerequisites
For a .NET environment, the two primary prerequisites that apply to both the CE and PE are: Microsoft .NET Runtime 2.0 Microsoft Web Services Enhancements 3.0
29
30
31
Figure 2-18 Adding a Content Engine Web Service .NET Web Reference
32
Figure 2-19 Adding a Process Engine Web Service .NET Web Reference
33
3. In the next dialog, specify the project name PERESTSample. Then, click Finish to create the project. See Figure 2-21 on page 35.
34
4. Extract the Dojo library .zip file to a temporary folder and copy the Dojo library into project folder dojoroot. After this step, the project structure looks like Figure 2-22.
5. Create a test page to run the sample code for PE REST API under folder samples. See Figure 2-23 on page 36.
35
6. In the testPEREST.html test page, copy and paste the code skeleton shown in Example 2-3.
Example 2-3 Code skeleton to test PE REST API
<html> <head> <title>Test PE REST API</title> <script type="text/javascript" src="../dojoroot/dojo/dojo.js" djConfig="isDebug:true"></script> <script type="text/javascript"> dojo.addOnLoad(function(){ // copy the sample code here }) </script> </head> <body> </body> </html> 7. Copy the sample code of PE REST API into the body of the anonymous function called by dojo.addOnLoad. Example 2-4 on page 37 shows a code example.
36
Example 2-4 A code sample to run PE REST API <html> <head> <title>Test PE REST API</title> <script type="text/javascript" src="../dojoroot/dojo/dojo.js" djConfig="isDebug:true"></script> <script type="text/javascript"> dojo.addOnLoad(function(){ // Ensure to be authenticated with the Application Server container var baseURL = "http://localhost:9080/WorkplaceXT/P8BPMREST/p8/bpm/v1/"; var applicationSpaceName = "GenericApproval"; // Construct the URI for roles var url = baseURL + "appspaces/" + applicationSpaceName + "/myroles"; // Use GET method to retrieve the roles dojo.xhrGet({ url: url, handleAs: "json-comment-optional", load: function(data) { // Callback to handle the data for(var roleName in data) { var role = data[roleName]; console.log("AuthoredName:" + roleName); console.log("Display Name:" + role.name); console.log("URI:" + role.URI); } }, error: function(data) { // The error callback console.dir(data); } } ); }) </script> </head> <body> </body> </html>
8. After you create the project and sample code, deploy this project to WebSphere to test it. In Eclipse, select File Export to open the export wizard. In the pop-up dialog, select WAR File, and save it to a folder. See Figure 2-24 on page 38.
37
9. Deploy the WAR file to WebSphere. The context root for the deployed Web application should be PERESTSample. 10.Access the test page to run the sample code for PE REST API. The Web address of the test page is: http://<server-name>:<port-number>/PERESTSample/testPEREST.html Note: Before you test the sample code, log in to WorkplaceXT first to ensure you can be authenticated with the application server container.
38
Chapter 3.
39
40
The CE API has over a hundred classes. They are arranged into a number of packages or namespaces, organized by functional areas, which include: Core Core (com.filenet.api.core and FileNet.Api.Core) provides classes related to the core business objects and other classes that are used in most applications. Examples include: Java: EntireNetwork, Document, Folder, CustomObject, Factory, UpdatingBatch, Connection .NET: EntireNetwork, IDocument, IFolder, ICustomObject, Factory, UpdatingBatch, Connection Meta Meta (com.filenet.api.meta and FileNet.Api.Meta) provides classes for holding immutable metadata for CE classes and properties. Examples include: Java: ClassDescription, PropertyDescription, PropertyDescriptionDateTime .NET: ClassDescription, IPropertyDescription, IPropertyDescriptionDateTime Admin Admin (com.filenet.api.admin and FileNet.Api.Admin) provides classes used in the administration of a CE, including classes for updating metadata objects. Examples include: Java: ClassDefinition, PropertyDefinition, PropertyDefinitionDateTime, DirectoryConfiguration, PEConnectionPoint, ServerInstance, TableDefinition .NET: ClassDefinition, IPropertyDefinition, IPropertyDefinitionDateTime, IDirectoryConfiguration, IPEConnectionPoint, IServerInstance, ITableDefinition Security Security (com.filenet.api.security and FileNet.Api.Security) provides classes related to authentication, authorization, and user-specific and group-specific data. Examples include: Java: User, Group, AccessPermission, MarkingSet .NET: IUser, IGroup, IAccessPermission, IMarkingSet
41
Query Query (com.filenet.api.query and FileNet.Api.Query) provides classes related to constructing and performing CE searches. Examples include: Java: SearchScope, RepositoryRow .NET: SearchScope, IRepositoryRow Collection Collection (com.filenet.api.collection and FileNet.Api.Collection) provides type-safe classes that are related to collections of objects. Examples include: Java: FolderSet, ContentElementList .NET: IFolderSet, IContentElementList Events Events (com.filenet.api.events, not available in .NET) provides classes representing events triggered on CE objects, as well as classes related to handling those events raised within the CE. Because all events are run inside the CE context, there is no equivalent .NET package. Examples include: Java: FileEvent, UnfileEvent, EventAction, InstanceSubscription Property Property (com.filenet.api.property and FileNet.Api.Property) provides classes related to CE properties and property values. Examples include: Java: Properties, PropertyDateTime, PropertyDateTimeList, PropertyFilter .NET: IProperties, IPropertyDateTime, IPropertyDateTimeList, IPropertyFilter Constants Constants (com.filenet.api.constants and FileNet.Api.Constants) provides classes defining collections of related, type-safe constant values. Examples include: Java and .NET: AccessRight, Cardinality, DatabaseType, PropertyNames, ReservationType Figure 3-1 on page 43 shows the relationship between key classes that are used for creating, storing, searching, and retrieving objects within the CE.
42
Factory Classes
ObjectStore
Document
Contains
Property Collection
Contains
SearchScope
IndependentObjectSet
Property
SearchSQL
RepositoryRow
Contains
After the connection has been made, assuming the application user is properly authenticated, the core objects (Connection, Domain, and ObjectStore) will be available for use.
Connection
A connection object tells the API how to connect to the CE server, primarily through the Uniform Resource Identifier (URI). The API then deduces both the method for connecting and the location of the CE from the URI. A connection object does not contain any user identification information. A connection is a lightweight API object that does not maintain any server state or tie up any server resources except when a server call is actually in progress.
43
Domain
A domain is an object holding IBM FileNet P8 resources at or above the object store level. These resources include: Object stores Fixed content devices Marking sets
ObjectStore
An object store is a collection of classes, objects, and metadata, and represents a logical division of data within a CE domain. Other objects can be retrieved directly from the object store or can be used with the Factory methods to create and retrieve objects such as: Documents Custom objects Folders Class and property definitions
Authentication in Java
For a Java application, the three primary methods for authenticating a user are: Container managed authentication A custom JAAS LoginModule that authenticates directly with the authentication provider The UserContext object with its pushSubject method For container-managed and LoginModule-based authentication, work with your application server provider or internal administration and development teams for the appropriate code. Although the ideal situation for authentication is either container-managed or LoginModule-based authentication, the Java API does provide a convenience method for authentication through the UserContext object. When doing a UserContext-based login, you create a Java Authentication and Authorization Service (JAAS) subject and push it onto the UserContext stack. After all CE-related operations are complete, you should pop the Subject back off the
44
stack. See Example 3-1 for how to create the subject, push it onto the UserContext, and then pop it off the stack.
Example 3-1 UserContext authentication in Java
Subject subject = UserContext.createSubject(connection, "username, "password", null); UserContext.get().pushSubject(subject); try { // do something } finally { UserContext.get().popSubject(); }
3.2.2 Java
Java offers two data transport layers: the native Enterprise JavaBeans (EJB) transport offered by the application server or the CE Web Services (CEWS) transport. The transport used is indicated by the CE server URI passed into the Connection object. Table 3-1 on page 46 shows examples of available CE connection URIs.
45
Note: For the Web services transport, the three endpoints are: FNCEWS40MTOM, FNCEWS40DIME, and FNCEWS40SOAP. The primary endpoint is MTOM. The other two endpoints, DIME and SOAP, exist for compatibility purposes only. All examples in this book use MTOM as the endpoint. For historical reasons, CEWS transport is sometimes referred to as Web Services Interface (WSI) transport or Web services transport. These are just naming differences and all refer to exactly the same thing. The CEWS transport is exactly the same set of Web services as would be used by someone calling CEWS directly (assuming that the persons uses a FNCEWS40* endpoint).
Table 3-1 Content Engine connection URIs Protocol Web Services EJB/WebSphere EJB/Weblogic EJB/JBoss URI http://server:port/wsi/FNCEWS40MTOM/ iiop://server:port/FileNet/Engine t3://server:port/FileNet/Engine jnp://server:port/FileNet/Engine
Getting an object store in Java consists of the following steps (see Example 3-3 on page 47 and Example 3-4 on page 47): 1. Get the connection object from Factory.Connection. 2. Create the Java Authentication and Authorization Service (JAAS) subject either by using UserContext.createSubject and pushing that subject into the UserContext, or by any way that creates a valid JAAS subject. 3. Get the domain object by using Factory.Domain.getInstance(). 4. Fetch the object store by using Factory.ObjectStore.fetchInstance(). Note: The main differences between CEWS and EJB when connecting are the URI and the JAAS stanza, as shown in bold in Example 3-3 and Example 3-4 on page 47.
46
Example 3-3 Getting the initial connection with Web services transport in Java
// Set the constants // Note: use /wsi/FNCEWS40MTOM/ for CEWS transport String uri = "http://ceserver:port/wsi/FNCEWS40MTOM/"; String username = "username"; String password = "password"; // Get the connection Connection conn = Factory.Connection.getConnection(uri); // Get the user context UserContext uc = UserContext.get(); // Build the subject using the FileNetP8WSI stanza // Use the FileNetP8WSI stanza for CEWS uc.pushSubject( UserContext.createSubject(conn,username,password,"FileNetP8WSI" ) ); try { // Get the default domain Domain domain = Factory.Domain.getInstance(conn, null); // Get an object store ObjectStore os = Factory.ObjectStore.fetchInstance(domain, "ObjectStoreName", null); } finally { uc.popSubject(); }
Example 3-4 Getting the initial connection with EJB transport in Java
the constants /FileNet/Engine for EJB uri = "http://ceserver:port/FileNet/Engine"; username = "username"; password = "password";
47
// Get the user context UserContext uc = UserContext.get(); // Build the subject using the FileNetP8 stanza // Use FileNetP8 for the EJB transport (also the default) uc.pushSubject( UserContext.createSubject(conn,username,password,"FileNetP8" ) ); try { // Get the default domain Domain domain = Factory.Domain.getInstance(conn, null); // Get an object store ObjectStore os = Factory.ObjectStore.fetchInstance(domain, "ObjectStoreName", null); } finally { // Pop the subject off the UserContext stack uc.popSubject(); } Note: There are other ways to handle authentication. All the API requires is a valid JAAS Subject. To use alternate authentication, work with your application server provider.
3.2.3 .NET
Unlike the Java API, the .NET API uses only the Web services transport for communicating with the CE. Making the initial connection to the CE and retrieving an object store involves the following steps: 1. 2. 3. 4. Create the UsernameToken for authentication. Pass the token to the UserContext. Get the domain using Factory.Domain.GetInstance(). Fetch the object store Factory.ObjectStore.FetchInstance().
Example 3-5 on page 49 is adapted from: ITSO.AutoRental.DataAccess.ContentEngineConnector.Connect() It shows the process of getting the initial connection, retrieving the domain, and retrieving an object store in C#.
48
public void Connect() { string uri = "http://ceserver:port/wsi/FNCEWS40MTOM/" string username = "username"; string password = "password"; // Create a security token using the username and password UsernameToken token = new UsernameToken(username, password, PasswordOption.SendPlainText); // Associate this UserContext with the whole process UserContext.SetProcessSecurityToken(token); // Now get the connection IConnection conn = Factory.Connection.GetConnection(uri); // Get the default domain _domain = Factory.Domain.GetInstance(conn, null); // Do the initial connection _os = Factory.ObjectStore.FetchInstance(_domain, objectStore, null); }
49
Example 3-6 and Example 3-7 on page 51 show an attempt to fetch an object and, in case of failure, attempt to create the object. This code has been adapted from the following method in the sample application Java code: RentalActivityHandler.getRentalNumber()
Example 3-6 Exception handling with Java
while (confirmationId == null) { try { Integer temp; if( createObject ) // Calls the create custom object code temp = createRentalNumber(dom,os); else // Fetches the custom object temp = getRentalNumber(os); confirmationId = temp; } catch( EngineRuntimeException ex) { ExceptionCode e = ex.getExceptionCode(); if( e == ExceptionCode.E_OBJECT_NOT_FOUND ) { // We can't find the requested object, so we should create it createObject = true; continue; } else if ( e == ExceptionCode.E_NOT_UNIQUE ) { // We tried creating an object and it's already there, use it createObject = false; continue; } // We hit an error we can't handle, so rethrow the exception throw ex; } }
50
int confirmationId = -1; bool createObject = false; while( confirmationId == -1 ) { try { int temp; if( createObject ) temp = CreateRentalNumber(dom,os); else temp = GetRentalNumber(os); confirmationId = temp; } catch( EngineRuntimeException ex) { ExceptionCode e = ex.GetExceptionCode(); if( e == ExceptionCode.E_OBJECT_NOT_FOUND ) { // We can't find the requested object, so we should create it createObject = true; continue; } else if ( e == ExceptionCode.E_NOT_UNIQUE ) { // We tried creating an object and it's already there, use it createObject = false; continue; } // We've hit an error we can't handle, so rethrow the exception throw ex; } }
51
52
Note: When creating objects, specifying the object ID for the object being created is possible by setting the value of the ID property. In addition, the ID class offers a method to create an IBM FileNet P8 object ID. Unless you have a specific reason for doing so, you should not explicitly specify the object ID. An ID will be created by the API or by the CE server.
Example 3-8 Creating objects in Java
CustomObject activity = Factory.CustomObject.createInstance(os, "ITSOIdleActivity"); // Property values are set here // Save the new IdleActivity activity.save(RefreshMode.NO_REFRESH);
Example 3-9 Creating objects in C#
ICustomObject activity = Factory.CustomObject.CreateInstance(os, "ITSOIdleActivity"); // Property values are set here // Save the new IdleActivity activity.Save(RefreshMode.NO_REFRESH);
53
Properties can also can be either single-valued or multi-valued, meaning the property can store either a single value or one or more values.
Object properties
Object-valued properties (OVP) work a bit differently than the other property types. For more information, see 4.3.1, Object-valued properties on page 94.
Properties collections
All CE objects have properties, or metadata, that describe that object. When an object has been retrieved with the API, these properties are stored locally in a properties collection. This collection holds property values for existing objects or stores new or updated values to be committed to the CE. The primary property collection classes are Properties for Java and IProperties for .NET and are typically accessed with the .getProperties() method in Java or the .Properties property in .NET. Although the properties collection can be iterated or enumerated, a more common approach is to access a given property directly through the .get(name) method or .Item[name] property, which returns a Property object that represents that property and its value (or values). Dynamically determining property type requires a cascade of instanceof in Java or is in .NET. Note: For clarity, the following code examples omit the save method call, so, as written, the examples would not commit any property changes.
54
// Get the properties collection Properties props = activity.getProperties(); // Get the start date Date start = new Date(System.currentTimeMillis()); // Set the properties props.putValue("ITSOStartDate", start); The .NET API works slightly different from the Java API. To set a single value property in .NET: 1. Create locally or retrieve the object. 2. Get the properties collection. 3. Set the value of the property by using the properties["propertyname"] convention. Note: For clarity, the following code examples omit the save method call, so, as written, the examples would not commit any property changes. Example 3-11 shows how to retrieve the properties of a document and to update the value of the ITSOStartDate property with the current date and time.
Example 3-11 Getting and setting properties in C#
// Get the properties collection for a Document IProperties properties = d.Properties; Property["ITSOStartDate"] = DateTime.Now;
55
// Get the properties collection for a Document Properties properties = document.getProperties(); // Create a multi-value integer list Integer32List list = Factory.Integer32List.createList(); list.add(100); list.add(212); // Add that to the properties for the document properties.putValue("MutliValuedIntProperty",list); To set a multi-valued property in .NET: 1. Create or retrieve the object. 2. Get the properties collection. 3. Create the value list. 4. Add the values. 5. Set the value of the property to be the list using the properties["name"] convention. See Example 3-13.
Example 3-13 Setting multi-valued property in C#
IProperties properties = d.Properties; // Create a multi-value integer list and add 2 values IInteger32List list = Factory.Integer32List.CreateList(); list.Add(100); list.Add(212); property["MultiValuedIntProperty"] = list;
56
Example 3-14 shows, using Java, how to retrieve the value of a single-valued string property, StringProperty, and a multi-valued ID property, RelatedIds.
Example 3-14 Retrieving property values from a CE object using Java
// Get the properties collection from a custom object Properties properties = o.getProperties(); // Get a string value and print to the console System.out.println( properties.getStringValue("StringProperty") ); // Get a multi-value ID property IdList ids = properties.getIdListValue("RelatedIds"); // Iterate through the list of values, printing them to the console for( Iterator i = ids.iterator(); i.hasNext(); ) { // Get the value and cast to an Id property type Id property = (Id)i.next(); // Print the value to the console System.out.println(property.toString()); } To retrieve property values in C#: 1. Retrieve the object. 2. Get the properties collection. 3. Get the value(s) using .Get<type>Value() or .Get<type>ValueList() (for example, GetStringValue or GetInt32ListValue()) Example 3-15 shows how to retrieve the value of a single-valued string property, StringProperty, and a multi-valued ID property, RelatedIds.
Example 3-15 Retrieving property values from a CE object using C#
// Get the properties for a custom object Properties properties = o.Properties; // Write out the string property value Console.WriteLine("Property value: " + properties.GetStringValue("StringProperty")); // Get a multi-valued ID property IIdList ids = properties.GetIdListValue("RelatedIds"); // Loop through the properties
57
for( IEnumerator i = ids.GetEnumerator(); i.MoveNext(); ) { // Cast the current property to an Id property Id property = (Id)i.Current; // Print out the value to the console Console.WriteLine(property.ToString()); }
58
Example 3-16 Fetching objects in Java // Retrieve document by path Document d1 = Factory.Document.fetchInstance(os,"/path/to/doc",null); // Retrieve document by ID Document d2 = Factory.Document.fetchInstance(os, new Id("{C6E0130B-F679-4244-9269-CCA073AE31C9}"),null); // Retrieve folder by path Folder f1 = Factory.Folder.fetchInstance(os,"/path/to/folder",null); // Retrieve folder by ID Folder f2 = Factory.Folder.fetchInstance(os, new Id("{C6E0130B-F679-4244-9269-CCA073AE31C9}"),null); // Retrieve custom object by path CustomObject o1 = Factory.CustomObject.fetchInstance(os,"/path/to/object", null); // Retrieve custom object by ID CustomObject o2 = Factory.CustomObject.fetchInstance(os, new Id("{C6E0130B-F679-4244-9269-CCA073AE31C9}"),null); Example 3-17 Fetching objects in C# // Retrieve by path IDocument d1 = Factory.Document.FetchInstance(os,"/path/to/doc",null); // Retrieve by ID IDocument d2 = Factory.Document.FetchInstance(os, new Id("{C6E0130B-F679-4244-9269-CCA073AE31C9}"),null); // Retrieve by path IFolder f1 = Factory.Folder.FetchInstance(os, "/path/to/folder", null); // Retrieve by ID IFolder f2 = Factory.Folder.FetchInstance(os, new Id("{C6E0130B-F679-4244-9269-CCA073AE31C9}"),null); // Retrieve by path ICustomObject o1 = Factory.CustomObject.FetchInstance(os, "/path/to/object", null); // Retrieve by ID ICustomObject o2 = Factory.CustomObject.FetchInstance(os, new Id("{C6E0130B-F679-4244-9269-CCA073AE31C9}"),null);
59
// Get the object Document doc = Factory.Document.getInstance(os,"Document","/Doc"); // Mark the document for deletion locally doc.delete(); // Perform the delete doc.save(Refresh.NO_REFRESH); // Get the folder for deletion Folder folder = Factory.Folder.getInstance(os,"Folder","/Folder"); // Prepare the folder for deletion f.delete(); // Commit the delete f.save(RefreshMode.NO_REFRESH); // Get the object CustomObject o = Factory.CustomObject.getInstance(os,"CustomObject","/Object");
60
// Prepare the object for deletion o.delete(); // Commit the deletion o.save(RefreshMode.NO_REFRESH);
Example 3-19 Deleting objects in C#
// Get the object IDocument doc = Factory.Document.GetInstance(os,"Document","/Doc"); // Mark the document for deletion locally doc.Delete(); // Perform the delete doc.Save(RefreshMode.NO_REFRESH); // Get the folder for deletion IFolder folder = Factory.Folder.GetInstance(os,"Folder","/Folder"); // Prepare the folder for deletion f.Delete(); // Commit the delete f.Save(RefreshMode.NO_REFRESH); // Get the object ICustomObject o = Factory.CustomObject.GetInstance(os,"CustomObject","/Object"); // Prepare the object for deletion o.Delete(); // Commit the deletion o.Save(RefreshMode.NO_REFRESH);
61
Finally, the CE stores a few metadata items for each content element attached, stored as a ContentTransfer. This metadata includes: Content size: Numerical size in bytes for the content element Content type: Content type of the element in MIME format Retrieval name: Optional property that indicates the original file name of the element Element sequence number: Ordered index for the content element indicating which element it is See Using ContentElement objects on page 63 for details about using ContentElement objects.
InputStream stream = document.accessContentStream(0); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String text = "", line; while ((line = reader.readLine()) != null) text += line; reader.close();
62
Stream stream = document.AccessContentStream(0); TextReader reader = new StreamReader(stream); string text = "", line; while ((line = reader.ReadLine()) != null) text += line; reader.Close();
public static void main(String[] args) { // Authentication and connection goes here (left out for space) // Retrieve the document Document d = Factory.Document.fetchInstance(os,"/document",null); // Get the content elements ContentElementList elements = d.get_ContentElements(); // Grab the first content element ContentTransfer element = (ContentTransfer)elements.get(0); String filename = element.get_RetrievalName(); InputStream stream = element.accessContentStream();
63
Double size = writeContent(stream,filename); Double expected = element.get_ContentSize() if( size != expected ) System.err.println("Invalid content size retrieved"); d = Factory.Document.fetchInstance("/document2",null); elements = d.get_ContentElements(); for( Iterator i = elements.iterator(); i.hasNext(); ) { element = (ContentTransfer)i.next(); writeContent( element.accessContentStream(), "element" + element.get_ElementSequenceNumber() ); } } public static Double writeContent(InputStream s, String filename) throws IOException { // Open a buffered output stream to write the content to // a file named the same as the retrieval name BufferedOutputStream writer = new BufferedOutputStream( new FileOutputStream(filename) ); Double size = new Double(0); int bufferSize; byte[] buffer = new byte[1024]; // Loop through the content and write it to the system while( ( bufferSize = s.read(buffer) ) != -1 ) { size += bufferSize; writer.write(buffer, 0, bufferSize); } writer.close(); s.close(); return size; }
64
static void Main(string[] args) { // Authenticate and connect (left out for space) // Retrieve the document IDocument d = Factory.Document.FetchInstance(os,"/document", null); // Get the content elements IContentElementList elements = d.ContentElements; // Grab the first content element IContentTransfer element = (IContentTransfer)elements[0]; // Grab the retrieval name string filename = element.RetrievalName; // Get the content stream Stream stream = element.AccessContentStream(); // Write the content and compare the size expected double size = writeContent(stream,filename); if( size != element.ContentSize ) Console.Error.WriteLine("Invalid content size retrieved"); // Fetch second document d = Factory.Document.FetchInstance(os,"/document2",null); // Grab the content elements elements = d.ContentElements; // Iterate through each element and write the content for( IEnumerator i = elements.GetEnumerator(); i.MoveNext(); ) { element = (IContentTransfer)i.Current; writeContent( element.AccessContentStream(), "element" + element.ElementSequenceNumber ); } } // Convenience method that writes the content to the given file
65
public static double writeContent(Stream stream, String filename) { byte[] buffer = new byte[4096]; int bufferSize; double size = 0; // Open a binary writer for the stream BinaryWriter writer = new BinaryWriter( File.Open(filename, FileMode.Create)); // Write the content while ((bufferSize = stream.Read(buffer, 0, buffer.Length)) != 0) { size += bufferSize; writer.Write(buffer, 0, bufferSize); } // Close the streams writer.Close(); stream.Close(); return size; }
66
To limit data returned using property filters: 1. Directly fetch the properties using the .fetchProperties() (Java) or .FetchProperties() (.NET) methods. 2. Create a PropertyFilter object. 3. Set the include and exclude properties. 4. Set the recursion to determine how far to follow object properties. 5. Pass the object to a .fetchInstance() (Java) or .FetchInstance() (.NET) call. Note: Trying to use a property that has not been retrieved will result in an exception. If you do not use property filters, the API generally manages the retrieval of additional properties. This process avoids the exceptions but can cost extra round-trips to the server. When you use a property filter, you get explicit control over the presence or absence of all properties. Example 3-24 and Example 3-25 on page 68 show how to use property filters to control which properties are retrieved when fetching a document and fetching a documents properties.
Example 3-24 Limiting properties returned using property filters in Java
// Get the document Document d = Factory.Document.getInstance(os, "Document", "/Doc1"); // Fetch properties DocumentTitle and DateCreated d.fetchProperties(new String[] { "DocumentTitle", "DateCreated" }); // Write out the Document Title System.out.println(d.getProperties().getStringValue("DocumentTitle")); // Write out the Creator (throws EngineRuntimeException) //System.out.println(d.getProperties().getStringValue("Creator")); // Same result using PropertyFilter PropertyFilter filter = new PropertyFilter(); filter.addIncludeProperty( new FilterElement(null, null, null, "DocumentTitle DateCreated")); // Calling fetch instance instead of getInstance d = Factory.Document.fetchInstance(os, "/Doc2", filter);
67
// Retrieve the document IDocument d = Factory.Document.GetInstance(os, "Document", "/Doc1"); // Fetch Document Title and Date Created d.FetchProperties(new string[] { "DocumentTitle", "DateCreated" }); // Write out the DocumentTitle (works) Console.WriteLine(d.Properties.GetStringValue("DocumentTitle")); // Write out the Creator (throws EngineRuntimeException) //Console.WriteLine(d.Properties.GetStringValue("Creator")); // Same result using PropertyFilter PropertyFilter filter = new PropertyFilter(); filter.AddIncludeProperty( new FilterElement(null, null, null, "DocumentTitle DateCreated")); // Calling fetch instance instead of get instance d = Factory.Document.FetchInstance(os, "/Doc2", filter);
68
SearchSQL sql = new SearchSQL( "select " + "ITSOCustomer, ITSOStartDate, ITSOEndDate, ITSOChargesNet," + "ITSOChargesTotal, ITSORentalAgreement ITSOVehicle," + "ITSODailyRate, ITSOConfirmationId " "from " + "ITSORentalActivity " + "where " + "ITSOConfirmationId = " + identifier); // Search the instantiated object store SearchScope scope = new SearchScope(os); // Create a property filter object PropertyFilter filters = new PropertyFilter(); filters.addIncludeProperty(2, null, null, "ContentElements Containees ITSOVehicleId ITSOVehicleYear " + "ITSOVehicleMake ITSOVehicleColor ITSOCustomerName"); IndependentObjectSet set = scope.fetchObjects(sql, 1, filters, false);
Example 3-27 Property filters in .NET
SearchSQL sql = new SearchSQL( "select " + "ITSOCustomer, ITSOStartDate, ITSOEndDate, ITSOChargesNet," + "ITSOChargesTotal, ITSORentalAgreement ITSOVehicle," + "ITSODailyRate, ITSOConfirmationId " + "from " + "ITSORentalActivity " + "where " + "ITSOConfirmationId = " + identifier); SearchScope scope = new SearchScope(_os); PropertyFilter filters = new PropertyFilter(); filters.AddIncludeProperty(2, null, null, "ContentElements Containees ITSOVehicleId ITSOVehicleYear " + "ITSOVehicleMake ITSOVehicleColor ITSOCustomerName"); IIndependentObjectSet set = scope.FetchObjects(sql, 1, filters, false);
69
Without property filters, the operation in the examples would require four round-trip calls to the CE, as follows: Execute the search and retrieve the ITSORentalActivity custom object. Retrieve the ITSOVehicle folder properties. Retrieve the ITSORentalAgreement properties. Retrieve the ITSOCustomer properties. Using the code examples, the total number of round-trips to the CE is reduced from four to one. Figure 3-2 shows the objects and properties that are returned from the code in the examples.
ITSORentalActivity ITSOCustomer ITSOStartDate ITSOEndDate ITSOChargesNet ITSOChargesTotal {4B608AFB-E6EA-4e76-A2CB-71543EAE5789} 2009-11-11 09:00:00 2009-12-12 09:00:00 100000 120000 ITSOCustomer Id ITSOUserId ITSOCustomerName ITSORentalAgreement Id ContentElements DocumentTitle ITSOVehicle Id ITSOVehicleID ITSOVehicleYear ITSOVehicleMake ITSOVehicleModel ITSOVehicleColor Containees FolderName {C4D27FCE-13A7-405c-8BDD-7EF09FB67251} 1F786HH76DCC1 1975 Dacia 1310 Blue {E407D1FC-EF11-48bc-A977-55DF8A9A9B60} <not retrieved> {35F89870-64A4-4e75-A71B-596E7215473F} Agreement.txt <not retrieved> {4B608AFB-E6EA-4e76-A2CB-71543EAE5789} <not retrieved> John Q. Renter
70
A getInstance() call is useful for batching, or for calls where the properties are not necessary, just the action upon the object (such as deleting an object). Because there is no initial round trip to the server to fetch the object, this is also called fetchless instantiation.
3.6 Querying
When developing for the CE, one of the primary ways of finding documents is to do a search, based on data from a user. Workplace and WorkplaceXT both offer search templates and stored searches that a user can execute. When you program, doing the search directly in code by using the SearchScope and SearchSQL classes is necessary. Searching the CE requires the following steps: 1. 2. 3. 4. Create the SQL statement. Set the SearchScope. Execute the search. Work with the results.
71
3.6.1 SearchSQL
The CE offers a language for executing queries within single or multiple object stores. The SearchSQL class offers helper methods to assist you in constructing a SQL statement, or the SQL statement can be constructed independently and passed to a SearchSQL instance as a string. SQL statements must follow the CE SQL syntax, which generally conforms to SQL-92, with extensions for FileNet-specific constructs. The complete SQL syntax guide is available in the IBM FileNet P8 Platform documentation by selecting ECM Help Developer Help Content Engine Development Reference SQL Syntax Descriptions.
SearchSQL sqlObject = new SearchSQL("SELECT DocumentTitle, Id FROM Document WHERE Creator = 'jsmith'");
Example 3-29 Building a query with SearchSQL in C#
SearchSQL sqlObject = new SearchSQL("SELECT DocumentTitle, Id FROM Document WHERE Creator = 'jsmith'"); Note: The helper methods on SearchSQL and a SearchSQL object that are instantiated with a SQL statement are mutually-exclusive. The SQL passed in (on creation) cannot be updated with the convenience methods. Experienced developers typically find that supplying the SQL as a string is the simpler approach.
72
3. Select new search. 4. Build the search in the Content Engine Query Builder. 5. Select View SQL View. Figure 3-3 shows how to use the Enterprise Managers Content Engine Query Builder to create the search SQL for use in a SearchSQL object.
Figure 3-3 Compiled SQL statement from Content Engine Query Builder
// Construct the sql statement SearchSQL sql = new SearchSQL( "select ISTOStartDate, ITSOEndDate, ITSOVehicle " + "from ITSOIdleActivity " + "where + "ITSOVehicle = OBJECT('{D5DC8C04-2625-496f-A280-D791AFE87A73}') " + "AND ITSOStartDate < 20090801T000000Z OR " + "ITSOEndDate > 20090701T000000Z" ); // Search the object store with the sql and get the returned items SearchScope scope = new SearchScope(os);
73
IndependentObjectSet set = scope.fetchObjects(sql, null, null, false); // Loop through the returned results for( Iterator i = set.iterator(); i.hasNext(); ) { // Get the document CustomObject obj = (CustomObject)i.next(); // Code to work with object goes here }
Example 3-31 Search example in C#
// Construct the sql statement SearchSQL sql = new SearchSQL( "select ITSOStartDate, ITSOEndDate, ITSOVehicle " + "from ITSOIdleActivity " + "where " + "ITSOVehicle = OBJECT('{D5DC8C04-2625-496f-A280-D791AFE87A73}') " + "AND ITSOStartDate < 20090801T000000Z OR " + "ITSOEndDate > 20090701T000000Z" ); // Search the object store with the sql and get the returned items SearchScope scope = new SearchScope(os); IIndependentObjectSet set = scope.FetchObjects(sql, null, null, false); IEnumerator e = set.GetEnumerator(); while(e.MoveNext()) { // Get the current object ICustomObject obj = (ICustomObject)e.Current; // Code to work with object goes here }
74
The SearchScope methods execute the SQL statement on one or more object stores to find objects (IndependentObject instances), database rows (RepositoryRow instances), or metadata (ClassDescription instances). If the query includes a JOIN operator, you must fetch rows instead of objects.
// Create the object store array ObjectStore[] osArray = new ObjectStore[]{os1,os2}; // Create the search scope SearchScope objStores = new SearchScope(osArray, MergeMode.INTERSECTION);
75
// Create the object store array IObjectStore[] osArray = new IObjectStore[] { os1, os2 }; // Create the search scope SearchScope objStores = new SearchScope(osArray, MergeMode.INTERSECTION);
76
Example 3-34 Paging in Java // A query that will return a large result set SearchSQL sql = new SearchSQL("select [DocumentTitle] from document"); SearchScope scope = new SearchScope(os); // Set the paging to be 50 items per page and enable continuation IndependentObjectSet s = scope.fetchObjects(sql, 50, null, true); // Get the page iterator PageIterator p = s.pageIterator(); // Loop through each page while(p.nextPage()) { // Loop through each item in the page for(Object obj : p.getCurrentPage()) { // Get the document object and write Document Title Document doc = (Document)obj; System.out.println( doc.getProperties().getStringValue("DocumentTitle")); } } Example 3-35 Paging in C# SearchSQL sql = new SearchSQL("select [DocumentTitle] from document"); SearchScope scope = new SearchScope(os); IIndependentObjectSet s = scope.FetchObjects(sql, 50, null, true); IPageEnumerator p = s.GetPageEnumerator(); while(p.NextPage()) { Console.WriteLine(p.ElementCount); foreach(object obj in p.CurrentPage ) { IDocument doc = (IDocument)obj; Console.WriteLine( doc.Properties.GetStringValue("DocumentTitle")); } }
77
// Call WorkplaceXTs setCredentials servlet to obtain user token URL url = new URL(baseP8URL + "setCredentials?op=getUserToken&userId=" + user + "&password=" + password + "&verify=true"); HttpURLConnection p8con = (HttpURLConnection) url.openConnection(); p8con.setRequestMethod("POST"); p8con.connect(); InputStream in = p8con.getInputStream(); int c = -1; String tempUserToken = ""; while ( (c=in.read()) >= 0) tempUserToken += new Character((char)c).toString();
78
String userToken = URLEncoder.encode(tempUserToken, "UTF-8"); // Build URL to getContent servlet String contentUrl = baseP8URL + "getContent?objectStoreName=" + objectStore + "&id=" + docID + "&objectType=document&ut=" + userToken + "&impersonate=true"; %> <script language="javascript"> window.top.location="<%=contentUrl%>" </script>
</body> </html> Example 3-37 Document viewing in C# and ASP.NET using System.Net; using System.IO; public partial class _Default : System.Web.UI.Page { public string WorkplaceRootUrl = ""; public string ContentUrl = ""; public string Username = ""; private void Page_Load(object sender, System.EventArgs e) { // set constant values // replace these values with values applicable to your site WorkplaceRootUrl = "http://aeServer:9080/WorkplaceXT/"; Username = "user"; string pwd = "password"; string objectStoreName = "ObjectStoreName"; string Id = "{C9712786-4B17-4512-9E13-9F4154B35FC2}";
// Call WorkplaceXTs setCredentials servlet to obtain user token string UserToken = getCEUserToken(WorkplaceRootUrl, Username, pwd); // create URLs for the JavaViewer ContentUrl = WorkplaceRootUrl + "getContent?objectStoreName=" + objectStoreName + "&id=" + Id + "&objectType=document&ut=" + UserToken + "&impersonate=true"; }
79
private string getCEUserToken(string baseURL, string uid, string pwd) { string UserToken = ""; // make the request and get the response WebRequest request = WebRequest.Create(baseURL + "setCredentials?op=getUserToken&userId=" + uid + "&password=" + pwd + "&verify=true"); request.Method = "POST"; WebResponse response = request.GetResponse(); // read the response from the stream into a byte[] Stream stream = response.GetResponseStream(); byte[] token = new byte[response.ContentLength]; stream.Read(token, 0, (int)response.ContentLength); response.Close(); // and convert the bytes in the array into a string. foreach (byte chr in token) UserToken += System.Convert.ToChar(chr); // return the encoded string return Server.UrlEncode(UserToken); } }
// Below is the aspx page source <html> <body> <script language="javascript"> window.top.location="<%=ContentUrl%>" </script> </body> </html>
80
User tokens can also be obtained in other ways and are described in detail in ECM Help Developer Help Workplace Development Workplace Customization Guide User Tokens.
81
Selecting the right mode can affect performance of operations or the work unit as a whole. For example, when committing a group of documents to the CE, you might only want to know whether the commit failed or is successful. So doing a refresh in this situation is not necessary, and would cause the entire operation to be slower. However, if the code has to work with the committed object, doing a refresh on commit operation can save a round-trip to the CE to fetch any updated properties (such as the ID of a newly created object).
Batch updates
You can perform bulk updating of objects in a batch by using UpdatingBatch. To update objects in batch: 1. Create the UpdatingBatch. 2. Retrieve the objects to update. 3. Apply the changes to the local objects (but do not .save() the changes). 4. Add the objects to the batch. 5. Update the batch. Example 3-38 and Example 3-39 on page 83, adapted from RentalActivityHandler.insertVehicleActivity, show how to update an existing object and create a second object in a single batch operation.
Example 3-38 Creating a batch of update actions in Java
// Get the IdleActivity record (from a previous search) CustomObject previous = (CustomObject)set.iterator().next(); // Create the next custom object CustomObject next = Factory.CustomObject.createInstance(os,"ITSOIdleActivity"); // Set the properties Properties props = next.getProperties(); props.putValue("ITSOVehicle", vehicle); props.putValue("ITSOStartDate", end); // Update the previous object previous.getProperties().putValue("ITSOEndDate", start); // Create the batch UpdatingBatch batch = UpdatingBatch.createUpdatingBatchInstance(domain,
82
RefreshMode.REFRESH); // Add the objects batch.add(previous, null); batch.add(next, null); // Execute the batch batch.updateBatch();
Example 3-39 Creating a batch of update actions in C#
// Get the IdleActivity record (from a previous search) ICustomObject previous = (ICustomObject)getPrevious(); // Create the next custom object ICustomObject next = Factory.CustomObject.CreateInstance(_os, "ITSOIdleActivity"); // Create the batch UpdatingBatch batch = UpdatingBatch.CreateUpdatingBatchInstance(domain, RefreshMode.REFRESH); // Add the objects batch.Add(previous, null); batch.Add(next, null); // Execute the batch batch.UpdateBatch();
Batch retrieval
In addition to bulk creating and updating objects, batches can also be used to retrieve objects in bulk. Using RetrievingBatch can help limit the number of round-trips to the CE, increasing performance, and reducing network traffic. To retrieve items in a batch: 1. Create the RetrievingBatch. 2. Instantiate the objects to be retrieved. 3. Add them to the batch. 4. Retrieve the batch. 5. Work with the returned item(s).
83
Example 3-40 and Example 3-41 show how to retrieve two documents in a batch using RetrievingBatch.
Example 3-40 Batch retrieval in Java
RetrievingBatch rb = RetrievingBatch.createRetrievingBatchInstance(domain); Folder vehicle = Factory.Folder.getInstance(os, "ITSOVehicle", vehiclePath); PropertyFilter filter = new PropertyFilter(); filter.addIncludeProperty(0, null, null, PropertyNames.ID + " " + PropertyNames.NAME + " " + "ITSODailyRate ITSOFranchiseCode" ); rb.add(vehicle, filter); Document doc = Factory.Document.getInstance(os, "ITSODocument", path); filter = new PropertyFilter(); filter.addIncludeProperty(0, null, null, PropertyNames.ID + " ITSOFranchiseCode"); rb.add(doc, filter); rb.retrieveBatch();
Example 3-41 Batch retrieval in C#
RetrievingBatch rb = RetrievingBatch.CreateRetrievingBatchInstance(domain); IFolder vehicle = Factory.Folder.GetInstance(os, "ITSOVehicle", vehiclePath); PropertyFilter filter = new PropertyFilter(); filter.AddIncludeProperty(0, null, null, PropertyNames.ID + " " + PropertyNames.NAME + " " + "ITSODailyRate ITSOFranchiseCode"); rb.Add(vehicle, filter);
84
IDocument doc = Factory.Document.GetInstance(_os, "ITSODocument", path); filter = new PropertyFilter(); filter.AddIncludeProperty(0, null, null, PropertyNames.ID + " ITSOFranchiseCode"); rb.Add(doc, filter); rb.RetrieveBatch();
85
86
Chapter 4.
87
/** * Removes the AccessRight.DELETE right from all direct ACEs for an * object. Caller must have fetched the Permissions property. * Return true if we actually changed anything. Caller must call save. */ public boolean removeDeletePerm(IndependentlyPersistableObject ipo) { boolean madeChanges = false; Properties props = ipo.getProperties(); if (!props.isPropertyPresent(PropertyNames.PERMISSIONS)) { return madeChanges; } AccessPermissionList acl =
88
(AccessPermissionList)props.getDependentObjectListValue( PropertyNames.PERMISSIONS); for (Iterator it = acl.iterator(); it.hasNext();) { AccessPermission ace = (AccessPermission)it.next(); PermissionSource acePS = ace.get_PermissionSource(); // Skip any inherited ACEs if (acePS == PermissionSource.SOURCE_PARENT) continue; int rights = ace.get_AccessMask().intValue(); if ((rights & AccessRight.DELETE_AS_INT) != 0) { madeChanges = true; // Remove the DELETE bit. rights &= ~AccessRight.DELETE_AS_INT; ace.set_AccessMask(rights); } } return madeChanges; }
Example 4-2 AccessPermissionList manipulation in C#
/** * Removes the AccessRight.DELETE right from all direct ACEs for an * object. Caller must have fetched the Permissions property. * Return true if we actually changed anything. Caller must call save. */ public Boolean RemoveDeletePerm(IIndependentlyPersistableObject ipo) { Boolean madeChanges = false; IProperties props = ipo.Properties; if (!props.IsPropertyPresent(PropertyNames.PERMISSIONS)) { return madeChanges; } IAccessPermissionList acl = (IAccessPermissionList)props[PropertyNames.PERMISSIONS]; foreach (IAccessPermission ace in acl) { PermissionSource acePS = ace.PermissionSource; // Skip any inherited ACEs if (acePS == PermissionSource.SOURCE_PARENT) continue; int rights = (int)ace.AccessMask; if ((rights & (int)AccessRight.DELETE) != 0) {
89
madeChanges = true; // Remove the DELETE bit. rights &= ~((int)AccessRight.DELETE); ace.AccessMask = rights; } } return madeChanges; }
4.2 Versioning
One of the fundamentals of traditional document management, the forerunner of modern enterprise content management, is that documents change over time. Rather than simply replacing the content as a whole, IBM FileNet Content Manager allows you to make a completely new version of the document, thereby preserving the older versions of the content. A Document object in CE represents a single version of what you might think of as a document (for example, a spreadsheet, a text file, or a photograph). The collection of all versions of a given document is represented in CE by a VersionSeries object. Each version in a VersionSeries object has its own security, life cycle, and other characteristics as an independently persistable object. The latest version of a document in a VersionSeries is called the current version and is pointed to by the CurrentVersion property. There is a two-level version numbering scheme (major and minor versions). The latest major version in a VersionSeries is called the released version and is pointed to by the ReleasedVersion property. A checked-in document can also be promoted to a major version or demoted to a minor version. Figure 4-1 on page 91 illustrates a VersionSeries object with multiple independent objects. Version 1.0 and 1.1 are superseded. Version 2.0 is the current official release. Version 2.1 is a checked-out version of 2.0 with a reservation state.
90
Version Series
To create a new version of a document, perform a check-out and check-in cycle: 1. Check out the current version of the document. This creates a new reservation document version. A reservation is not a different type of object. It is merely a new document version marked as being in the reservation state. The immediately previous version is in the reserved state. Properties may be automatically copied from the current version to the reserved version, depending on the value of the PropertyDescription boolean CopyToReservation metaproperty. 2. Make content changes and possibly property changes. 3. Check in the reserved document version. If you change your mind and want to cancel the check-out step, you can call the cancelCheckout helper method or simply delete the reserved document version (these are exactly the same operation). Content can only be updated on a document object that is in the reserved state. You can update content as many times as you want, with new content completely replacing the old content for that reserved version. After you perform the check-in step, the content for that version becomes immutable. (Properties for document versions can be changed at any time. Locking out property changes for a particular document version is possible by calling the freeze method.)
91
Within a given version series, individual independent versions can be deleted and removed from the version series by instantiating a specific document object and calling its delete method. Deleting the entire version series requires instantiating the VersionSeries object and calling its delete method. The instantiation of the VersionSeries can be done by using a Factory.VersionSeries method or by getting the value of the VersionSeries property from any of the documents in the version series. Example 4-3 and Example 4-4 on page 93 show how to retrieve a document, check it out, add content, and check the document back in as major version.
Example 4-3 Check-out and check-in cycle in Java // Get the document (saving a round-trip that a fetch would require) Document doc = Factory.Document.getInstance(os,"Document","/Doc1"); // Checkout the document and save doc.checkout(ReservationType.EXCLUSIVE, null, null, null); doc.save(RefreshMode.REFRESH); // Get the reservation object Document res = (Document)doc.get_Reservation(); // Update the properties res.getProperties().putValue("DocumentTitle","NextVersion"); // Prepare the content for attaching // Create the element list ContentElementList list = Factory.ContentElement.createList(); // Create a content transfer element by attaching a simple text file ContentTransfer element = Factory.ContentTransfer.createInstance(); // Set the MIME type element.set_ContentType("text/plain"); // Set the retrieval name element.set_RetrievalName("file.txt"); // Set the content source element.setCaptureSource(new FileInputStream(new File("file.txt"))); // Add the item to the list list.add(element); // Add the content transfer list to the document res.set_ContentElements(list); // Set the PendingAction to be check-in as a major version without
92
// automatic content classification res.checkin(AutoClassify.DO_NOT_AUTO_CLASSIFY, CheckinType.MAJOR_VERSION); // Save the document to the repository res.save(RefreshMode.NO_REFRESH); Example 4-4 Check-out and check-in cycle in C# // Get the document (saving a round-trip that a fetch would require) IDocument doc = Factory.Document.GetInstance(os,"Document","/Doc1"); // Checkout the document and save doc.Checkout(ReservationType.EXCLUSIVE, null, null, null); doc.Save(RefreshMode.REFRESH); // Get the reservation object IDocument res = (IDocument)doc.Reservation; // Update the properties IProperties properties = res.Properties; // Set the value properties["DocumentTitle"] = "NewVersion"; // Create the content element list IContentTransferList l = Factory.ContentTransfer.CreateList(); // Create the content element IContentTransfer element = Factory.ContentTransfer.CreateInstance(); element.RetrievalName = "file.txt"; element.ContentType = "text/plain"; element.SetCaptureSource( System.IO.File.Open("file.txt", FileMode.Open)); l.Add(element); // Add the elements to the object res.ContentElements = l; // Set the check-in type res.Checkin(AutoClassify.DO_NOT_AUTO_CLASSIFY, CheckinType.MAJOR_VERSION); // Commit the changes to the CE res.Save(RefreshMode.NO_REFRESH);
93
4.3 Relationships
The CE APIs and the CE server itself have many features which emulate features of modern object-oriented programming languages. One of those features is the ability to create explicit relationships between objects. In most cases, the server perform referential integrity checks based on those relationships.
94
/* Folder vehicle = ... */ // Create the ITSOIdleActivity object CustomObject activity = Factory.CustomObject.createInstance(os, "ITSOIdleActivity"); // Get the properties collection Properties props = activity.getProperties(); // Set the properties props.putValue("ITSOFranchiseCode", vehicle.getProperties().getStringValue("ITSOFranchiseCode")); props.putObjectValue("ITSOVehicle", vehicle); // Save the new IdleActivity activity.save(RefreshMode.NO_REFRESH);
Example 4-6 OVP manipulation in C#
/* IFolder vehicle = ... */ // Create the ITSOIdleActivity object ICustomObject activity = Factory.CustomObject.CreateInstance(os, "ITSOIdleActivity"); // Get the properties collection IProperties props = activity.Properties; // Set the properties props["ITSOFranchiseCode"] = vehicle.getProperties().getStringValue("ITSOFranchiseCode"); props["ITSOVehicle"] = vehicle; // Save the new IdleActivity activity.Save(RefreshMode.NO_REFRESH);
95
It is either of the following objects: ReferentialContainmentRelationship (RCR) object DynamicReferentialContainmentRelationship (DRCR) object Both RCR and DRCR are extensible. The relationship object, being an intermediary, enables a folder to contain many objects and an object to be contained in many folders. In fact, a given object may be contained more than once in the same folder. The RCR (and DRCR) Head property is reflected by containees Containers property. The RCR Tail property is reflected by the folder Containees property. To understand the nomenclature of head and tail, imagine arrows pointing from the folder to the various containees. The RCR properties give you the tails and heads of those arrows. Imagine the RCR object as a single marker of sorts in the middle of each arrow. The APIs provide convenience methods for filing and unfiling objects. They are convenience methods because they do not represent fundamental operations and are instead built upon creation or deletion of RCR or DRCR objects. Newcomers to the APIs generally find the convenience methods easier to understand, but developers experienced in the APIs generally find direct creation and manipulation of the RCR and DRCR objects much clearer. The difference in terms of lines of code is very small. Example 4-7 and Example 4-8 on page 97 show a sample of filing, adapted from RentalActivityHandler.java in the sample application. Because it happens to be filing a CustomObject, the sample uses RCR. For filing a document object, you want to use DRCR unless you have a very specific use case for using RCR.
Example 4-7 Filing a document to a folder in Java
Document d = Factory.Document.getInstance(os, "Document", "/Document"); Folder f = Factory.Folder.getInstance(os, "Folder", "/Folder"); ReferentialContainmentRelationship rcr = Factory.ReferentialContainmentRelationship.createInstance(os, ClassNames.DYNAMIC_REFERENTIAL_CONTAINMENT_RELATIONSHIP); rcr.set_Head(d); rcr.set_Tail(f); rcr.save(RefreshMode.NO_REFRESH);
96
IDocument d = Factory.Document.GetInstance(os, "Document", "/Document"); IFolder f = Factory.Folder.GetInstance(os, "Folder", "/Folder"); IReferentialContainmentRelationship rcr = Factory.ReferentialContainmentRelationship.CreateInstance(os, ClassNames.DYNAMIC_REFERENTIAL_CONTAINMENT_RELATIONSHIP); rcr.Head = d; rcr.Tail = f; rcr.Save(RefreshMode.NO_REFRESH);
97
/** * Count the total number of children and parent documents */ public int childrenAndParents(Document doc) { System.out.println("document: " + doc); int childCount = 0; // Treat this doc as a parent and count its children if (doc.get_CompoundDocumentState() == CompoundDocumentState.COMPOUND_DOCUMENT) { // Could get_ChildRelationships instead. DocumentSet children = doc.get_ChildDocuments(); for (Iterator it = children.iterator(); it.hasNext();) { Document child = (Document)it.next(); System.out.println("child: " + child); ++childCount; } } int parentCount = 0; // Any document can be a child, so always count parents. // Could get_ParentRelationships instead. DocumentSet parents = doc.get_ParentDocuments(); for (Iterator it = parents.iterator(); it.hasNext();) { Document parent = (Document)it.next(); System.out.println("parent: " + parent); ++parentCount; } return childCount + parentCount; }
Example 4-10 Compound documents in C#
/// <summary> /// Count the total number of children and parent documents /// </summary> public int ChildrenAndParents(Document doc) { Console.WriteLine("document: " + doc); int childCount = 0; // Treat this doc as a parent and count its children
98
if (doc.CompoundDocumentState == CompoundDocumentState.COMPOUND_DOCUMENT) { // Could use ChildRelationships instead. IDocumentSet children = doc.ChildDocuments; foreach (IDocument child in children) { Console.WriteLine("child: " + child); ++childCount; } } int parentCount = 0; // Any document can be a child, so always count parents. // Could use ParentRelationships instead. IDocumentSet parents = doc.ParentDocuments; foreach (IDocument parent in parents) { Console.WriteLine("parent: " + parent); ++parentCount; } return childCount + parentCount; }
4.4 Annotations
An annotation, as its name implies, is some kind of additional information associated with an object. For example, you can think of using a pen to physically mark up a photograph or to add review comments to a document. Although one typically thinks of an annotation as being graphically overlaid on the annotated object, there is no requirement for that to be so. The non-versionable Annotation class may contain content elements. It can also be made into a subclass, so any desired custom properties may be added to it. The specific subclass type can be used to distinguish among different annotation types on an object. The CE annotation feature provides relationships and convenient default security and other behaviors for annotation objects. Documents, folders, and custom objects may have associated annotations. For Documents, the Annotation property AnnotatedContentElement provides the opportunity to affiliate an annotation with a specific content element. When you do that, using the invariant content element ElementSequenceNumber to make that association is better than using the volatile position number of the content element within a Documents content elements collection.
99
An annotation can be for any purpose that an application developer feels is appropriate. The Application Engines Java viewer applet has its own specific implementation of annotations, but the formats of those annotations are subject to change at any time without notice. Annotations may also be carried over from Image Services with Content Federation Services for Image Services (CFS-IS). Example 4-11 and Example 4-12 on page 101 illustrate the creation of a custom annotation and associating it with a specific Document content element. The custom properties are adapted from the sample application.
Example 4-11 Custom annotation in Java
public Annotation createThumbnail(Document gallery, int eltNum) { ContentElementList galleryElements = gallery.get_ContentElements(); ContentElement contentElement = (ContentElement)galleryElements.get(eltNum); if (!(contentElement instanceof ContentTransfer)) { throw new RuntimeException("Cannot make thumbnail for content reference"); } ContentTransfer gCt = (ContentTransfer)contentElement; String type = gCt.get_ContentType(); String rName = gCt.get_RetrievalName(); Integer esn = gCt.get_ElementSequenceNumber(); Properties gProps = gallery.getProperties(); String franchiseCode = gProps.getStringValue("ITSOFranchiseCode"); // Instantiate the new thumbnail Annotation ObjectStore os = gallery.getObjectStore(); Annotation thumbnail = Factory.Annotation.createInstance(os, "ITSOThumbnail"); Properties tProps = thumbnail.getProperties(); tProps.putValue("ITSOFranchiseCode", franchiseCode); thumbnail.set_AnnotatedObject(gallery); // Better to use immutable ESN than element position thumbnail.set_DescriptiveText("thumbnail image [" + esn + "]"); thumbnail.set_AnnotatedContentElement(esn); ContentTransfer tCt = Factory.ContentTransfer.createInstance(); tCt.set_ContentType(type);
100
if (rName != null && rName.length() > 0) { tCt.set_RetrievalName("t_" + rName); } // The computation of the thumbnail is done elsewhere InputStream photoStream = gCt.accessContentStream(); tCt.setCaptureSource(computeThumbnailGraphics(type, photoStream)); ContentElementList thumbElements = Factory.ContentElement.createList(); thumbElements.add(tCt); thumbnail.set_ContentElements(thumbElements); // Return the new Annotation. return thumbnail; }
Example 4-12 Custom annotation in C#
public IAnnotation CreateThumbnail(IDocument gallery, int eltNum) { IContentElementList galleryElements = gallery.ContentElements; IContentElement contentElement = (IContentElement)galleryElements[eltNum]; if (!(contentElement is IContentTransfer)) { throw new Exception("Cannot make thumbnail for content reference"); } IContentTransfer gCt = (IContentTransfer)contentElement; string type = gCt.ContentType; string rName = gCt.RetrievalName; int? esn = gCt.ElementSequenceNumber; IProperties gProps = gallery.Properties; string franchiseCode = gProps.GetStringValue("ITSOFranchiseCode"); // Instantiate the new thumbnail Annotation IObjectStore os = gallery.GetObjectStore(); IAnnotation thumbnail = Factory.Annotation.CreateInstance(os, "ITSOThumbnail");
101
IProperties tProps = thumbnail.Properties; tProps["ITSOFranchiseCode"] = franchiseCode; thumbnail.AnnotatedObject = gallery; // Better to use immutable ESN than element position thumbnail.DescriptiveText = "thumbnail image [" + esn + "]"; thumbnail.AnnotatedContentElement = esn; IContentTransfer tCt = Factory.ContentTransfer.CreateInstance(); tCt.ContentType = type; if (rName != null && rName.Length > 0) { tCt.RetrievalName = "t_" + rName; } // The computation of the thumbnail is done elsewhere Stream photoStream = gCt.AccessContentStream(); tCt.SetCaptureSource(ComputeThumbnailGraphics(type, photoStream)); IContentElementList thumbElements = Factory.ContentElement.CreateList(); thumbElements.Add(tCt); thumbnail.ContentElements = thumbElements; // Return the new Annotation. return thumbnail; } Caller must save.
102
Note: The event subscription subsystem is strongly related to the audit subsystem. That approach is understandable when you consider that the same activities are interesting both for auditing and for event notifications. The audit subsystem can also be enabled for content retrieval but the event subsystem cannot. We do not cover the audit subsystem in this book. Refer to the product documentation for further information. Event subscriptions are divided into synchronous and asynchronous types. The subscription object sets the type to either synchronous or asynchronous. Informally, the associated EventAction is commonly referred to as a synchronous or asynchronous event handler. Note the following information about synchronous and asynchronous: A synchronous event handler is executed as part of the path to persisting a change. It is within the same transaction scope. In other words, the change has not actually happened yet. If the event handler throws an exception, the entire transaction is aborted. In this way, the synchronous event action can veto a change. An important restriction on synchronous event handlers is that they are not allowed to update the source object, either directly or by acting on a copy. An asynchronous event handler is executed after a change has been committed. The delay between the triggering change and the running of the asynchronous event handler is typically small, but guaranteed maximum delay. An asynchronous event handler has its own transaction scope. Although it cannot veto the change that has already happened, the asynchronous event handler can update the source object. It can also do just about anything else that the developer wants it to do if it fits within the transaction scope and timeout and can be done in the context of a J2EE application server container. Both types of event handlers allow the insertion of user code in a common location in the CE server. The synchronous case can be used to approve or veto updates to keep them consistent with an application policy. The asynchronous case can be used to make changes to keep state consistent, again according to an application policy. Either type of event handler can be used to perform notifications or to initiate actions in external systems. Unlike other forms of application code, an event handler has the nature of a callback and is called by the CE server code. It receives a copy of the source object along with sufficient information to understand the nature of the triggering update activity. Because event handlers execute in the context of the server, normal access control checks do not apply. Another consequence of executing in
103
server context, however, is that event handlers must be written in Java. Interactions with the CE server are through the Java API. Example 4-13 shows an example of an event handler. It is adapted from ITSONewVehicleActivity.java in the sample application.
Example 4-13 Event handler in Java
public class ITSONewVehicleActivity implements EventActionHandler { public void onEvent(ObjectChangeEvent event, Id subId) { try { // Get the object store and the new vehicle folder ObjectStore os = event.getObjectStore(); Folder vehicle = (Folder) event.get_SourceObject(); // Create the ITSOIdleActivity object CustomObject activity = Factory.CustomObject.createInstance(os, "ITSOIdleActivity"); // Get the properties collection Properties props = activity.getProperties(); // Get the start date Date start = new Date(System.currentTimeMillis()); // Calculate an end date of 20 years from now GregorianCalendar end = new GregorianCalendar(); end.setTime(start); end.add(Calendar.YEAR, 20); // Set the properties props.putValue("ITSOFranchiseCode", vehicle.getProperties().getStringValue("ITSOFranchiseCode")); props.putObjectValue("ITSOVehicle", vehicle); props.putValue("ITSOStartDate", start); props.putValue("ITSOEndDate", end.getTime()); // Save the new IdleActivity activity.save(RefreshMode.NO_REFRESH); } catch (RuntimeException r) {
104
throw r; } catch (Throwable t) { // Catch any other exception and wrap it throw new RuntimeException("Unexpected exception", t); } } }
105
there is a read-only and slightly more compact representation of the metadata embodied in ClassDescription and PropertyDescription objects. Note: Newcomers to CE often find the similar terminology of definition and description confusing. Think of it this way: The definition objects are the place where you can actively define various attributes for a class or property. The description objects merely describe what has been defined (and so are read-only). The high-level steps for finding a piece of metadata for a particular property is: 1. Find the applicable ClassDescription object. 2. Iterate over the PropertyDescriptions collection looking for the PropertyDescription object of interest. 3. Read attributes from that PropertyDescription object. Consulting the metadata is common, and changes to it are so rare that the APIs implement a client-side metadata cache (CMC). The CMC transparently intercepts some metadata fetches and satisfies them with locally cached copies. Because the class and property description objects are read-only, there is no harm in sharing them. CMC automatically keeps track of the differences in requester locale and organizes the data by ObjectStore. Although most of the CMC behavior is automatic and transparent, there is also an explicit way of fetching things from CMC. Many developers find this clearer than the implicit behavior. To use the explicit behavior, use a Factory method to instantiate a MetadataCache object. From there, the use of MetadataCache methods is strightforward. Example 4-14 and Example 4-15 on page 107 show metadata discovery. If you want to find all of the custom classes and properties in the sample application, you can call this method with a value of itso for both prefix parameters.
Example 4-14 Metadata discovery in Java public void cmcDemo(ObjectStore os, String classPrefix, String propPrefix) { classPrefix = classPrefix.toLowerCase(); propPrefix = propPrefix.toLowerCase(); MetadataCache cmc = Factory.MetadataCache.getDefaultInstance(); // Use a query to get a list of class names from the ObjectStore. // Can't query on ClassDescription, so query on ClassDefinition // (the class names are identical by design). SearchScope ss = new SearchScope(os); String sqlString = "SELECT " + PropertyNames.SYMBOLIC_NAME
106
+ " FROM " + ClassNames.CLASS_DEFINITION; SearchSQL sql = new SearchSQL(sqlString); RepositoryRowSet rrs = ss.fetchRows(sql, null, null, true); // Iterate over the results. For any class with a name that // starts with the classPrefix, pull a ClassDescription out of // CMC and look for PropertyDescriptions whose names start with // the propPrefix. for (Iterator it = rrs.iterator(); it.hasNext();) { RepositoryRow row = (RepositoryRow)it.next(); Properties props = row.getProperties(); String className = props.getStringValue(PropertyNames.SYMBOLIC_NAME); if (className.toLowerCase().startsWith(classPrefix)) { ClassDescription cd = cmc.getClassDescription(os, className); PropertyDescriptionList pds = cd.get_PropertyDescriptions(); for (Iterator itp = pds.iterator(); itp.hasNext();) { PropertyDescription pd = (PropertyDescription)itp.next(); String propName = pd.get_SymbolicName(); if (propName.toLowerCase().startsWith(propPrefix)) { TypeID type = pd.get_DataType(); // Print the results. System.out.println(className + "." + propName + " (" + type + ")"); } } } } } Example 4-15 Metadata discovery in C# public void cmcDemo(IObjectStore os, string classPrefix, string propPrefix) { classPrefix = classPrefix.ToLower(); propPrefix = propPrefix.ToLower(); IMetadataCache cmc = Factory.MetadataCache.GetDefaultInstance(); // Use a query to get a list of class names from the ObjectStore. // Can't query on ClassDescription, so query on ClassDefinition // (the class names are identical by design). SearchScope ss = new SearchScope(os); String sqlString = "SELECT " + PropertyNames.SYMBOLIC_NAME
107
+ " FROM " + ClassNames.CLASS_DEFINITION; SearchSQL sql = new SearchSQL(sqlString); IRepositoryRowSet rrs = ss.FetchRows(sql, null, null, true); // Iterate over the results. For any class with a name that // starts with the classPrefix, pull a ClassDescription out of // CMC and look for PropertyDescriptions whose names start with // the propPrefix. foreach (IRepositoryRow row in rrs) { IProperties props = row.Properties; string className = props.GetStringValue(PropertyNames.SYMBOLIC_NAME); if (className.ToLower().StartsWith(classPrefix)) { IClassDescription cd = cmc.GetClassDescription(os, className); IPropertyDescriptionList pds = cd.PropertyDescriptions; foreach (IPropertyDescription pd in pds) { string propName = pd.SymbolicName; if (propName.ToLower().StartsWith(propPrefix)) { TypeID type = pd.DataType; // Print the results. Console.WriteLine(className + "." + propName + " (" + type + ")"); } } } } }
108
Some traditional inheritance features in the server are implemented in terms of dynamic security inheritance. Perhaps the most well-known of these is the inheritance of folder security by the folders containees. It is also possible for developers to define custom security inheritance relationships. The implementation mechanism is to define a custom object-valued property (OVP) and designate that property as pointing to a security proxy object. Specifically, you set the value of the corresponding PropertyDefinitionObject SecurityProxyType property to SecurityProxyType.FULL. On the security proxy object itself, you mark the InheritableDepth property of each ACE according to how you would like the inheritance to proceed (none, immediate children, or infinite). Dynamic security inheritance can act transitively. That is, object A can inherit security from object B, which in turn can inherit security from object C. There is no built-in limitation for how long such chains can be. Directly applied ACEs have precedence over inherited ACEs in the access check calculations. In practical terms, this means that a user or group that is denied access through inheritance can still be granted access by a directly applied ACE. An interesting use of dynamic security inheritance is to augment the enterprise directory group structure. This can be especially handy in situations where the natural organizational groups typically found in a directory do not represent security access groups very well. It can also be helpful in situations where security access groups or memberships in those groups changes frequently, and the site does not want to make such frequent changes to the directory. In some ways, security proxy objects can be used to implement an authorization scheme that resembles a limited form of role-based access control (RBAC) that is often sufficient to meet site needs. Rather than providing a code sample for this feature (which is typically an administrative set-up and the application of appropriate default values for the security proxy property on new object instances), we instead provide a description of how it can work with the sample application described elsewhere in this book. Understanding the sample application in detail is not necessary in order to follow this description. A franchise location consists of maintenance employees, front-office employees, and supervisors responsible for managing both maintenance and front-office operations. Maintenance records (ITSOMaintenanceActivity objects in the sample application data model) may be accessed by maintenance employees and supervisory employees, but only within that franchise location. Those objects (and all objects in the sample application data model) have an OVP called ITSOSecurityProxy. There is also a class of objects called ITSORole that is intended to act as security proxy objects, among other things; see the sample application description for more details.
109
Although directly adding all maintenance employees and supervisors of a franchise location to every object where they need access is possible, it then becomes necessary to update the ACL on many objects any time a maintenance employee or supervisor is hired, resigns, changes status, and so on. This is both an operational and performance burden, and the chances for data errors are high. We can solve it more efficiently and elegantly with a chain of proxy objects: Create an ITSORole object to represent the concept of employees who should have access to maintenance records at this franchise location. It should have no directly applied ACEs. We refer to this object as MS. Create an ITSORole object to represent supervisors at this franchise location. It has direct ACEs that are granting access to all the supervisors at that location. We refer to this object as S. Create an ITSORole object to represent maintenance employees at this franchise location. It has direct ACEs granting access to all of the maintenance employees at that location. We refer to this object as M. Maintenance records at this franchise location are created with inheritance from object MS. This is done by populating the ITSOSecurityProxy property with a pointer to MS. Object MS inherits security from both object M and object S. This is done by populating the ITSOSecurityProxy property with a pointer to object M and the ITSOSecurityProxy2 with a pointer to object S. With this arrangement, access for supervisors (object S) and maintenance employees (object M) flows to object MS. From there, the access for the combined groups flows to the maintenance record object. There are many ways to organize this sort of custom inheritance. If access control from groups is being combined, as in this example, you need a class with more than one security proxy property. That is why we used the intermediate object MS in this example; we only needed the second security proxy property on the ITSORole object instead of all the other objects in the data model. Although modeling any kind of aggregation with intermediate objects with just two security proxy properties should be possible, defining more might be more convenient for you. A good practice is to define as few security proxy properties as you think you need and then add more later if necessary.
110
Chapter 5.
111
112
exposes all PE functionality, this API is used for all use cases that are presented; however, for certain cases, we also show how those cases can be implemented using the PEWS API for .NET clients or the PE REST API, depending on the use case and whether the API includes the required functionality.
113
REST API
114
PE Java API object methods also use naming conventions to perform actions over certain PE objects. Table 5-3 on page 116 describes the naming convention used by PE API object methods.
115
Table 5-3 Process Engine API object methods naming convention Object method fetchMethod() Description Retrieves an object from a PE isolated region executing a database operation. Retrieves a parameter from the PE object. These methods usually do not require additional database operations because the parameters are retrieved from cache. Instantiates a VW object, retrieving it from the PE isolated region. Sets a parameter value for a PE object. Tests presence of an object state. Processes work on the PE isolated region, usually with a void return type. Examples VWRoster.fetchCount() method gets the number of work item in the roster. VWRoster.getName() method returns the translated name.
getMethod()
createMethod()
VWQueue.createQuery() method performs a filtered fetch of queue items and returns a VWQueueQuery object. VWDataField.setValue() method sets the value of the data contained in an editable field. VWDataField.isArray() method determines whether the data field is an array. VWWorkObject.doDispatch() method saves changes made in the work object, unlocks it, and moves the current step to the next workflow step. VWSession.convertIdToUserName () method converts the user ID assigned by PE to a user name.
setMethod()
isMethod()
doMethod()
convertMethod()
116
The PE session class consists of the VWSession object used to establish a session and log on to a PE server. Several PE operations can be performed, such as querying rosters and queues, retrieving a list of rosters or queues, administering the system, and establishing an audit trail. The PE error handling class consists of the VWException object, which handles all workflow-related exceptions. The create and process work classes are used to create a workflow processes, get and assign parameter values to work items, and process work items across the workflow life cycle. This group includes the following classes: VWWorkObject VWStepElement VWParameter VWFieldType VWDataField The search work classes are used to find work items either on a PE roster, work queue, or event log. This group includes the following classes: VWRoster VWRosterQuery VWRosterElement VWQueue VWQueueQuery VWQueueElement VWLog VWLogQuery VWLogElement The retrieve work status classes are used to fetch step history data for workflow process associated with a workflow map and information related to milestone events. This group includes the following classes: VWProcess VWWorkflowDefinition VWWorkflowHistory VWStepHistory VWStepOcurrenceHistory VWStepWorkObjectHistory VWWorkflowMilestones VWMilestoneElement
117
In the next section, we put in practice these API classes for process use cases.
118
Connection point
A connection point name identifies a specific isolated region in the workflow database connecting the PE API to an associated isolated region. A defined connection point consists of a PE server, communications port, and isolated region number. For Process Engine Web Service (PEWS) clients, the PE connection point must be specified in the SOAP header request using the router SOAP header element. If no router value is specified, the default value is used. The default connection point for the Process Engine Web Service is PEWSConnectionPoint. PE API usage tips: Performance improvements can be achieved by minimizing the number of Remote Procedure Calls (RPCs) to the PE. Methods that fetch data or cause certain action to occur typically cause RPCs to the PE server, whereas methods that get and set data are local to the object. Similarly, minimize logging on and logging off the PE.
119
Note: You might sometimes see CE connection URIs with a prefix of cemp:. This prefix is for historical purposes only and is ignored by the PE APIs. When you are specifying URIs directly, there is no reason to use that prefix.
Authentication
This section assumes the authentication mechanism between CE and the directory service is properly configured. Example 5-1 on page 121 shows how to create the VWSession object, set the CE URI, and log on to the PE passing the required parameters.
120
// User Information String userName = "Administrator"; String password = "filenet"; // Connection Point String connectionPoint = "CEPoint"; // Create a Process Engine Session Object VWSession myPESession = new VWSession(); // Set Bootstrap Content Engine URI myPESession.setBootstrapCEURI("iiop://ceserver:2809/FileNet/Engine"); // Log onto the Process Engine Server myPESession.logon(userName, password, connectionPoint);
Session logoff
The sessions logoff method ends the session with the PE and frees all resources. Although the system calls this method internally, an explicit call makes finalization more immediate and certain, as shown in Example 5-2. Otherwise, finalization is uncertain even when the Java virtual machine (JVM) shuts down.
Example 5-2 Log off from Process Engine using Java API
121
The SOAP header request must include the correct elements and values, such as account credentials. These credentials are verified when functional operations are attempted. Example 5-3 shows how to initialize the PEWS object and set the correct parameter values including the request SOAP context.
Example 5-3 Creating a PEWS RequestSoapContext header using a C# client
// User Information string userName = "Administrator"; string password = "filenet"; // Connection Point Value string connectionPoint = "CEPoint"; // URL for the PEWS string wsUrl = "http://ceserver:9080/wsi/ProcessEngineWS"; // PE Web Service Policy private static Policy pePolicy = new Policy(new PolicyAssertion[] {new PEAssertion(),new PESecurityAssertion()}); // Create the WS Service Port object peWS.ProcessEngineServiceWse peWSServicePort = new peWS.ProcessEngineServiceWse(); // Set PE Web Service Policy peWSServicePort.SetPolicy(pePolicy); // Set connection point name and wsURL parameters peWSServicePort.RequestSoapContext["router"]=connectionPoint; peWSServicePort.Url = wsUrl; // Create User Context for the RequestSoapContext SecurityToken tok = new UsernameToken(userName, password, PasswordOption.SendPlainText); UserContext.SetProcessSecurityToken(tok); In the example, the C# client application uses authentication helper classes to initiate a Process Engine Web Service Policy object and a UserContext object, which are required to interject the WS-Security and other SOAP headers for authentication purposes. You can refer to these helper classes that are included with the pick-up and drop-off kiosk application as part of the provided sample application in this book.
122
See Chapter 7, Sample applications for Fictional Auto Rental Company A on page 223.
123
VWException.getMessage()
VWException.getCauseClassName() VWException.getCauseDescription()
// User Information String userName = "Administrator"; String password = ""; // Connection Point String connectionPoint = "CEPoint";
124
// Create a Process Engine Session Object VWSession myPESession = new VWSession(); // Set Bootstrap Content Engine URI myPESession.setBootstrapCEURI("iiop://ceserver:2809/FileNet/Engine"); // Start try-catch block to handle exception when log onto PE try { myPESession.logon(userName, password, connectionPoint); } catch (VWException vwe) { System.out.println("\nVWException Key: " + vwe.getKey() + "\n"); System.out.println("VWException Cause Class Name: " + vwe.getCauseClassName() + "\n"); System.out.println("VWException CauseDescription: " + vwe.getCauseDescription()+ "\n"); System.out.println("VWException Message: " + vwe.getMessage()); // Perform error recovery ... }
125
Example 5-5 and Example 5-6 show how to retrieve and create a workflow using both the Java API and a PEWS client.
Example 5-5 Create a workflow process using the Java API
// Create session object and log onto Process Engine ... // Workflow name to launch String workflowName = "myWorkflow"; // Retrieve transfered work classes String[] workClassNames = myPESession.fetchWorkClassNames(true); for (int i=0;i<workClassNames.length;i++) System.out.println(workClassNames[i] ); // Launch Workflow VWStepElement stepElement = myPESession.createWorkflow(workflowName); // Get and Set Workflow parameters for the Launch Step ... // Dispatch Worflow Launch Step stepElement.doDispatch();
Example 5-6 Create a workflow process using PEWS
// Create the PEWS RequestSoapContext header ... // Workflow name to launch string workflowName = "myWorkflow"; // Get the available workclasses ArrayList arrayWorkClasses = new ArrayList(); string[] workClassNames = peWSServicePort.getWorkClassNames(); foreach (string workClassName in workClassNames) { ... } private peWS.StepElement stepElement; stepElement = peWSServicePort.createWorkflow(workflowName); // Get and Set Workflow parameters for the Launch Step ...
126
// Dispatch Worflow Launch Step peWS.UpdateStepRequest updStepRequest = new peWS.UpdateStepRequest(); peWS.UpdateFlagEnum updFlagEnum = peWS.UpdateFlagEnum.UPDATE_DISPATCH; updStepRequest.stepElement = stepElement; updStepRequest.updateFlag = updFlagEnum; peWSServicePort.updateStep(updStepRequest);
127
// Get the work object's default values defaultWorkObjectValue = data; }, error: function(data) { // The error callback console.dir(data); }, sync: true } ); // Set URL for POST request url = baseURL + newWorkItemURL; var workObject = defaultWorkObjectValue; // Update work class lauch step fields workObject.dataFields["CompanyName"].value = "IBM"; // Set the attachment value workObject.attachments["Documents"].value = [{"vsId":"{997E0AAC-8068-4990-AC08-D748E3063162}", "title":"MyDocument1", "type":3, "libraryName":"objectstore", "libraryType":3, "version":"{D48EE0A9-61CA-4DAD-8B61-961CE362434B}", "desc":"web.xml"}]; // Use HTTP POST Method to create the new work object dojo.rawXhrPost({ // the response callback url: url, handleAs: "json-comment-optional", headers: {"Content-Type": "application/json", "POE": "1"}, _raw: true, // Post back the modified work object postData: dojo.toJson(workObject), load: function(data, ioArgs) { console.log(dojo.toJson(data)); }, error: function(data) { // the error callback console.log(data); }, sync: true } );
128
129
To optimize PE queries: Set the appropriate query flags to return only user fields from roster, queue, and log queries. For example, to avoid retrieving system fields and helper data from the work items returned, set the query flags for the queryFlags parameter of createQuery(): QUERY_GET_NO_SYSTEM_FIELDS QUERY_GET_NO_TRANSLATED_SYSTEM_FIELDS Note that helper methods on elements are not functional without translated system fields. Create indexes and limit the number of indexes to achieve more efficient queries with less data transmitted. Indexes must be unique. Use filters to get ranges of elements for more efficient queries with less data transmitted. Use filters to limit elements retrieved to a specified range or to set a maximum number of objects to be retrieved for each fetch from the PE server (default is 50 items).
substitutionVars fetchType
130
Note: Use VWWorkObjectNumber class as a substitution value type for queries when using F_WobNum or F_WorkFlowNumber. The type is substituted into the filter string specified. This class takes care of formatting the work object or workflow number so the developer does not have to.
Query flags
These flags represent an integer value that specifies the search options. Setting this parameter refines the search for the work items that are specified by the search index. Table 5-7 shows the available query flags for work search.
Table 5-7 Process Engine query flag options for work search Query flag QUERY_GET_NO_SYSTEM_ FIELDS QUERY_GET_NO_TRANSLAT ED_SYSTEM_FIELDS QUERY_MAX_VALUES_ INCLUSIVE QUERY_MIN_VALUES_ INCLUSIVE QUERY_NO_OPTIONS QUERY_READ_UNWRITABLE QUERY_RESOLVE_NAMES Integer value 1024 2048 64 32 0 4 8192 Description Returns objects without system fields. Returns objects without translated fields. Specifies the inclusion of maximum search values. Specifies the inclusion of minimum search values. Specifies no search option. Specifies the return of read-only work items. Supports conversion of user names to IDs for Process Engine Web services to perform queries using user ID fields within an index or filter.
131
To optimize roster queries: Expose only infrequently updated fields. Exposed data fields on rosters are more costly for updates. Set an optimal buffer size on the roster-related queries. For example, consider increasing the buffer size (default is 50, maximum is 200) to minimize round-trips to the PE server. Query roster elements instead of work objects. Query work objects through the roster causes the application to access database records twice instead of once. Example 5-8 and Example 5-9 on page 133 show how to retrieve work items from a workflow roster by using both the Java API and a PEWS client.
Example 5-8 Query workflow roster using the Java API
// Create session object and log onto Process Engine ... // Set Roster Name String rosterName= "DefaultRoster"; // Retrieve Roster Object and Roster count VWRoster roster = myPESession.getRoster(rosterName); System.out.println("Workflow Count: " + roster.fetchCount()); // Set Query Parameters int queryFlags=VWRoster.QUERY_NO_OPTIONS; String queryFilter="F_WobNum=:A"; String wobNum = "5BDD567B70453C48A5388AC56ABC69E4"; // VWWorkObjectNumber class takes care of the value format // used in place of F_WobNum and F_WorkFlowNumber Object[] substitutionVars = {new VWWorkObjectNumber(wobNum)}; int fetchType = VWFetchType.FETCH_TYPE_ROSTER_ELEMENT; // Perform Query VWRosterQuery query = roster.createQuery (null,null,null,queryFlags,queryFilter,substitutionVars,queryType); // Process Results while(query.hasNext()) { VWRosterElement rosterItem = (VWRosterElement) query.next(); System.out.println("WF Number: "+rosterItem.getWorkflowNumber());
132
133
Query queues
The following steps retrieve work items from a workflow queue using the PE Java and Web services APIs: 1. 2. 3. 4. 5. 6. Create a VWSession object and log on to PE. Retrieve the queue to search. Get the queue depth. Set the query parameters. Perform the query. Process the results returned by the query.
The same steps are included to retrieve work items from a workflow queue for all queue categories described above. Refer to Table 5-6 on page 130 for a detailed description of the required parameters that are included in the createQuery method to query a queue by using the PE APIs.
134
To optimize queue queries: Use the QUERY_LOCK_OBJECTS flag. This avoids the necessity of an additional RPC to check the lock status of an object (or to lock an object). Using the flag also reduces lock contention. Set an optimal buffer size on the query. For example, consider increasing the buffer size (default is 50, maximum is 200) to minimize round-trips to the PE server. Partition, if possible, to use more than one queue. Example 5-10 and Example 5-11 on page 136 show how to retrieve work items from a workflow queue using both the Java API and a PEWS client.
Example 5-10 Query workflow queue using the Java API
// Create session object and log onto Process Engine ... // Queue Name String queueName = "Inbox"; // Retrieve the Queue to be searched and Queue depth VWQueue queue = myPESession.getQueue(queueName); System.out.println("Queue Depth: " + queue.fetchCount()); // Set Query Parameters String wobNum = "5BDD567B70453C48A5388AC56ABC69E4"; VWWorkObjectNumber wob = new VWWorkObjectNumber(wobNum); VWWorkObjectNumber[] queryMin = new VWWorkObjectNumber[1]; VWWorkObjectNumber[] queryMax = new VWWorkObjectNumber[1]; String queryIndex = "F_WobNum"; queryMin[0] = wob; queryMax[0] = wob; int queryFlags = VWQueue.QUERY_MIN_VALUES_INCLUSIVE + VWQueue.QUERY_MAX_VALUES_INCLUSIVE; int fetchType = VWFetchType.FETCH_TYPE_QUEUE_ELEMENT; // Perform Query VWQueueQuery queueQuery = queue.createQuery(queryIndex,queryMin, queryMax,queryFlags,null,null,fetchType); // Process Results while(queueElement.hasNext()) {
135
VWQueueElement queueElement = (VWQueueElement) queueQuery.next(); System.out.println("Username: "+ queueElement.getFieldValue("F_BoundUser").toString()); System.out.println("WOB Number: "+ queueElement.getWorkObjectNumber()); System.out.println("F_Subject: " + queueElement.getFieldValue("F_Subject")); }
Example 5-11 Query workflow queue using PEWS // Create the PEWS RequestSoapContext header ... // Set Queue Name string queueName= "Inbox"; // Set Query Parameters peWS.GetQueueElementsRequest query = new peWS.GetQueueElementsRequest(); query.queryFlags = new peWS.QueryFlagEnum?[1] { peWS.QueryFlagEnum.QUERY_READ_LOCKED }; query.nToReturn = 100; query.queueName = queueName; // Perform Query peWS.QueueElement[] queueelements = peWSServicePort.getQueueElements(query); // Process Results foreach (peWS.QueueElement queueelement in queueelements) { peWS.Field[] fields = queueelement.Fields; foreach(peWS.Field field in fields) { // Only process the field if there is a value if (field.Values.Length > 0) { // Process field values //field.Name; //field.Values[0].Item.GetType(); //field.Values[0].Item; } } }
136
Event-logging categories
Each system event that is logged is part of an event category, and has an associated event number. Table 5-8 shows the primary event-logging categories used for workflow event tracking. For further details about all event-logging categories available, refer to the following P8 documentation path: ECM Help User Help Integrating workflow Workflow overview Process Engine Reference Events and statistics Event log categories.
Table 5-8 Primary event logging categories Event log category Creation Event logged VW_WOChildCreatio nMsg VW_WOParentCreati onMsg Termination VW_WOChildTermin ationMsg VW_WOParentTermi nationMsg VW_WFTermination Administration message VW_WOForcedToSki pInstructionMsg VW_WOForcedToTer minateMsg VW_WOForcedToDe leteMsg Event number 130 140 150 160 165 180 190 200 Description Records the creation of a child work item. Records the creation of a parent work item. Records the termination of a child work item. Records the termination of a parent work item. Records the completion of all work items in a workflow. Records when a work item is forced to skip an instruction. Records when a work item is forced to terminate. Records when a work item is forced to delete.
137
Description Records when a step processor or user locks a work item. Records when a work item is queued. Records when a work item is updated and dispatched to the next queue. Records when a work item is saved while retaining the existing lock. Records when work item processing ends abnormally. Records when a work item is updated and unlocked in the same queue. Records when a work item is delegated to another user. Records when a work item is reassigned to another user. Records when a work item is returned to a user following delegation. Records when a user cancels, stops, or ends an operation. Records when a step is executed without specifying a queue. Records when a compound step is completed.
End operation
VW_WPEndService NormalMsg VW_WPWOBSaveW ithLockMsg VW_WPEndService AbnormalMsg VW_WPEndService ReleaseMsg VW_WPEndService ReleaseDelegateMs g VW_WPEndService ReleaseReassignMs g VW_WPEndService ReleaseReturnMsg VW_WPEndService AbortMsg
365
370 380
382
384
386
390 500
510
The following steps retrieve work items from an event log using the PE Java API: 1. Create a VWSession object and log on to PE. 2. Retrieve the event log to search. 3. Set the query parameters.
138
4. Perform the query and count the elements returned. 5. Process the results. Refer to Table 5-6 on page 130 for a detailed description of the required parameters included in the createQuery method to query a queue using the PE APIs. To optimize event log queries: Partition to use different logs for different workflows. Disable any logging options that you do not need. Note that although this improves performance, it also affects the Process Tracker and Process Analyzer. Manage log records. Use the vwlog tool to maintain logs. Use operating system scheduling tools to periodically remove unused log records. Save log information in text files. Example 5-12 shows how to retrieve work items from an event log by using the Java API.
Example 5-12 Query event log by using the Java API // Create session object and log onto Process Engine ... // Set Event Log Name String eventLogName = "DefaultEventLog"; // Retrieve the Event Log to be searched VWLog log = myPESession.fetchEventLog(eventLogName); // Set Query Parameters String queryFilter = "F_EventType = 240"; // user logged in event type int queryFlags = VWLog.QUERY_NO_OPTIONS; // Perform Query VWLogQuery query = log.startQuery(null,null,null,queryFlags,queryFilter,null); // Process Results VWLogElement logElement = (VWLogElement) query.next(); int eventType = logElement.getEventType(); String stringEventType = VWLoggingOptionType.getLocalizedString(eventType); String[] fieldNames = logElement.getFieldNames(); String FieldValue = logElement.getFieldValue(fieldNames[0]).toString();
139
For further details about steps to retrieve a step element using the PE REST API, see Retrieve step element: REST API scenario on page 142.
140
Example 5-13 and Example 5-14 show how to retrieve a step element from a user queue by using both the Java API and a PEWS client.
Example 5-13 Retrieve a step element from the Inbox by using the Java API
// Create session object and log onto Process Engine ... // Queue Name String queueName = "Inbox"; // Retrieve the Queue VWQueue queue = myPESession.getQueue(queueName); // Set Query Parameters String wobNum = "5BDD567B70453C48A5388AC56ABC69E4"; VWWorkObjectNumber wob = new VWWorkObjectNumber(wobNum); VWWorkObjectNumber[] queryMin = new VWWorkObjectNumber[1]; VWWorkObjectNumber[] queryMax = new VWWorkObjectNumber[1]; String queryIndex = "F_WobNum"; queryMin[0] = wob; queryMax[0] = wob; // Query Flags and Type to retrieve Step Elements int queryFlags = VWQueue.QUERY_READ_LOCKED; int queryType = VWFetchType.FETCH_TYPE_STEP_ELEMENT; VWQueueQuery queueQuery = queue.createQuery (queryIndex,queryMin,queryMax,queryFlags,null,null,queryType); // Get an individual Step Element VWStepElement stepElement = (VWStepElement) queueQuery.next();
Example 5-14 Retrieve a step element from the Inbox using PEWS
// Create the PEWS RequestSoapContext header ... // Set Queue Name string queueName= "Inbox"; // Set Query Parameters string wobNum= "5BDD567B70453C48A5388AC56ABC69E4"; peWS.RetrieveStepRequest request = new peWS.RetrieveStepRequest(); request.bLock = true; request.bOverrideLock = true; request.queueName = queueName; request.wobNum = wobNum;
141
peWS.GetStepElementsFromQueueRequest qry = new peWS.GetStepElementsFromQueueRequest(); request.queryFlags = new peWS.QueryFlagEnum? []{peWS.QueryFlagEnum.QUERY_NO_OPTIONS}; // Perform Query and Retrieve Step Element peWS.StepElement = peWSServicePort.retrieveStep(request);
// Ensure to be authenticated with the Application Server container // Set request URI var baseURL = "http://localhost:9080/WorkplaceXT/P8BPMREST/p8/bpm/v1/"; // Set REST API resource and work item number var queueName = "Inbox"; var wobNumber = "5BDD567B70453C48A5388AC56ABC69E4"; var url = baseURL + "queues/" + queueName + "/stepelements/" + wobNumber; var stepElement; // Use HTTP GET method to retrieve the step element by specifying // the queue name and work object number dojo.xhrGet({ url: url, // Handle the result as JSON object handleAs: "json-comment-optional", // the callback to handle the response load: function(data) { stepElement = data; // Process the attachments for (var attachmentName in stepElement.attachments) { // .... console.log(attachmentName); }
142
// Process the data fields for (var dataFieldName in stepElement.dataFields) { // .... console.log(dataFieldName); } // Process the system properties for (var systemPropName in stepElement.systemProperties) { // .... console.log(systemPropName); } // Process step processor //var stepProcessor = stepElement.stepProcessor; }, error: function(data) { // the error callback console.dir(data); } } );
143
Table 5-9 Primary process field flags Field flag Field type Values Integer (FIELD_TYPE_INT) String (FIELD_TYPE_STRING) Boolean (FIELD_TYPE_BOOLEAN) Float (FIELD_TYPE_FLOAT) Time (FIELD_TYPE_TIME) Attachment (FIELD_TYPE_ATTACHMENT) Participant (FIELD_TYPE_PARTICIPANT) All types (ALL_FIELD_TYPES) User (FIELD_USER_DEFINED) System (FIELD_SYSTEM_DEFINED) User and system (FIELD_USER_AND_SYSTEM_DEFINED) Read only (MODE_TYPE_IN) Write only (MODE_TYPE_OUT) Read and write (MODE_TYPE_IN_OUT) Description An integer value that specifies the parameter type or types
Field creator
An integer that specifies one of the field creator types An integer value that indicates the mode of the step parameter
Field mode
The following steps get step element parameters by using the PE Java and Web services APIs: 1. Retrieve the user- and system-defined VWParameters. 2. Get the name, data type, read and write mode, and value for each parameter. 3. Retrieve the step element responses. For further details about included steps to retrieve step element parameters using the PE REST API, see Get step element parameters: REST API scenario on page 146. Example 5-16 and Example 5-17 on page 145 show how to retrieve step element parameters and responses using both the Java API and a PEWS client.
Example 5-16 Get step element parameters and responses using the Java API
// Create session object and log onto Process Engine ... // Retrieve Step Element ... // Specify Field Type and Field Creator flags to retrieve // user- and system-defined parameters VWParameter[] parameters = stepElement. getParameters(VWFieldType.ALL_FIELD_TYPES, VWStepElement.FIELD_USER_AND_SYSTEM_DEFINED);
144
// Get the name, type, mode, and value for each parameter for (int i = 0; i < parameters.length; i++ ) { // Get Parameter Name String parameterName = parameters[i].getName(); // Get Parameter Type (Field Type Flag) String parameterType = VWFieldType.getLocalizedString (parameters[i].getFieldType()); // Get Parameter Mode (Field Mode Flag) String parameterMode = VWModeType.getLocalizedString (parameters[i].getMode()); // Get Parameter Value String parameterValue =parameters[i].getStringValue(); } // Retrieve Step Element Responses String[] stepResponses = stepElement.getStepResponses(); if(stepResponses != null) { int len = stepResponses.length; for(int j = 0; j < len; j++ ) { // Process Response System.out.println(stepResponses[j]); } }
Example 5-17 Get step element parameters and responses using PEWS
// Create the PEWS RequestSoapContext header ... // Retrieve Step Element ... // Retrieve Step Element Parameters peWS.Parameter[] parameters = stepElement.Parameters; // Get the name, type, mode, and value for each parameter foreach(peWS.Parameter param in parameters) { // Get Parameter Name string paramName = param.Name; // Get Parameter Type (peWS.FieldTypeEnum) string paramType = param.Type; // Get Parameter Mode (peWS.ModeTypeEnum) string paramMode = param.Mode;
145
// Get Parameter Value if( param.Values.Length > 0) { foreach( peWS.Value stepvalue in param.Values) { string paramValue = stepvalue.Item; } } } // Retrieve Step Element Responses peWS.ArrayOfResponse stepResponses = stepElement.Responses; if (stepResponses!=null) { foreach (string response in stepResponses.Response) { // Process Response System.Windows.Forms. MessageBox.Show("Step Element Response: "+response); } }
// Ensure to be authenticated with the Application Server container // Set request URI var baseURL = "http://localhost:9080/WorkplaceXT/P8BPMREST/p8/bpm/v1/"; // Set REST API resource and work item number var queueName = "Inbox"; var wobNumber = "5BDD567B70453C48A5388AC56ABC69E4"; var url = baseURL + "queues/" + queueName + "/stepelements/" + wobNumber; // Helper funtion to print parameter properties
146
var printParameter = function(parameter) { // get the attachment name var name = parameter.name; // get the mode var mode = parameter.mode; // get the type var type = parameter.type; // get the value var value = parameter.value; console.log("Attachment " + name + ": "); console.log(" - Mode: " + mode); console.log(" - Type: " + type); console.log(" - Value: " + value); }; // Use HTTP GET method to retrieve the step element by specifying // the queue name and work object number dojo.xhrGet({ url: url, handleAs: "json-comment-optional", load: function(data) { // the callback to handle the response stepElement = data; var attachments = stepElement.attachments; var dataFields = stepElement.dataFields; var stepProcessor = stepElement.stepProcessor; var systemProperties = stepElement.systemProperties; // print the attachment parameters for (var attachmentName in attachments) { var attachment = attachments[attachmentName]; printParameter(attachment); } // print the dataField parameters for (var dataFieldName in dataFields) { var dataField = dataFields[dataFieldName]; printParameter(dataField); } // print the systemField parameters for (var systemPropName in systemProperties) { var systemPropValue = systemProperties[systemPropName]; console.log("systemProperty (" + systemPropName + "):"
147
+ systemPropValue); } // print the step responses var responses = systemProperties.responses; for (var i = 0; i < responses.length; i++) { console.log("response (" + i + "):" + responses[i]); } }, error: function(data) { // the error callback console.dir(data); } } );
148
Table 5-10 Workflow attachment types Attachment type ATTACHMENT_TYPE_CUSTOM_OBJECT ATTACHMENT_TYPE_DOCUMENT ATTACHMENT_TYPE_FOLDER ATTACHMENT_TYPE_LIBRARY Integer value 6 3 2 1 Description Indicates the attachment type is a custom object Indicates the attachment is the document type Indicates the attachment is the folder type Indicates the attachment type is library or Object Store Indicates the attachment is the stored search type Indicates the attachment type is not known Indicates the attachment type is a UNC or URL
4 0 5
Note: The VWParticipant object represents the name of a user or user group in any of the following ways: Short (logon) name Distinguished name (DN) Display name (configurable) For a detailed description of the primary field flags required to properly handle step element and work item fields, see the list in Table 5-9 on page 144. The following steps are required to update step element parameter values using the PE Java and Web services APIs: 1. 2. 3. 4. 5. 6. Lock the step element. Check whether the parameter is read only. Switch through each data type for editable parameters. For each data type, check whether the parameter is single or an array. Set the value for the parameter. Set the value for the system-defined response parameter.
149
For further details about included steps to update step element parameter values by using the PE REST API, see the Set step element parameter values: REST API scenario on page 154. Example 5-19 and Example 5-20 on page 152 show how to perform the steps required to set step elements parameter values, using both the Java API and a PEWS client.
Example 5-19 Set step element parameters and responses by using the Java API
// Create session object and log onto Process Engine ... // Retrieve Step Element ... // Retrieve Step Element Parameters ... // Lock the Step Element stepElement.doLock(true); // Process Step Element Parameters for (int i = 0; i < parameters.length; i++ ) { // Check parameter mode boolean readOnly = (parameters[i].getMode() == VWModeType.MODE_TYPE_IN); // If the parameter is editable, switch through each data type if (!readOnly) { // For each data type, // check whether the parameter is single or an array // and set the parameter value(s) switch (parameters[i].getFieldType()) { case VWFieldType.FIELD_TYPE_STRING: if (parameters[i].isArray()) { String[] arrParamValues = new String[] {"value_1", "value_2", "value_3"}; stepElement.setParameterValue (parameters[i].getName(),arrParamValues,true); } else { String paramValue = "value_1"; stepElement.setParameterValue (parameters[i].getName(),paramValue,true); } break;
150
case VWFieldType.FIELD_TYPE_ATTACHMENT: if (!parameters[i].isArray()) { // Get the value for the VWAttachment VWAttachment attachment = (VWAttachment) parameters[i].getValue(); // Set the attachment name attachment.setAttachmentName("Document Title"); // Set the attachment description attachment.setAttachmentDescription ("A document added programmatically"); // Set the type of object (Document) attachment.setType (VWAttachmentType.ATTACHMENT_TYPE_DOCUMENT); // Set the library type and name (CE Object Store) attachment.setLibraryType (VWLibraryType.LIBRARY_TYPE_CONTENT_ENGINE); attachment.setLibraryName("ObjectStoreName"); // Set the document ID and version attachment.setId ("{BBE5AD7F-2449-4DC3-AA38-012A65EC4286}"); attachment.setVersion ("{BBE5AD7F-2449-4DC3-AA38-012A65EC4286}"); // Set the parameter value stepElement.setParameterValue (parameters[i].getName(),attachment,true); } break; case VWFieldType.FIELD_TYPE_PARTICIPANT: // Instantiate a new VWParticipant array VWParticipant[] participant = new VWParticipant[1]; // Set the participant name using username value String participantUserName = "Administrator"; participant[0].setParticipantName(participantUserName); // Set the parameter value stepElement.setParameterValue (parameters[i].getName(),participant,true); break; default: // Do not take action for other data types break; } }
151
} // Set the value for the system-defined Response parameter if (stepElement.getStepResponses() != null) { String responseValue = "Ok"; stepElement.setSelectedResponse(responseValue); }
Example 5-20 Set step element parameters and responses by using PEWS
// Create the PEWS RequestSoapContext header ... // Retrieve and Lock Step Element // request.bLock = true; // request.bOverrideLock = true; ... // Retrieve Step Element Parameters // Process Step Element Parameters foreach(peWS.Parameter param in parameters) { // If the parameter is editable, switch through each data type bool readOnly = param.Mode == peWS.ModeTypeEnum.MODE_TYPE_IN; if (!readOnly) { switch(param.Type) { case peWS.FieldTypeEnum.FIELD_TYPE_STRING: // Set the parameter value string paramValue = "value_1"; peWS.Value stepvalue = new peWS.Value(); peWS.Value[] values = {paramValue}; param.Values = values; param.Modified = true; break; case peWS.FieldTypeEnum.FIELD_TYPE_ATTACHMENT: // Get the value for the attachment object peWS.Attachment peAttachment = (peWS.Attachment)stepvalue.Item; // Set the attachment name peAttachment.Name = "Document Title"; // Set the attachment description peAttachment.Description =
152
"A document added programmatically"; // Set the library type and name (CE Object Store) peAttachment.LibraryType = peWS.LibraryTypeEnum.LIBRARY_TYPE_CONTENT_ENGINE; peAttachment.Library = "ObjectStoreName"; // Set the type of object (Document) peAttachment.Type = peWS.AttachmentTypeEnum.ATTACHMENT_TYPE_DOCUMENT; // Set the document ID and version peAttachment.Id = "{BBE5AD7F-2449-4DC3-AA38-012A65EC4286}"; peAttachment.Version = "{BBE5AD7F-2449-4DC3-AA38-012A65EC4286}"; // Set the parameter value peWS.Value stepvalue = new peWS.Value(); peWS.Value[] values = {peAttachment}; param.Values = values; param.Modified = true; break; case peWS.FieldTypeEnum.FIELD_TYPE_PARTICIPANT: // Set the participant name using username value string participantUserName = "Administrator"; // Set the parameter value peWS.Value stepvalue = new peWS.Value(); peWS.Value[] values = {participantUserName}; param.Values = values; param.Modified = true; break; default: // Do not take action for other data types break; } } } // Set the value for the system-defined Response parameter peWS.ArrayOfResponse stepResponses = stepElement.Responses; if (stepResponses!=null) { string responseValue = "Ok"; stepResponses.Selected = responseValue; }
153
// Ensure to be authenticated with the Application Server container // Set request URI var baseURL = "http://localhost:9080/WorkplaceXT/P8BPMREST/p8/bpm/v1/"; // Set REST API resource and work item number var queueName = "Inbox"; var wobNumber = "5BDD567B70453C48A5388AC56ABC69E4"; var url = baseURL + "queues/" + queueName + "/stepelements/" + wobNumber; var eTag; var stepElement; // Use the HTTP GET method to retrieve the step element and eTag dojo.xhrGet({ url: url, handleAs: "json-comment-optional", // The callback to handle the response load: function(data, ioArgs) { // Get the step element stepElement = data; // Get the eTag eTag = ioArgs.xhr.getResponseHeader("ETag"); }, // The error callback error: function(data) { console.dir(data); }, sync: true // Use the HTTP PUT method to lock the step element
154
var urlForLock = url + "?action=lock&responseContent=1"; dojo.rawXhrPut({ url: urlForLock, handleAs: "text", // Set the value of "If-Match" to the value of eTag // that you got in the 1st step headers: {"Content-Type":"application/json","If-Match":eTag}, _raw: true, // The callback to handle the response load: function(data, ioArgs) { console.log(dojo.toJson(data)); console.log("Lock successfully"); }, // The error callback error: function(data) { console.dir(data); }, sync: true } ); // Set the step element parameter values for (var dataFieldName in stepElement.dataFields) { var dataField = stepElement.dataFields[dataFieldName]; if (dataField.type === 2) { dataField.value = "Value_1"; dataField.modified = true; console.log("Set the value for data field: " + dataFieldName); } } for (var attachmentName in stepElement.attachments) { console.log("Set the value for attachment: " + attachmentName); var attachment = stepElement.attachments[attachmentName]; if (attachment.isArray) { attachment.value = [{"vsId":"{997E0AAC-8068-4990-AC08-D748E3063162}", "title":"Document Title", "type":3, "libraryName":"objectstore", "libraryType":3, "version":"{D48EE0A9-61CA-4DAD-8B61-961CE362434B}", "desc":"A document added programmatically"}]; } else { attachment.value = {"vsId":"{997E0AAC-8068-4990-AC08-D748E3063162}",
155
"title":"Document Title", "type":3, "libraryName":"objectstore", "libraryType":3, "version":"{D48EE0A9-61CA-4DAD-8B61-961CE362434B}", "desc":"A document added programmatically"}; } attachment.modified = true; } // set workflow group participant for (var workflowGroupName in stepElement.workflowGroups) { console.log("Set the value for workflow group: " + workflowGroupName); var workflowGroup = stepElement.workflowGroups[workflowGroupName]; if (workflowGroup.isArray) { workflowGroup.value = [{"Administrator"}]; } else { workflowGroup.value = {"Administrator"}; } workflowGroup.modified = true; } // Set the selected Response stepElement.systemProperties.selectedResponse = "Complete";
156
// Create session object and log onto Process Engine ... // Retrieve Step Element and Step Parameters ... // Set Step Element Parameters ... // Action Types final int ACTION_TYPE_REASIGN = 1; final int ACTION_TYPE_RETURN = 2; final int ACTION_TYPE_ABORT = 3; final int ACTION_TYPE_SAVE= 4; final int ACTION_TYPE_DISPATCH = 5; // Complete Step Element // Action to perform on the Step Element int actionToPerform = 5; // Dispatch switch (actionToPerform) { case ACTION_TYPE_REASIGN: // Determine whether a step element // can be reassigned and reassign it if (stepElement.getCanReassign()) { String participantName = "Administrator"; stepElement.doReassign(participantName,true,null); } break; case ACTION_TYPE_RETURN: // Determine whether a step element can be returned to the // queue from which the user delegated or reassigned it and // return it if (stepElement.getCanReturnToSource()) stepElement.doReturnToSource(); break; case ACTION_TYPE_ABORT: // Cancel the changes to the work item // without advancing it in the workflow stepElement.doAbort(); break;
157
case ACTION_TYPE_SAVE: // Save the changes to the work item // and unlock it without advancing it in the workflow stepElement.doSave(true); break; case ACTION_TYPE_DISPATCH: // Save the changes to the work item // and advance it in the workflow stepElement.doDispatch(); break; } Note: Abort actions on step elements are not available for the Process Engine Web Services API. Instead, the unlockStep operation is available for step elements (to cancel changes on a work item and unlock it).
Example 5-23 Complete a work item using PEWS // Create the PEWS RequestSoapContext header ... // Retrieve Step Element and Step Parameters ... // Set Step Element Parameters ... // Action Types sealed int ACTION_TYPE_REASIGN = 1; sealed int ACTION_TYPE_RETURN = 2; sealed int ACTION_TYPE_SAVE= 3; sealed int ACTION_TYPE_DISPATCH = 4; // Complete Step Element // Action to perform on the Step Element int actionToPerform = 4; // Dispatch switch (actionToPerform) { case ACTION_TYPE_REASIGN: if (stepElement.CanReassign) { string participantName = "Administrator"; peWS.ReassignStepRequest reassignRqt = new peWS.ReassignStepRequest (); reassignRqt.delegate = true; reassignRqt.newUserName = participantName; reassignRqt.stepElement = stepElement;
158
peWSServicePort.reassignStepRequest(reassignRqt); } break; case ACTION_TYPE_RETURN: // Determine whether a step element can be returned to the // queue from which the user delegated or reassigned it and // return it if (stepElement.CanReturnToSource) { peWS.UpdateStepRequest updStepRequest = new peWS.UpdateStepRequest(); peWS.UpdateFlagEnum updFlagEnum = peWS.UpdateFlagEnum.UPDATE_SAVE_RETURN; updStepRequest.stepElement = stepElement; updStepRequest.updateFlag = updFlagEnum; peWSServicePort.updateStep(updStepRequest); } break; case ACTION_TYPE_SAVE: // Save the changes to the work item // and unlock it without advancing it in the workflow peWS.UpdateStepRequest updStepRequest = new peWS.UpdateStepRequest(); peWS.UpdateFlagEnum updFlagEnum = peWS.UpdateFlagEnum.UPDATE_SAVE_UNLOCK; updStepRequest.stepElement = stepElement; updStepRequest.updateFlag = updFlagEnum; peWSServicePort.updateStep(updStepRequest); break; case ACTION_TYPE_DISPATCH: // Save the changes to the work item // and advance it in the workflow peWS.UpdateStepRequest updStepRequest = new peWS.UpdateStepRequest(); peWS.UpdateFlagEnum updFlagEnum = peWS.UpdateFlagEnum.UPDATE_DISPATCH; updStepRequest.stepElement = stepElement; updStepRequest.updateFlag = updFlagEnum; peWSServicePort.updateStep(updStepRequest); break; }
159
saveAndUnlock
abort dispatch
Example 5-24 shows how to complete a work item with a Dojo toolkit client.
Example 5-24 Complete a work item with a Dojo toolkit client
// Ensure to be authenticated with the Application Server container // Set request URI var baseURL = "http://localhost:9080/WorkplaceXT/P8BPMREST/p8/bpm/v1/"; // Set REST API resource and work item number var queueName = "Inbox"; var wobNumber = "5BDD567B70453C48A5388AC56ABC69E4";
160
var url = baseURL + "queues/" + queueName + "/stepelements/" + wobNumber; // Use the HTTP GET method to retrieve the step element and eTag ... // Use the HTTP PUT method to lock the step element ... // Set step element parameter values and response ... // Complete the step element by HTTP PUT method var urlForDispatch = url + "?action=dispatch&responseContent=0"; dojo.rawXhrPut({ url: urlForDispatch, handleAs: "text", // Set the value of "If-Match" to the value of eTag //retrieved from the initial request headers: {"Content-Type":"application/json","If-Match":eTag}, _raw: true, // Set the data you want to put back putData: dojo.toJson(stepElement), // The callback to handle the response load: function(data, ioArgs) { console.log("Complete the step element successfully"); }, // The error callback error: function(data) { console.dir(data); }, sync: true } );
161
Table 5-12 on page 163 shows the information that can be retrieved from the PE objects to track the workflow-related historical information.
162
Table 5-12 Process history information Process Engine object VWProcess VWProcessHistory VWStepHistory VWStepOcurrenceHistory VWStepWorkObjectHistory VWParticipantHistory Information to retrieve Status, history, child, and split work object information Launch step comments, launch date, workflow originator, launch step response Step occurrence completion date, date participant received work, step status Step name Whether this process was completed Comments, responses, dates completed and received, exposed log fields, activity status, name of participant who completed, delegated, reassigned, returned, or terminated step
Example 5-25 shows how to retrieve information about the workflow history by using the Java API
Example 5-25 Retrieve workflow history information using the Java API // Create session object and log onto Process Engine ... // Get the specific work item ... // Get VWProcess object from work object VWProcess process = stepElement.fetchProcess(); // Get workflow definitions from the VWProcess VWWorkflowDefinition workflowDefinition = process.fetchWorkflowDefinition(false); // Get maps for each workflow definition VWMapDefinition[] workflowMaps = workflowDefinition.getMaps(); // Iterate through each map in the workflow Definition for (int i = 0; i < workflowMaps.length; i++) { // Get map ID and map name for each map definition int mapID = workflowMaps[i].getMapId(); String mapName = workflowMaps[i].getName(); // Get workflow history information for each map VWWorkflowHistory workflowHistory = process.fetchWorkflowHistory(mapID); String workflowOriginator = workflowHistory.getOriginator();
163
// Iterate through each item in the Workflow History while (workflowHistory.hasNext()) { // Get step history objects for each workflow history VWStepHistory stepHistory = workflowHistory.next(); // Iterate through each item in the Step History while (stepHistory.hasNext()) { // Get step occurrence history // objects for each step history object VWStepOccurrenceHistory stepOccurenceHistory = stepHistory.next(); Date stepOcurrenceDateReceived = stepOccurenceHistory.getDateReceived(); Date stepOcurrenceDateCompleted = stepOccurenceHistory.getCompletionDate(); while (stepOccurenceHistory.hasNext()) { // Get step work object information // for each step occurrence VWStepWorkObjectHistory stepWorkObjectHistory = stepOccurenceHistory.next(); stepWorkObjectHistory.resetFetch(); // Get participant information for each work object while (stepWorkObjectHistory.hasNext()) { VWParticipantHistory participantHistory = stepWorkObjectHistory.next(); Date participantDateReceived = participantHistory.getDateReceived(); String participantComments = participantHistory.getComments(); String participantUser = participantHistory.getUserName(); String participantName = participantHistory.getParticipantName(); } // while stepWorkObjectHistory } // while stepOccurenceHistory } // while stepHistory } // while workflowHistory } // for workflow maps
164
Each milestone that is defined within a workflow is associated with a level (1 - 99). The workflow-reached milestones are based on the milestone level that is specified. For example, if the milestone level is set to 5, reached-milestones of levels 1 - 5 are retrieved. Example 5-26 and Example 5-27 on page 166 show how to perform the steps required to retrieve the workflow milestones history information, using both the Java API and a PEWS client.
Example 5-26 Get milestones of a workflow using the Java API
// Create session object and log onto Process Engine ... // Get the specific work item ... // Get VWProcess object from work object ... // Get all milestones definition from the workflow process VWMilestoneDefinition[] milestonesDefinition = process.getMilestoneDefinitions(); for (int i = 0; i < milestonesDefinition.length; i++) { // Milestone element information VWMilestoneDefinition milestoneDefinition = milestonesDefinition[i]; String milestoneName = milestoneDefinition.getName(); String milestoneMessage = milestoneDefinition.getMessage(); int milestoneLevel = milestoneDefinition.getLevel(); } // Get reached milestones from the VWProcess object int level = 99; VWWorkflowMilestones milestones = process.fetchReachedWorkflowMilestones(level); while (milestones.hasNext()) { // Milestone element information
165
VWMilestoneElement milestoneElement = milestones.next(); String milestoneName = milestoneElement.getName(); String milestoneMessage = milestoneElement.getMessage(); Date milestoneTimeLogged = milestoneElement.getTimestamp(); }
Example 5-27 Get milestones of a workflow using PEWS
// Create the PEWS RequestSoapContext header ... // Get milestones work object from the roster string rosterName = "DefaultRoster"; string wobnum = "5BDD567B70453C48A5388AC56ABC69E4"; peWS.GetMilestoneForRosterElementRequest query = new peWS.GetMilestoneForRosterElementRequest (); query.milestoneLevel = 99; query.rosterName = rosterName; query.queryValue = wobnum; query.queryEnum = peWS.MilestoneQueryEnum.MILESTONE_QUERY_WOBNUMBER; peWS.Milestone [] milestones = peWSServicePort.getMilestoneForRosterElement(query); if (milestones!=null) { foreach (peWS.Milestone m in milestones) { // Milestone element information string map = m.Map; string milestoneMessage = m.Message; string milestoneName = m.Name; int milestoneId = m.Id; int milestoneLevel = m.Level; int stepId = m.StepId; DateTime milestoneDateReached = m.Reached; } }
166
Chapter 6.
167
168
Available actions
Table 6-1 describes available actions that are provided by the CE_Operations component.
Table 6-1 Available CE_Operations Action File objects Unfile objects Publish document Get object property values Description File one or more objects (documents and custom objects) to a specified folder. Unfile one or more objects (documents and custom objects) from a specified folder. Publish a specified document by using a publishing template. Get single or multiple property values from a supplied document, custom object, or folder. The available methods to get property values support integer, double, date, Boolean, string, and object types. Set single or multiple property values of a supplied document, custom object, or folder. The available methods to set property values support integer, double, date, Boolean, string, and object types. Change the class of a supplied document, folder, or custom object. Delete one or more objects (documents, folders, and custom objects). Check out a specified document from the repository and check in a specified document as a new major version. Copy one or more objects (documents and custom objects) within the same repository. Create a new object (documents, folders, and custom objects) instance using a specified class and property values. For document objects, MIME type and content parameters must be specified Move one or more objects (documents and custom objects) from their existing folder to a specified folder. Get an object (custom object, folder, or document) from a specified repository using a specified path.
Change object class Delete object Document versioning Copy object Create object
169
Description Apply a security template using a specified template to one or more objects (documents, folders, and custom objects). Execute a specified search template or stored search, returning the first object or an array of objects matching the search criteria. Available methods to send mail supporting the following scenarios: Text (plain) with no attachment With documents attached Using a template with no attachment Using a template with documents attached With the URLs of the attached documents appended to the end of the body of the e-mail Using a template with the URLs of the attached documents appended to the end of the body of the e-mail
Send mail
Note: All sendMail methods require that e-mail notification be properly configured by using the Process Task Manager. For further details about how to configure e-mail notification, refer to the following P8 documentation path: ECM Help System Administrator Enterprise-wide Administration Process Task Manager Process Engine Configure Process Engine Email notification.
170
Note: For multithread-safe custom components, concurrent threads may be increased to enable parallel execution of the component on a multiprocessor system, improving the component execution performance. The number of threads for the component can be increased according the number of processors on the system. The custom Java classes serving as a gateway for the component must comply with the following conditions: A constructor that has no parameters. Only public methods are available for the component operations. Public methods exposed as component operations can contain only the following parameter types (single and array): String Date Integer Float Double Boolean VWAttachment VWParticipant
171
/** * DAO class used as business entity for customer-related operations */ public class ITSOCustomerDAO { // Retrieve the content from a ITSOCustomer // document and parse specific meta-data public String[] getCustomerDetailsFromOS(String objectStoreName, String customerID, String[] selectedFields) throws Exception { String[] customerDetails = new String[] {};
172
ITSOUtil itsoUtil = new ITSOUtil(); SearchScope search = new SearchScope(itsoUtil.getCEConnection().fetchOS(objectStoreName)); SearchSQL sql = new SearchSQL(); sql.setSelectList("*"); sql.setFromClauseInitialValue("ITSOCustomer", "d", true); sql.setWhereClause("ITSOCustomerUserId='"+customerID+"' AND NOT (IsClass(d, CodeModule))"); DocumentSet documents = (DocumentSet)search.fetchObjects (sql,Integer.getInteger("1"),null, Boolean.valueOf(true)); Iterator itDoc = documents.iterator(); if (itDoc.hasNext()) { Document doc = (Document) itDoc.next(); ContentElementList contents = doc.get_ContentElements(); ContentElement content; Iterator itContent = contents.iterator(); if (itContent.hasNext()) { content = (ContentElement)itContent.next(); customerDetails = parseCustomerDetailsContent ((ContentTransfer)content, selectedFields); } } return customerDetails; } // Get external database connection from the // custom LoginModule and perform call public Boolean verifyCustomerCredit(String creditCardNumber, Integer requestedAmount) throws Exception { return Boolean.TRUE; } // Additional Customer DAO Methods ... }
173
/** * DAO class used as business entity for vehicle-related operations */ public class ITSOVehicleDAO { public String[] getVehicleMaintananceQueueDetails(String vehicleID, String[] selectedFields) throws Exception { String[] vehicleDetails = new String[] {}; String maintenanceQueue = "ITSO_Maintenance"; ITSOUtil itsoUtil = new ITSOUtil(); VWQueue queue = itsoUtil.getPESession(). getQueue(maintenanceQueue); String queryFilter="ITSOVehicleId=:A"; String[] substitutionVars = {new String(vehicleID)}; int queryFlags = VWQueue.QUERY_READ_LOCKED; int fetchType = VWFetchType.FETCH_TYPE_WORKOBJECT; VWQueueQuery queueQuery = queue.createQuery(null,null,null, queryFlags,queryFilter,substitutionVars,fetchType); if (queueQuery.hasNext()) { vehicleDetails = new String[selectedFields.length]; VWWorkObject workItem = (VWWorkObject) queueQuery.next(); for (int i=0;i<selectedFields.length;i++) vehicleDetails[i] = workItem.getFieldValue (selectedFields[i]).toString(); } return vehicleDetails; } // Additional Vehicle DAO Methods ... }
174
The ITSO_Operations component implements the Java gateway class ITSOOperations to expose the business methods (public methods) and define the component queue operations. The gateway class has a constructor without any parameters and the public methods only contain allowable component operation parameter types. The gateway class consumes the business entities (ITSOVehicleDAO and ITSOConsumerDAO) to perform all business-related logic. See Example 6-3.
Example 6-3 Operations gateway class: ITSOOperations.java /** * Gateway class for ITSO_Operations. */ public class ITSOOperations { public ITSOOperations() { } // Validate the customer's credit from external database system public Boolean verifyCustomerCredit(String creditCardNumber, Integer requestedAmount) throws Exception { return new ITSOCustomerDAO(). verifyCustomerCredit(creditCardNumber, requestedAmount); } // Get customer details from ITSOCustomer // document content using ad-hoc query public String[] getCustomerDetailsFromOS(String objectStoreName, String customerID, String[] selectedFields) throws Exception { return new ITSOCustomerDAO(). getCustomerDetailsFromOS(objectStoreName, customerID, selectedFields); } // Get vehicle maintenance details from the // Process Engine maintenance queue public String[] getVehicleMaintDetails(String vehicleID, String[] selectedFields) throws Exception { return new ITSOVehicleDAO(). getVehicleMaintananceQueueDetails(vehicleID, selectedFields); } // Additional Business Methods ... }
175
The FileNetP8 stanza must be present for any JAAS configuration file containing the appropriate login module to connect to CE, depending on the CE transport protocol. By default, when running outside of an application server, the Content Engine Web Services (CEWS) transport protocol is recommended (com.filenet.api.util.WSILoginModule) because it is typically easier to configure. EJB transport can have performance advantages. The CELogin stanza is used by the CE_Operations component. This login context includes the following login module that provides authentication to CE: com.filenet.wcm.toolkit.server.operations.util.CELoginModule
176
This login module is used in conjunction with the CE 3.x Java Compatibility Layer; therefore, a com.filenet.wcm.api.Session object is initiated using this module. At the minimum, a login context that is used for custom Java components must contain the filenet.vw.server.VWLoginModule module, which authenticates to a PE Isolated Region. This approach means that the provided user information should exist for both the directory server used by the IBM FileNet P8 platform and the custom component. Because ITSO_Operations performs custom CE actions that are not available within CE_Operations, the custom ITSOLogin login context is implemented for the component. The following steps describe how the custom login context is implemented for the ITSO_Operations component: 1. 2. 3. 4. 5. Create ITSOPrincipal class. Create ITSOLoginModule class. Add ITSOLogin login context to taskman.login.config file. Create ITSOUtil class to retrieve the ITSOPrincipal object. Deploy ITSO_Operations component using ITSOLogin context.
ITSOPrincipal implements the java.security.Principal interface, which is used by ITSOLoginModule class. See Example 6-5.
Example 6-5 ITSO_Operations principal class: ITSOPrincipal.java
/** * Principal class for ITSO_Operations */ public class ITSOPrincipal implements Principal, Serializable { private String m_username; private ITSOCEConnection m_ceconnection; public ITSOPrincipal( ITSOCEConnection m_ceconnection, String m_username ) { if( m_username == null ) throw new NullPointerException( "illegal null input" ); this.m_ceconnection = m_ceconnection; this.m_username = m_username; } public ITSOCEConnection getCEConnection()
177
{ return this.m_ceconnection; } public boolean equals( Object o ) { if( o == null ) return false; if( this == o ) return true; if( !(o instanceof ITSOPrincipal) ) return false; ITSOPrincipal that = (ITSOPrincipal) o; if( this.getName().equals( that.getName() ) ) return true; return false; } // Additional ITSOPrincipal methods ... } ITSOLoginModule implements the javax.security.auth.spi.LoginModule interface including the custom CE authentication and passing the connection object to ITSOPrincipal for further handling. See Example 6-6.
Example 6-6 ITSO_Operations login module class: ITSOLoginModule.java
/** * Custom Login Module class for ITSO_Operations. */ public class ITSOLoginModule implements LoginModule { // ITSO Principal private ITSOPrincipal m_principal; public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) { this.m_subject = subject; this.m_callbackHandler = callbackHandler;; this.m_options = options;
178
this.m_sharedState }
= sharedState;
public boolean login() throws LoginException { if (m_callbackHandler == null) { throw new LoginException("Error: no CallbackHandler available to get authentication information"); } String password = null; m_username = (String)m_sharedState.get ("javax.security.auth.login.name"); password = (String)m_sharedState.get ("javax.security.auth.login.password"); if (m_username == null) { Callback[] callbacks = null; callbacks = new Callback[3]; callbacks[0] = new TextOutputCallback(TextOutputCallback. INFORMATION, "Custom Authentication"); callbacks[1] = new NameCallback("user name:"); callbacks[2] = new PasswordCallback("password:", false); try { m_callbackHandler.handle(callbacks); m_username = ((NameCallback)callbacks[1]).getName(); char[] tmpPassword = ((PasswordCallback)callbacks[2]). getPassword(); if (tmpPassword != null) password = new String(tmpPassword); else password = null; ((PasswordCallback)callbacks[2]).clearPassword(); m_sharedState.put("javax.security.auth.login.name", m_username); m_sharedState.put("javax.security.auth.login.password", password); }
179
catch (IOException ioe) { throw new LoginException(ioe.toString()); } catch (UnsupportedCallbackException uce) { throw new LoginException("Error: no CallbackHandler available to get authentication information"); } } try { /** * Perform custom CE authentication */ String ceURI = System.getProperty ("filenet.pe.bootstrap.ceuri"); m_ceconnection = new ITSOCEConnection(m_username, password, "FileNetP8WSI", ceURI); } catch (Exception e) { m_ceconnection = null; throw new LoginException(e.toString()); } m_validSession = true; return (m_validSession); } public boolean commit() throws LoginException { if(m_ceconnection == null) return false; m_principal = new ITSOPrincipal(m_ceconnection, m_username); if(!m_subject.getPrivateCredentials().contains(m_principal)) m_subject.getPrivateCredentials().add(m_principal); return true; } // Additional ITSOLoginModule methods ... }
180
ITSOLogin is the custom login context appended to taskman.login.config file that is used by the ITSO_Operations component. See Example 6-7.
Example 6-7 JAAS custom login context implemented for ITSO_Operations
ITSOLogin { filenet.vw.server.VWLoginModule required; itso.autorental.components.authentication.ITSOLoginModule required debug=true; }; The ITSOUtil class is a custom class that is implemented to retrieve the ITSOPrincipal, including the custom CE authenticated object. A method to retrieve the PE session object (VWSession) is also implemented for custom PE-related operations. See Example 6-8.
Example 6-8 ITSO_Operations class to retrieve ITSOPrincipal: ITSOUtil.java
/** * Utility class for ITSO_Operations. */ public class ITSOUtil { private VWSession pesession = null; public VWSession getPESession() throws Exception { if(this.pesession == null || !(this.pesession.isLoggedOn())) { Subject subject = Subject.getSubject(AccessController.getContext()); Set creds = subject.getPrivateCredentials (Class.forName("filenet.vw.api.VWSession")); Iterator i = null; if (creds != null) i = creds.iterator(); if (i != null) this.pesession = (VWSession) i.next(); } return this.pesession; } public ITSOCEConnection getCEConnection() throws Exception { Subject subject Subject.getSubject (AccessController.getContext()); Set set = null; try {
181
set = subject.getPrivateCredentials(Class.forName ("itso.autorental.components.authentication.ITSOPrincipal")); } catch(Exception exception) { } if(set == null) throw new Exception("Failed to find principal"); Iterator iterator = set.iterator(); if(iterator == null || !iterator.hasNext()) throw new Exception("Failed to find principal"); Principal principal = (Principal)iterator.next(); if(!(principal instanceof ITSOPrincipal)) throw new Exception("Failed to find principal"); else return ((ITSOPrincipal)principal).getCEConnection(); } }
182
Description JAAS password Name of the component queue gateway class (Optional) Names of the methods of the classes to be imported as the component queue operations. If not specified, all public methods of the class are imported as operations for the queue
To use filenet.vw.integrator.base.PEComponentQueueHelper tool in Eclipse, perform the following steps (see Figure 6-2): 1. Create a run configuration for the tool. 2. Enter PEComponentQueueHelper for name and enter filenet.vw.integrator.base.PEComponentQueueHelper for the main class.
3. On the Arguments tab, set the following values by using the information in Table 6-3. Replace the parameter values with that of your environment. For an example, see Figure 6-3 on page 184.
Table 6-3 Parameters for PEComponentQueueHelper Program arguments VM arguments /PEuser administrator /PEpw filenet /PErouter CEPoint /queue ITSO_Operations /user administrator /pw filenet /JAAS ITSOLogin /class itso.autorental.components.ITSOOperations -Djava.security.auth.login.config=${workspace_loc}/P8Librarie s/CE_API/config/jaas.conf.WSI -Dwasp.location=${workspace_loc}/P8Libraries/CE_API/wsi -Dfilenet.pe.bootstrap.ceuri=http://CEServer:CEPort/wsi/FNCEW S40DIME/
183
4. Run PEComponentQueueHelper and use the Process Configuration Console to verify that the component queue is created with the specified component name (ITSO_Operations), JAAS information, and operations.
184
Table 6-4 Component Manager parameters description Parameter /named /routerURL=PEConnectio nPointName /username=PEUsername /password=PEPassword /registryPort=32771 Description Specifies the component manager name. Parameter is optional. Specifies the connection point name to access the PE. Specifies PE user name. Specifies PE password. Specifies the RMI registry port to register the Component Manager instance. The default value is 32771. This parameter allows the AE Process Task Manager to manage the instance The Component Manager can be set up to receive notification from the PE server when work arrives at any component queues. This approach avoids excessive polling. However, only one instance can be set up to receive notification. The default value is 32773 Specifies the Component Manager RMI server name; it must be unique within the same RMI registry. When AE Process Task Manager starts, by default, the parameter is: FileNet.VW.VWComponentManager.<connectionPointNam e>.<queueName> For example:
/eventPort=32773
FileNet.VW.VWComponentManager.hqruby_600.CE_ Operations
/queues=queueName /unbind Specifies all the queues (using a value of *), a specific queue, or a list of queues separated by comma. When present, this stops the current instance that has the RMI registry object with the specified /registryName
To set up Eclipse to run Component Manager, which allows for an easy way to debug the component, perform the following steps: 1. Create a run configuration for Component Manager. 2. Enter Component Manager START for name and enter filenet.vw.integrator.base.VWComponentManager for the main class. See Figure 6-4 on page 186.
185
3. On the Arguments tab, set the values by using the information in Table 6-5. Replace the parameter values with that of your environment. For an example, see Figure 6-5.
Table 6-5 Parameter for Component Manager START Program arguments /named /routerURL CEPoint /userName administrator /password filenet /registryPort 32771 /eventPort 32773 /registryName FileNet.VW.VWComponentManager.ITSO_Operations /queues=ITSO_Operations -Djava.security.auth.login.config=${workspace_loc}/config/t askman.login.config -Dwasp.location=${workspace_loc}/P8Libraries/CE_API/wsi -Dfilenet.pe.bootstrap.ceuri=http://CEServer:CEPort/wsi/FNC EWS40DIME/
VM arguments
186
4. Before running the Component Manager, ensure that all other Component Manager instances for the same PE connection point have been stopped. Otherwise, work in the queue is picked up and processed by those instances. Create a run configuration to stop Component Manager by duplicating the Component Manager START run configuration, and name it Component Manager STOP. Add /unbind to the program arguments as shown in Figure 6-6.
Run the Component Manager STOP configuration to stop the running Component Manager instance. 5. Run Component Manager START in debug mode to start debugging and testing the component (ITSO_Operations) operations. Make sure to add a breakpoint to the intended component section (or sections) to be debugged.
187
In this section, we present information for using PE Java API and REST API to access the application space, role, and workbasket.
// Create session object and log onto Process Engine ... String appSpaceName = "GenericApproval"; // Fetch the roles from session using the application space name VWRole roles[] = session.fetchMyRoles(appSpaceName); for(int i = 0; i < roles.length; i++) { System.out.println("Role Name:" + roles[i].getName()); System.out.println("AuthoredName:" + roles[i].getAuthoredName()); }
// Ensure to be authenticated with the Application Server container var baseURL = "http://localhost:9080/WorkplaceXT/P8BPMREST/p8/bpm/v1/"; var applicationSpaceName = "GenericApproval"; // Construct the URI for roles var url = baseURL + "appspaces/" + applicationSpaceName + "/myroles"; // Use GET method to retrieve the roles
188
dojo.xhrGet({ url: url, handleAs: "json-comment-optional", load: function(data) { // Callback to handle the data for(var roleName in data) { var role = data[roleName]; console.log("AuthoredName:" + roleName); console.log("Display Name:" + role.name); console.log("URI:" + role.URI); } }, error: function(data) { // The error callback console.dir(data); } } );
189
// Create session object and log onto Process Engine ... VWRole role; String roleName = "Approver"; String appSpaceName = "GenericApproval"; role = session.fetchMyRole(roleName, appSpaceName); System.out.println("name:" + role.getName()); System.out.println("authoredName:" + role.getAuthoredName()); System.out.println("description:" + role.getDescription()); System.out.println("homePage:" + role.getHomePageURL()); filenet.vw.api.VWRole.WorkBasketReference wbs[] = role.getWorkBasketReferences(); // Process the workbasketsif(wbs != null) { for(int i = 0; i < wbs.length; i++) { System.out.println("Workbasket name:" + wbs[i].getWorkBasketName()); System.out.println("Queue name:" + wbs[i].getWorkBasketName()); System.out.println("Workbasket authoredName:" + wbs[i].getWorkBasketAuthoredName()); } } VWAttributeInfo info = role.getAttributeInfo(); String names[] = info.getAttributeNames(); for(int i = 0; i < names.length; i++) { String fieldName = names[i]; Integer filedType = info.getFieldType(fieldName); Boolean isArray = new Boolean(info.isFieldArray(fieldName)); Object object = info.getFieldValue(fieldName); // Print out the role attribute value }
190
Example 6-12 shows how to retrieve role with a Dojo toolkit client.
Example 6-12 Retrieve role with a Dojo toolkit client
// Ensure to be authenticated with the Application Server container var baseURL = "http://localhost:9080/WorkplaceXT/P8BPMREST/p8/bpm/v1/"; var applicationSpaceName = "GenericApprovalGenericApproval"; var roleName = "Approver"; // Construct the URI for role var url = baseURL + "appspaces/" + applicationSpaceName + "/roles/" + roleName; // Use GET method to retrieve the roles dojo.xhrGet({ url: url, handleAs: "json-comment-optional", load: function(data) { var role = data; console.log("HomePage:" + role.homePage); console.log("Description: " + role.description); console.log("Display Name: " + role.name); console.log("AuthoredName: " + role.authoredName); console.log("Attributes: " + role.attributes); var workbaskets = role.workbaskets; // Process the workbaskets for (var workbasketName in workbaskets) { var workbasket = workbaskets[workbasketName]; console.log("Workbasket Display Name:" + workbasket.name); console.log("Workbasket URI:" + workbasket.URI); console.log("Workbasket AuthoredName:" + workbasketName); } }, error: function(data) { // The error callback console.dir(data); } } );
191
// Create session object and log onto Process Engine ... String queueName = "GenericApprovalQueue"; String workbasketName = "Approve"; VWWorkBasket workbasket; VWQueue queue = session.getQueue(queueName); workbasket = queue.fetchWorkBasket(workbasketName); System.out.println("Workbasket name:" + workbasket.getName()); System.out.println("Workbasket authoredName:" + workbasket.getAuthoredName()); System.out.println("Workbasket description:" + workbasket.getDescription()); // retrieve the columns filenet.vw.api.VWWorkBasket.Column columns[] = workbasket.getColumns(); if(columns != null) { for(int i = 0; i < columns.length; i++) { String name = columns[i].getName(); String authoredName = columns[i].getAuthoredName(); String prompt = columns[i].getPrompt(); int type = columns[i].getType(); boolean isSortable = columns[i].isSortable(); } } // Retrieve the filers filenet.vw.api.VWWorkBasket.Filter filters[] = workbasket.getFilters();
192
if(filters != null) { for(int i = 0; i < filters.length; i++) { String filterName = filters[i].getName(); String authoredFilterName = filters[i].getAuthoredName(); String description = filters[i].getDescription(); String prompt = filters[i].getPrompt(); int type = filters[i].getType(); int operator = filters[i].getOperator(); } }
// Ensure to be authenticated with the Application Server container var baseURL = "http://localhost:9080/WorkplaceXT/P8BPMREST/p8/bpm/v1/"; var queueName = "GenericApprovalQueue"; var workbasketName = "Approve"; var url = baseURL + "queues/" + queueName + "/workbaskets/" + workbasketName; // Use GET method to retrieve dojo.xhrGet({ url: url, handleAs: "json-comment-optional", load: function(data) { var workbasket = data; var columns = workbasket.columns; var filters = workbasket.filters; var description = workbasket.description; var displayName = workbasket.name; var authoredName = workbasket.authoredName; // Print the columns for (var columnName in columns) { var column = columns[columnName]; console.log("Column DisplayName:" + column.name); console.log("Sortable:" + column.sortable);
193
console.log("Type:" + column.type); console.log("Prompt:" + column.prompt); console.log("Ordinal:" + column.ordinal); } // Print the filters for (var filterName in filters) { var filter = filters[filterName]; console.log("Filter DisplayName:" + filter.name); console.log("Type:" + filter.type); console.log("Description:" + filter.description); console.log("Prompt:" + filter.prompt); console.log("Operator:" + filter.operator); console.log("Attributes URL:" + filter.attributes); } }, sync: true, error: function(data) { // The error callback console.dir(data); } } );
194
// Create session object and log onto Process Engine ... String queueName = "GenericApproval"; String workbasketName = "Index"; VWWorkBasket workbasket; // the filter condition String[] filterNames = {"CompanyName"}; String[] subsVars = {"XYZ"}; // Get the Queue VWQueue queue = session.getQueue(queueName); // Get the Workbasket workbasket = queue.fetchWorkBasket(workbasketName); int pageSize = 4; System.out.println("Workbasket name:" + workbasket.getName()); System.out.println("Workbasket authoredName:" + workbasket.getAuthoredName()); System.out.println("Workbasket description:" + workbasket.getDescription()); // Query the first page filenet.vw.api.VWWorkBasket.QueryResults results = workbasket .fetchNextBatch( VWQueue.QUERY_READ_LOCKED, // queryFlags pageSize, // buffer_size null, // sort column filterNames, // filter names subsVars, // subsitution vars null, // last record 3 // fetch type, 3 means Queue element ); Object queueElements[] = null; String lastRecord = null; int pageNumber = 1; while (results != null) {
195
// save the last record to a local variable // it will be used to query the next page lastRecord = results.getLastRecord(); queueElements = results.getWorkObjects(); System.out.println("Process page: " + pageNumber); for (int i = 0; i < queueElements.length; i++) { VWQueueElement qe = (VWQueueElement) queueElements[i]; System.out.println("WobNumber:" + qe.getWorkObjectNumber()); System.out.println("QueueName:" + qe.getQueueName()); System.out.println("StepName:" + qe.getStepName()); filenet.vw.api.VWWorkBasket.Column columns[] = workbasket.getColumns(); if (columns != null) { for (int j = 0; j < columns.length; j++) { String name = columns[j].getAuthoredName(); System.out.println("name:" + name); Object value = qe.getDataField(name).getValue(); // Print out the value System.out.println("Value:" + value.toString()); } } } results = workbasket.fetchNextBatch( VWQueue.QUERY_READ_LOCKED, // pageSize, // null, // filterNames, // subsVars, // lastRecord, // 3 // element ); System.out.println("Next page"); pageNumber++; }
queryFlags buffer_size sort column filter names subsitution vars last record fetch type, 3 means Queue
196
var url = baseURL + "queues/" + queueName + "/workbaskets/" + workbasketName + "/queueelements"; // Helper method to print the queue elements var printQueueElements = function(queueElements) { dojo.forEach( queueElements, function(queueElement) { console.log("workObjectNumber:" + queueElement.workObjectNumber); console.log("queueName:" + queueElement.queueName); console.log("lockedById:" + queueElement.lockedById); console.log("lockedBy:" + queueElement.lockedBy); console.log("ETag:" + queueElement.ETag); console.log("stepElementURL:" + queueElement.stepElement); for (var columnName in queueElement.columns) { var columnValue = queueElement.columns[columnName]; console.log("columnName:" + columnName); console.log("columnValue:" + columnValue); } }, this); }; // Construct the query parameters var queryData = "pageSize=" + pageSize + "&queryFlags=1";
197
var lastRecord; var queueElements; var pageNumber = 1; // Query the first page dojo.rawXhrPost({ url: url, handleAs: "json-comment-optional", load: function(data) { lastRecord = data.lastRecord; queueElements = data.queueElements; printQueueElements(queueElements); pageNumber++; }, _raw: true, sync: true, postData: queryData, error: function(data) { // The error callback console.dir(data); } } ); // Query the next page while(queueElements && queueElements.length > 0) { // Construct the query parameters // the lastRecord will be used to fetch the next batch result queryData = "pageSize=" + pageSize + "&queryFlags=1&lastRecord=" + lastRecord; dojo.rawXhrPost({ url: url, handleAs: "json-comment-optional", load: function(data) { lastRecord = data.lastRecord; queueElements = data.queueElements; printQueueElements(queueElements); pageNumber++; }, _raw: true, sync: true, postData: queryData, error: function(data) { // The error callback console.dir(data); } } ); }
198
var baseURL = "http://localhost:9080/WorkplaceXT/P8BPMREST/p8/bpm/v1/"; var applicationSpaceName = "GenericApproval"; // Construct the URI for the initial myroles resource var url = baseURL + "appspaces/" + applicationSpaceName + "/myroles"; var roleURI = null; var workbasketURI = null; // Use GET method to retrieve myroles, // Save the first role's resource URI to local variable dojo.xhrGet({ url: url, handleAs: "json-comment-optional", load: function(data) { // Callback to handle the data for(var roleName in data) { var role = data[roleName]; console.log("AuthoredName:" + roleName); console.log("Display Name:" + role.name); console.log("URI:" + role.URI); // construct the complete role URI roleURI = baseURL + role.URI; break; } }, sync: true, error: function(data) {
199
// The error callback console.dir(data); } } ); if (roleURI === null) { console.log("roleURI is empty."); return; } // Use the saved URI and GET method to retrieve role resource // Save the URI of the first Workbasket to a local variable dojo.xhrGet({ url: roleURI, handleAs: "json-comment-optional", load: function(data) { var role = data; console.log("HomePage:" + role.homePage); console.log("Description: " + role.description); console.log("Display Name: " + role.name); console.log("AuthoredName: " + role.authoredName); console.log("Attributes: " + role.attributes); var workbaskets = role.workbaskets; for (var workbasketName in workbaskets) { var workbasket = workbaskets[workbasketName]; console.log("Workbasket Display Name:" + workbasket.name); console.log("Workbasket URI:" + workbasket.URI); console.log("Workbasket AuthoredName:" + workbasketName); // construct the complete workbasket URI workbasketURI = baseURL + workbasket.URI; break; } }, sync: true, error: function(data) { // The error callback console.dir(data); } } ); if (workbasketURI === null) {
200
console.log("workbasketURI is empty."); return; } // Use GET method to retrieve the information of the workbasket dojo.xhrGet({ url: workbasketURI, handleAs: "json-comment-optional", load: function(data) { var workbasket = data; var columns = workbasket.columns; var filters = workbasket.filters; var description = workbasket.description; var displayName = workbasket.name; var authoredName = workbasket.authoredName; // print out the columns and filters // ... }, sync: true, error: function(data) { // The error callback console.dir(data); } } );
201
Widget
ECM Widgets is a collection of widgets to assemble user interfaces for IBM enterprise content management and business process management applications. In the context of ECM Widgets, a widget means a user interface component that follows the iWidget specification. For information about the iWidget specification, see the IBM Mashup Center wiki: http://www.lotus.com/ldd/mashupswiki.nsf/dx/widget-programming-guide
In-basket
In the context of ECM Widgets, In-basket has the same meaning as the workbasket that is defined in PE.
Events
All widgets that follow the iWidget specification communicate with each other through an event mechanism. The two types of events are: published event and handled event. For example, when a user clicks a button in Widget A, an event is published to another Widget B. To enable Widget B to subscribe to events sent from Widget A, you must wire Widget A with Widget B. This process is called wiring widgets. WebSphere Business Space has a graphical user interface (GUI) that allows you to wire the widgets.
Pages
The three types of mashup pages for ECM Widgets are: My Work page, Step Processor Page, and Single Page application. A My Work page is a top-level page that displays one or more In-baskets for selecting work items. Figure 6-7 on page 203 shows an example of My Work page.
202
A Step Processor Page is used to process a work item selected from an In-basket. A step processor page exists for each step in a workflow. Figure 6-8 shows an example.
203
ECM Widgets also support a Single Page application. This means that all widgets are put into one mashup page, and no page-switching exists when a user opens a work item. Figure 6-9 shows an example.
In-basket widget
The In-basket widget displays a list of In-baskets that belong to the current role. When you open an In-basket, it displays a list of work items according to the configuration defined in PE. When you double click a work item from the In-basket widget, it triggers an event as a notification that the user wants to open the work item. The In-basket widget can be placed on the My Work page or a Single Page application.
204
broadcast the work item to other widgets, such as Attachment and Work Data widget.
Attachment widget
The Attachment widget displays attachment lists that are grouped by workflow fields. It provides document-related functions: checkout, checkin, cancel checkout, view, properties, download, and remove attachment.
Viewer widget
The Viewer widget wraps the WorkplaceXT Image Viewer applet for displaying document attachments.
205
206
Figure 6-11 Get Next In-basket Widget working with the other ECM Widgets
207
payload to the Step Completion widget. In turn, the Step Completion widget, Work Data widget, and Attachment widget will work on the next work item. Figure 6-12 illustrates the use case sequence diagram.
208
2. In the next dialog, specify the project name SampleECMWidgets (Figure 6-14 on page 210) and then click Finish to create the project. In the created project, you will be able to edit the source code for this sample widget.
209
210
As shown in Figure 6-15, the code for the Get Next widget is divided into three files: GetNext.xml This file is the XML definition for the widget. GetNext.js This file contains the JavaScript logic to control the behavior of the widget. GetNext.css This file contains the look and feel of the widget. You need to add your cascading style sheet (CSS) definitions into this file.
211
Table 6-6 Widget attributes Attribute name bpmServiceBaseUrl Description The base URL for PE REST Service. To simplify the sample code, we do not provide a GUI to configure this value. If you want to change it, modify the default value stored in GetNext.xml. The application space name for retrieving role list. To simplify the sample code, we do not provide a GUI to configure this value. If you want to change it, modify the default value stored in GetNext.xml. The In-basket name used to retrieve queue elements. You can configure this value in the configuration panel of the Get Next widget. The URL of the queue elements resource. After you configure the role name and In-basket name in configuration panel, the URL of the queue elements resource for the selected In-basket will be saved into mashup page.
applicationSpaceName
inbasketName
queueElementsUrl
"Send Work Item Id" event This is a published event. The three scenarios that trigger this event are: The Get Next widget loads the first queue element. A user clicks the Get Next button. The Get Next widget receives a "Receive Close Step Processor" event. "Receive Close Step Processor" event This is a handled event. If you wire the Step Completion widget with the Get Next widget using this event, when a user clicks the Complete button in the Step Completion widget, an event will be published from the Step Completion widget to the Get Next widget. As defined in the onEvent attribute of this event, the event handler is "handleReceiveCloseStepProcessor" and which is a JavaScript function declared in the GetNext.js file.
Example 6-18 GetNext.xml
<iw:iwidget name="GetNext" xmlns:iw="http://www.ibm.com/xmlns/prod/iWidget" iScope="com.ibm.im.ecmwidgets.sample.GetNext" allowInstanceContent="true" supportedModes="view edit" mode="view"> <iw:resource uri="GetNext.js"/> <iw:resource uri="GetNext.css"/> <iw:itemSet id="attributes">
212
<iw:item id="bpmServiceBaseUrl" value="/WorkplaceXT/P8BPMREST/p8/bpm/v1"/> <iw:item id="applicationSpaceName" value="GenericApproval"/> <iw:item id="inbasketName" value=""/> <iw:item id="queueElementsUrl" value=""/> </iw:itemSet> <iw:payloadDef name="WorkItemId"> .... </iw:payloadDef> <iw:event id="Send Work Item Id" published="true" eventDescName="SendWorkItemIdDescription"/> <iw:eventDescription id="SendWorkItemIdDescription" payloadType="WorkItemId" description="" lang="en"/> <iw:payloadDef name="WorkItem"> ... </iw:payloadDef> <iw:payloadDef name="CloseStepProcessor"></iw:payloadDef> <iw:event id="Receive Close Step Processor" handled="true" onEvent="handleReceiveCloseStepProcessor" eventDescName="ReceiveCloseStepProcessorDescription"/> <iw:eventDescription id="ReceiveCloseStepProcessorDescription" payloadType="CloseStepProcessor" description="" lang="en"/> <iw:content mode="view"> <![CDATA[ <div id="_IWID_viewModeContent" class="ecmwdgt ecmwdgtViewModeContent ecmwdgtGetNext"></div> ]]> </iw:content> <iw:content mode="edit"> <![CDATA[ <div id="_IWID_editModeContent" class="ecmwdgt ecmwdgtEditModeContent ecmwdgtGetNext"></div> ]]> </iw:content> </iw:iwidget>
213
dojo.provide("com.ibm.im.ecmwidgets.sample.GetNext"); dojo.declare("com.ibm.im.ecmwidgets.sample.GetNext", null, { onLoad: function(){ // Will be invoked when mashup container loads this widget. }, onview: function(){ // Will be invoked when widget shows the view mode pane. this._renderViewModeContentNode(); }, onedit: function() { // Will be invoded when widget shows the edit mode pane. this._renderEditModeContentNode(); }, handleReceiveCloseStepProcessor: function() { // Handle the incoming Close Step Processor event. this._getNextQueueElement(); }, _getNextQueueElement: function() { // Get the next queue element and publish the // Send Work Item Id event. }, _renderEditModeContentNode: function() { // Render the edit mode content pane. }, _renderViewModeContentNode: function() { // Render the view mode content pane. }, _request: function(method, xhrArgs) { // This is the helper method that request Ajax request to PE REST // service. } });
214
215
console.error("No target xhr url"); var deferred = new dojo.Deferred(); deferred.errback(); return deferred; } xhrArgs.url = this.bpmServiceBaseUrl + "/" + xhrArgs.url; return dojo[method](xhrArgs); } The _getNextQueueElement function is called when the Get Next widget wants to fetch the next queue element. This method constructs the URL for the queue element resource and registers a callback function _getNextQueueElementCallback to handle the return result. It then initiates the request by calling the _request function. See Example 6-21.
Example 6-21 _getNextQueueElement method
_getNextQueueElement: function() { console.debug("[" + this.declaredClass + "." + arguments.callee.nom + "]"); var postData = "pageSize=1&queryFlags=1"; if (this.lastRecord) { postData += "&lastRecord=" + encodeURIComponent(this.lastRecord); } this._request("rawXhrPost", { url: this.queueElementsUrl, handleAs: "json", headers: { "Content-Type": "application/x-www-form-urlencoded" }, postData: postData }).addCallback(this, "_getNextQueueElementCallback"); }, The _getNextQueueElementCallback function handles the result coming from the PE REST service, getting the next queue element and publishing the data through the "Send Work Item Id" event. As a result, the target widget will be invoked to handle the incoming work item ID payload. See Example 6-22 on page 217.
216
_getNextQueueElementCallback: function(result) { this.lastRecord = result.lastRecord; var queueElements = result.queueElements; if (!queueElements) { console.info("No more work items."); return; } var queueElement = queueElements[0]; var lockedById = queueElement.lockedById; if (lockedById !== 0 && lockedById !== this.currentUserId) { console.info("Work item is locked by another user: " + lockedById); return this._getNextQueueElement(); } var workItemId = { queueName: queueElement.queueName, workObjectNumber: queueElement.workObjectNumber }; this.iContext.iEvents.fireEvent("Send Work Item Id", "WorkItemId", workItemId); this.workItemIdNode.innerHTML = queueElement.workObjectNumber; },
217
2. Deploy the WAR file to WebSphere. The context root for the deployed Web application should be SampleECMWidgets. 3. Stop the Web application of WebSphere Business Space. 4. Copy the widget registration file of the Get Next widget to the Business Spaces registry data directory. You can find the sample registration file in the sample widget application that you download from IBM Redbooks Web server. Refer to Appendix A, Additional material on page 315 to locate the information. 5. Start the Web application of Business Space. If you deploy the Get Next widget successfully, the widget appears in the widget toolbox of Business Space (Figure 6-19 on page 219) and you can drag and drop the Get Next widget into a mashup page.
218
2. Drag and drop the Get Next In-basket, Step Completion, Work Data, Attachment, and Viewer widgets to the page. See Figure 6-21 on page 220.
219
3. Wire the Get Next In-basket widget with the Step Completion widget by the "Send Work Item Id" published event and "Receive Work Item Id" handled event. See Figure 6-22 for the widget wiring.
Figure 6-22 Wire Get Next and Step Completion by Send Work Item Id and Receive Work Item Id events
4. Wire the Step Completion widget with the Get Next widget by the "Send Close Step Processor" published event and "Receive Close Step Processor" received event. See Figure 6-23 for the widget wiring.
Figure 6-23 Wire Step Completion and Get Next by Send Work Item Id and Receive Work Item Id events
220
5. Open the configuration panel of the Get Next widget, select a role name and an In-basket name. See Figure 6-24. Click Save. As a result, the Get Next widget starts to run and the other widgets display the content of current work item.
221
222
Chapter 7.
223
224
software, but we developed the sample without it because we believe it is somewhat easier to follow as sample code. If we were to develop this as a production application, we would definitely follow best practices for globalization and localization. Likewise, and for similar reasons, the sample applications do not adhere to best practices for accessibility. That would also be necessary and desirable for production applications.
225
226
If not a member, the user must register in the system. Figure 7-2 shows the registration panel. The user must enter his or her information including a new user ID and password that are required when reserving a vehicle from this application.
227
Figure 7-3 shows the main reservation data panel. This is where the user can select where and when to pick up the automobile.
After the user selects where and when to rent a vehicle, the system displays a list of available vehicles to be rented during this period of time in that location, as shown in Figure 7-4. The user selects a vehicle of his or her choice. Each vehicle has a photo associated with it, a brief description, and a daily rate for rental.
228
After selecting the rental vehicle, the user enters the information of the credit card that is used for the reservation. Figure 7-5 shows the credit card information collection panel.
Figure 7-5 Reservation Web application credit card information collection panel
229
When the reservation is complete, the system displays a reservation confirmation panel. Figure 7-6 shows the confirmation panel for a successful rental reservation.
230
At the rental counter when picking up a car, the customer enters the rental car confirmation number (provided in the confirmation panel as shown in Figure 7-6). The Kiosk application matches the confirmation number to the reservation and (in reality) physically delivers the keys and rental paperwork to the customer. In our samples however, the Kiosk application simulates delivery of the keys and paperwork by supplying two codes. One code identifies the vehicle being rented, and the other code represents this specific rental transaction. Figure 7-7 shows the interface for Rental Kiosk application where the user enters the rental car confirmation number.
Figure 7-8 shows the rental information based on the confirmation number entered.
231
When a vehicle returns to the rental lot, a sensor scans a vehicle bar code from a window sticker. We simulate this by having the user enter the code using the keyboard. See Figure 7-9.
232
using IBM FileNet P8 system. As part of the sample, we do not provide an implementation of the Kiosk application used by the vehicle technicians to record low-level maintenance details (for example, parts used and breakdown of labor), but we do provide a Web application used by the maintenance supervisor to accept, schedule, and release vehicles. The same Web application is used by rental office staff because maintenance is just one aspect of tracking vehicle availability. The Fleet Status Manager Web application provides the following functions: A fleet status dashboard mode provides a summary of the status of all vehicles in the inventory (for example, out for rental, idle, in maintenance). A vehicle may be put into maintenance status by authorized employees. This can be well before the vehicle is actually moved to the maintenance area. The effect is that the vehicle is unavailable for future rentals during this period. The Kiosk application is used to scan the window sticker bar code as the vehicle is moved physically into or out of the maintenance area. We do not show that aspect in the sample application. An authorized maintenance employee may enter or update a maintenance substatus for the vehicle (for example, waiting for parts, working, sent to external service vendor). Most substatus changes require an estimated completion time for that status. An authorized maintenance employee may take a vehicle out of maintenance status, typically to return it to service. As a special case of the maintenance application, newly-acquired vehicles are added to the inventory and scheduled for an initial maintenance examination. Likewise, when a vehicle is being sold or disposed of, it gets a final maintenance inspection as it is removed from the active inventory. Several screen captures of this Fleet Status Manager Web Application are shown in the remaining figures in this section.
233
Figure 7-10 shows the Fleet Status Dashboard page, which lists vehicles in inventory and their status. Supervisor users have access to this page through security roles.
234
When the supervisor selects one of the vehicles from the inventory, the vehicle information appears, as shown in Figure 7-11. The supervisor can then send the vehicle to maintenance.
When a maintenance worker logs into this application, the worker is routed to a page that lists the vehicles in the maintenance group queue as well as those in that specific workers inbox queue. These vehicles are represented by Process Engine (PE) work items. Figure 7-12 shows a typical page that a maintenance worker sees after logging in.
235
The maintenance worker can select a vehicle from the Unassigned Work Items list, and route the item to his or her own work queue. See Figure 7-13.
Figure 7-13 Maintenance worker page: route work item to workers work queue
After the vehicle is in the maintenance workers work queue, the maintenance worker can complete the work item or send it back to the group queue. See Figure 7-14.
236
Figure 7-15 shows the maintenance queues page when logging in as a different maintenance worker. The purpose of this picture is to show that the group queue work items are available to all users who have access to this queue, although the users inbox only shows that users assigned work items.
All of these work items can be tracked by using the Process Administrator applet in WorkplaceXT. Figure 7-16 shows the maintenance work items in the roster. The F_BoundUser column shows which users inbox that the work item is assigned to.
237
The Billing Report application provides the following functions: Summary and details of all vehicle hours by status (for example, out for rental, idle, and in maintenance). Summary and details of all payments made (credit card charges) for completed rentals. Summary and details of all maintenance expenses (parts, labor, third party). Exception report of all unusual events (for example, vehicle not ready when promised to a customer, vehicle overdue for return, vehicle entering non-routine maintenance). In the sample application, we only show the summary and details report for vehicles hours by status. Several screen captures of this Billing report application are shown in the remaining figures in this section. Figure 7-17 shows the login dialog for this application. The user must enter an IBM FileNet P8 user ID and password to log in.
If the user enters wrong information, the Billing Report application raises an error message, as shown in Figure 7-18.
After login, the user provides the start date and end date to generate the report. Figure 7-19 shows the generated report displayed in the Billing Report
238
application. The vehicle hours report contains two sections: Summary Report and Detailed Report. The Summary Report lists the total hours and total numbers of activities for the various status types of the vehicle. By clicking a row in Summary Report, the Detailed Report is refreshed and lists the corresponding detailed information.
For this sample application, we did not implement the Print Report function.
239
They can be inferred from the attribute data types in the diagrams and also from the explanatory material in the tables in this chapter. The data file for the UML diagrams (created with IBM Rational Software Architect 7.5) is included in the downloadable material that accompanies this book, in file: sg247743-sample/CEartifacts/FictionalAutoRentalCompanyADataModel.emx In the diagrams and in the explanations that follow, we use the class and property symbolic names. These are the unique, case-insensitive, non-localizable names that are used by applications. Classes and properties also have localizable display names. A common general pattern for display names is to create the English version by removing the prefix from the symbolic name and inserting spaces between words in the symbolic name. For example, a symbolic name of ITSOVehicleActivity could have a display name of Vehicle Activity. In the data import files for the sample applications, we use display names that are the same as the symbolic names. Figure 7-20 shows the model for ITSODocument class and its subclasses.
240
Figure 7-21 shows the models for ITSOFolder, ITSOAnnotation, and their subclasses.
241
Figure 7-22 shows the model for ITSOCustomObject and its subclasses.
242
243
Table 7-1 ITSODocument, ITSOFolder, ITSOCustomObject, ITSOAnnotation Class: ITSODocument, ITSOFolder, ITSOCustomObject, ITSOAnnotation Property ITSOFranchiseCode Type String(10) Comment Value required. Franchise identity code is always normalized to lowercase. A pseudo-code of itsoautohq is for the company headquarters. Most objects have a single pointer to an ITSORole object for security inheritance purposes. Even objects which are publicly visible have a value here for simplified administration.
ITSOSecurityProxy
OVP (ITSORole)
Folders must exist at a single place in a strictly hierarchical namespace. All folders of any kind for these applications are under the top-level folder /ITSOAutoRental/. A franchise has a franchise identity code, and folders specific to a particular franchise are placed under a subfolder named after the franchise code. For example, a franchise with identity code ought2 would have all its folders under /ITSOAutoRental/ought2/.
7.4.2 ITSOVechicle
This class acts as a collector of information about many things that are related to a specific physical vehicle. Examples of these assorted things include scanned images of legal documents related to ownership and registration, photographs, and accident reports. Because it acts as a collecting point for many different types of things, it is modelled as a folder object. Various documents of unpredictable types may be filed into a folder for a specific vehicle. A large franchise may have hundreds of vehicles in inventory, so browsing folders as a way of searching for vehicles is not very practical. We instead expect the applications to identify a particular vehicle through a search and then use the corresponding folder as a paradigm for navigating to related documents. Each vehicle has a unique identity code. That identity code is used as the name of the ITSOVehicle folder. To facilitate occasional browsing navigation, the ITSOVehicle folders are filed into subfolders that are named for the character in the ninth position of the identity code (all of which are filed under a vehicles subfolder). If no ninth character exists, the last non-space character is used. If that character is a letter, it is converted to lowercase. For example, a vehicle with
244
an identity code of JT4TN12D8V0030519 could be represented by a folder with the following path: /ITSOAutoRental/ought2/vehicles/8/JT4TN12D8V0030519 Allowing at least 17 characters for the identity code allows for the direct use of the industry standard Vehicle Identification Number (VIN). Position 9 of the VIN is a check digit and thus well-distributed; it has eleven possible values (digits 0 - 9, letter X). Because of the unique inventories of the company franchisees, they might have older vehicles without a VIN, or with a VIN in a different format. Much of the provenance information for a vehicle (for example, year, make, and model of manufacture) can be extracted by decoding a standard VIN, but it must be explicitly provided for other types of identity codes. For purposes of the sample application, we assume that all vehicles have a VIN and the ITSOVehicleId property always matches the ITSOVehicleVIN property. In other words, ITSOVehicleIdIsVIN is always true for the sample application. By convention, there are documents filed into an ITSOVehicle folder with specific containment names to indicate specific purposes. See, for example, 7.4.3, ITSOPhotoGallery on page 247. Note the following information: Not shown elsewhere in this book is an ITSODocument with a containment name of obd. Its content is an XML document holding OBD II diagnostics data that is collected from the vehicle. Each time OBD II data is collected, a new version of the document is created so that old data sets are preserved. Not shown elsewhere in this book is an ITSODocument with a containment name of description. It contains the full description of the vehicle. The actual descriptive narrative is contained in the first content element, and it must be in a format understood by the rendering application. For our samples, we use text or HTML descriptions. Rental charges for a vehicle are abstracted to a separate ITSOChargesSchedule object, which can be shared by many vehicles. For our sample application, we do not use or further describe the ITSOChargesSchedule (vehicle rental charges are supplied by hard-coded application logic). After it is created, ITSOChargesSchedule objects are not modified because they are still pointed to by ITSORentalActivity objects from the past. A DeletionAction metaproperty value of DeletionAction.PREVENT on the MVOVP that is pointing from the ITSOChargesSchedule to ITSOVehicle objects can be used to ensure referential integrity for attempted deletions.
245
Data
Table 7-2 shows the properties of ITSOVehicle.
Table 7-2 ITSOVehicle Class: ITSOVehicle (subclass of ITSOFolder) Property ITSOVehicleId ITSOIsAvailable Type String(25) Boolean Comment Value required. Standard VIN is 17 characters. As a performance measure, this field can be manually set to false when a vehicle is in maintenance for an unusually long time. It is also set to false when the vehicle is disposed of. Value required. VIN decoding can be used if this value is true. Manufacturers model year Manufacturer name Manufacturers model name Same codes as used in a VIN Intended for searching. More detailed and nuanced color descriptions can be provided in the vehicle description. Value required. Short description that is suitable for display in search summaries, and other things. This property avoids an immediate fetch of the full description document that is contained in the folder. Daily rate Total mileage of car Reflective of ITSOVehicleActivity property ITSOVehicle.
ITSOShortDescription
Long String(100)
246
Security
ITSOVehicle security is defined as follows: ITSOVehicle can be read by customers and all employees. ITSOVehicle can be created, updated, and deleted by franchise supervisory employees. The OBD II document can be created, read, and updated by any franchise employee. An update for the OBD II document is a checkout and checkin cycle. The OBD II document versions can be deleted by franchise supervisory employees. ITSOChargesSchedule can be read by customers and all employees. ITSOChargesSchedule can be created, updated, and deleted by franchise supervisory employees.
7.4.3 ITSOPhotoGallery
A document filed in an ITSOVehicle folder with a containment name of photogallery contains photographs of the vehicle. All photographs are in either JPEG, GIF, or PNG format. The primary photograph is in the first content element. Additional photographs are in other content elements.
Data
The ITSOPhotoGallery is a subclass of ITSODocument and has no specific subclass custom properties.
Security
An ITSOPhotoGallery completely inherits its security from the containing ITSOVehicle, and is implemented through the normal dynamic security inheritance of the SecurityFolder property.
7.4.4 ITSOThumbnail
By convention, each content element in an ITSOPhotoGallery document has an ITSOThumbnail annotation containing a smaller version of the image. The thumbnail image is contained in the first and only content element of the annotation and is also in JPEG, GIF, or PNG format.
247
Data
The ITSOThumbnail is a subclass of ITSOAnnotation and has no specific subclass custom properties.
Security
An ITSOThumbnail completely inherits its security from the annotated ITSOPhotoGallery, and is implemented through the normal dynamic security inheritance of the AnnotatedObject property.
7.4.5 ITSOVehicleActivity
A vehicle is always in some kind of activity state; the default state is idle. All activity records indicate a timespan, expressed as start and end date properties. In some cases, those dates are adjusted over the lifetime of the activity record. For example, the start and end dates are estimates for a reservation and are adjusted to actual rental period dates when the vehicle is picked up and returned. We can look both backward and forward in time to see when a vehicle was in a state or when it is expected to be in a state. For example, when a vehicle is reserved for rental by a customer, an activity record with a future timespan is created. Any period of time that is not covered by an activity record is considered idle time, and the vehicle is available for rental for that period (although business rules enforce a buffer period around some types of activities to recognize that the vehicle might not become available exactly when expected). The major states for vehicles are reflected in subclasses of ITSOVehicleActivity (see 7.4.7, ITSORentalActivity on page 250; 7.4.8, ITSOMaintenanceActivity on page 251; and 7.4.9, ITSODisposalActivity on page 253). Several other minor activities exist, but we do not show them here (for example, when a vehicle has been returned and is being washed and prepared for the next rental).
248
Data
Table 7-3 shows the properties of ITSOVehicleActivity.
Table 7-3 ITSOVehicleActivity Class: ITSOVehicleActivity (subclass of ITSOCustomObject) Property ITSOVehicle ITSOStartDate ITSOEndDate ITSODisposalActivity Type OVP (ITSOVehicle) Date Date MVOVP (ITSODisposalActivity) Comment If this activity led directly to a disposal, then this property points to the disposal activity object. Although for referential integrity purposes this is a reflective property corresponding to the ITSODispoalActivity property ITSODisposingActivity, we expect it to have either no value or a single value.
Security
ITSOVehicleActivitys security is defined as follows: All ITSOVehicleActivity records can be read by customers and all employees. Customers must read all records for the purpose of doing reservation activity; however, application logic restricts display to only ITSORentalActivity records which are affiliated with that customer through the ITSOCustomer property. Further access is described for each ITSOVehicleActivity subclass.
7.4.6 ITSOSingleton
ITSOSingleton is used to maintain the last confirmation ID that is used for a car rental. See Table 7-4.
Table 7-4 ITSOSingleton Class: ITSOSingleton (subclass of ITSOCustomObject) Property ITSOIntegerValue Type Integer Comment Used to generate the unique ITSOConfirmationID for rental reservations.
249
7.4.7 ITSORentalActivity
This type of activity record is used both for reservations, in-progress rentals, and completed rentals. Payment details, including credit card number and itemized charges, are recorded in an ITSOChargesRecord. For simplicity in our sample application, we do not use or further describe the ITSOChargesRecord. Instead, we directly record an artificial credit card-like number in the ITSOCreditCardSimulation property.
Data
Table 7-5 shows the properties of ITSORentalActivity.
Table 7-5 ITSORentalActivity Class: ITSORentalActivity (subclass of ITSOVehicleActivity) Property ITSOConfirmationID Type Integer Comment Fetch the ITSOSingleton object and get the ITSOIntegerValue and increment it by 1 for generating ITSOConfirmationID. Save the ITSOSingleton object with incremented value. Value required. It can be one of the following values: reserved, active, historical Is used for historical and auditing purposes. Cancelled reservations do not participate in vehicle activity. Daily rate Artificial credit card-like payment indicator Pointer to a separate payment record containing credit card and other details
ITSORentalStatus
String(10)
ITSORentalIsCancelled
Boolean
250
Class: ITSORentalActivity (subclass of ITSOVehicleActivity) Property ITSOCurrency Type String(3) Comment The currency type for money amounts. Values are usd, cad, eu, and so on. Total estimated or actual rental charges rolled up from the ITSOChargesRecord Net estimated or actual rental charges (after direct costs like taxes and fees are deducted) that are rolled up from the ITSOChargesRecord Is used to demonstrate versioning Mileage at the beginning of rental Miles driven during rental period.
ITSOChargesTotal
String
ITSOChargesNet
String
Security
ITSORentalActivity security is defined as follows: ITSORentalActivity objects may be created, read, and updated by any customer, but application logic restricts read access to objects associated with that customer. All create and update activities are mediated by an application. ITSORentalActivity objects may be created, read, updated, and deleted by any employee of the franchise to which the vehicle belongs.
7.4.8 ITSOMaintenanceActivity
This type of activity records a single maintenance event, generally meaning a single contiguous trip to the maintenance area. There are additional ITSOMaintenanceDetail objects showing time spent waiting, sent to outside service contractors, and so on. The details are aggregated to a single ITSOMaintenanceActivity record. The sample application does not show the ITSOMaintenanceDetail objects.
251
Data
Table 7-6 shows the properties of ITSOMaintenanceActivity.
Table 7-6 ITSOMaintenanceActivity Class: ITSOMaintenanceActivity (subclass of ITSOVehicleActivity) Property ITSOMaintenanceCode Type String (10) Comment Required value. One of a set of fixed values including oilchange, tirerepair, bodydamage, and so on. Unusual maintenance can be described in:
ITSOMaintenanceComment
ITSOMaintenanceComment
Long String(5000)
Manually entered text describing the nature of the maintenance Reflective from ITSOMaintenanceDetail property ITSOMaintenanceActivity Currency type for money amounts. Values are usd, cad, eu, and so on. Cost of parts charged by an outside service contractor. Money amounts are multiplied by 100 to preserve accuracy. Cost of parts from in-house sources. Money amounts are multiplied by 100 to preserve accuracy. Labor hours from outside service contractors Labor hours from in-house technicians
ITSOMaintenanceDetails
MVOVP (ITSOMaintenanceDetail)
ITSOCurrency
String(3)
ITSOPartsExternal
Integer
ITSOPartsInternal
Integer
ITSOLaborExternal ITSOLaborInternal
Float Float
252
Security
ITSOMaintenanceActivity security is defined as follows: ITSOMaintenanceActivity objects may be read by any employee of the franchise to which the vehicle belongs. ITSOMaintenanceDetail objects may be read by any maintenance employee or supervisory employee of the franchise to which the vehicle belongs. ITSOMaintenanceActivity objects may be created, updated, or deleted by any supervisory employee of the franchise to which the vehicle belongs. There is typically at least one supervisory employee in the maintenance department. ITSOMaintenanceDetail objects may be created, updated, or deleted by any maintenance employee of the franchise to which the vehicle belongs.
7.4.9 ITSODisposalActivity
When a vehicle is sold or removed permanently from inventory, the vehicle records are kept online for a period of time. To prevent an unavailable vehicle from being scheduled for any real activities, it is given an ITSODisposalActivity record with an end date in the distant future. The sample application does not show the process of disposing of vehicles.
Data
Table 7-7 shows the properties of ITSODisposalActivity.
Table 7-7 ITSODisposalActivity Class: ITSODisposalActivity (subclass of ITSOVehicleActivity) Property ITSODisposalType Type String(10) Comment Value required. One of the values sold, scrapped, stolen. Manually entered text describing the nature of the disposal. An optional pointer to a rental or maintenance activity that led to the disposal.
ITSODisposalComment
Long String(5000)
ITSODisposingActivity
OVP (ITSOVehicleActivity)
253
Security
ITSODisposalActivity is defined as follows: ITSODisposalActivity objects may be read by any employee of the franchise to which the vehicle belongs. ITSODisposalActivity objects may be created/updated/deleted by any supervisory employee of the franchise to which the vehicle belongs.
7.4.10 ITSOIdleActivity
When a vehicle has no explicit activity of some other type, it is said to be idle. It is possible to deduce the idle periods by noting the gaps between other types of activities. However, it is difficult to perform a query for that gap, so the repository uses explicit ITSOIdleActivity objects to keep track of the gaps. To find vehicles available for rental, the application queries for ITSOIdleActivity records for the applicable time frame.
Data
The ITSOIdleActivity is a subclass of ITSOVehicleActivity and has no specific subclass custom properties.
Security
ITSOIdleActivity security is defined as follows: ITSOIdleActivity objects may be read by any customer or employee. Because ITSOIdleActivity objects are managed completely by event action handlers (which run in system context), they are read-only to all customers and employees.
7.4.11 ITSOCustomer
Employees have entries in the enterprise directory, but customers do not. Customer information is kept in the repository. Customer information can be coarsely divided into two types: customer factual information (for example, address) and customer preference information. Information that is not typically needed for routine customer searches is kept as XML as the document content. A new document version is created when the information is revised so that prior data sets can be kept.
254
Data
Table 7-8 shows the properties of ITSOCustomer.
Table 7-8 ITSOCustomer Class: ITSOCustomer (subclass of ITSODocument) Property ITSOCustomerUserid ITSOCustomerPassword Type String (20) Binary (20) Comment Used by customer for login identity SHA-1 160-bit hashed password value. Used for authentication. Reflective from ITSORentalActivity property ITSOCustomer Reflective from ITSOCommentary property ITSOCustomer
ITSORentalActivities
ITSOCommentaries
Security
ITSOCustomer security is defined as follows: ITSOCustomer objects may be created, read, updated, or deleted by customers or any employee at headquarters or at a franchise location. Application logic restricts a customer to viewing or acting on the single applicable ITSOCustomer object.
7.4.12 ITSOCommentary
As an aspect of social networking, the company allows customers to make comments and provide ratings of specific vehicles. These comments are visible to customers as they browse the vehicle inventory. A comment is always tied to a particular ITSOCustomer, but it is not a requirement that a customer has rented that specific vehicle in the past. For example, customers might like to make comments that are related only to the type or model of vehicle. ITSOCommentary is implemented as a custom annotation class annotating the ITSOVehicle objects. Although the company does not censor negative comments, all comments added go through an editorial moderation process to screen for obscenities, spam, legal risks, and so on. Moderators may also make minor formatting, grammar, and spelling corrections.
255
Data
Table 7-9 shows the properties of ITSOCommentary.
Table 7-9 ITSOCommentary Class: ITSOCommentary (subclass of ITSOAnnotation) Property ITSOCustomer ITSOCommentaryDate Type OVP (ITSOCustomer) Date Comment The moderation process is prone to disrupt the DateCreated and DateLastModified properties, so this explicit date reflects when the commentary was originally created by the customer. Values are restricted to 0 - 10, where 0 means not rated. A conventional five-star scale with the possibility of half-stars can be created by dividing this value in half. Value is assumed to be HTML text. Moderation life cycle status of a particular comment. Values are raw (as received from the author), edit (being edited by a moderator), and ready (available for viewing by customers)
ITSORating
Integer
ITSOCommentaryText ITSOCommentaryStatus
256
Security
ITSOCommentary security is defined as follows: When a commentary is initially created, it has an explicit access control entry of AccessType.DENY for all access rights for the customers. As part of the moderator approval process, that access control entry is removed. Thus, normal access control mechanisms will render unmoderated commentaries invisible to customers. ITSOCommentary objects are visible to customers (after the moderation process) and any headquarters or franchise employee. ITSOCommentary objects may be created, updated, or deleted by a customer or any non-maintenance employee of the franchise to which the vehicle belongs. Application logic restricts customers to updating or deleting comments that they created.
7.4.13 ITSOFranchise
ITSOFranchise objects provide details for Fictional Auto Rental Company A franchise locations. The inherited ITSOFranchiseCode is used by many other classes to narrow those objects to a particular franchise location. Note: The sample application assumes one location per city. In reality, one city could have multiple locations.
Data
Table 7-10 shows the properties of ITSOFranchise.
Table 7-10 ITSOFranchise Class: ITSOFranchise (subclass of ITSOCustomObject) Property ITSOFranchiseName ITSOFranchiseCity ITSOFranchiseStateProvince ITSOFranchisePostalCode ITSOFranchiseDescription ITSOFranchiseTelephone ITSOFranchiseDirections Type String(20) String(20) String(3) String(10) String(30) String(12) String(30)
257
7.4.14 ITSORole
ITSORole objects identify functional types of users. The sample application considers the following distinct types of users, each represented by a distinct ITSORole object with the indicated ITSORoleName: Customer (customer) Headquarters employee (hq) Franchise supervisory employee (supervisor) Franchise front-office (customer-facing) employee (frontoffice) Franchise maintenance employee (maintenance) An important role is customer, which is the role for the single account that is used by the back-end systems for all customer interactions. The corresponding ITSORole object has an ITSOFranchiseCode of itsoautohq, as does the ITSORole object for headquarters employees. Objects that represent roles serve two distinct purposes in the sample application. It is not a requirement that the same set of ITSORole objects be used for both purposes. Because a large amount of overlap exists, we do not specialize it further into subclasses. Instead, we distinguish the type of individual ITSORole object through custom properties and business rules, which use those properties. A franchise supervisory employee has access to everything to which either a franchise front-office employee or a franchise maintenance employee has access. We model this with ITSORole objects by having both the frontoffice and maintenance ITSORole objects for a given franchise inheriting security (through the ITSOSecurityProxy property) from the supervisor ITSORole object for that same franchise.
258
maintenance ITSORole object. To make its decision, the application issues a query of the form: SELECT TOP 1 Id from ITSORole WHERE ITSORoleName = 'maintenance' If at least one result is returned from that query, the application knows that the user has access to one or more maintenance ITSORole objects. In this particular example, where we are controlling the display of application features visible only to maintenance employees, matching on the ITSOFranchiseCode is not necessary. Security constraints on the maintenance-related objects ensure that users see only objects that are associated with a particular franchise.
Data
Table 7-11 on page 260 shows the properties defined for ITSORole.
259
Table 7-11 ITSORole Class: ITSORole (subclass of ITSOCustomObject) Property ITSORoleName Type String(20) Comment Short but meaningful name for this ITSORole object, as described in the text. Uniqueness is enforced by convention when combined with the ITSOFranchiseCode for this object. Value is true if this ITSORole is used for security access control. Value is true if this ITSORole is used for controlling user interface elements. Additional security proxy property. Used when combining two roles together. See ITSOSecurityProxy2 property.
ITSOSecurityProxy2
OVP (ITSORole)
ITSOSecurityProxy3
OVP (ITSORole)
Security
The security of the ITSORole objects (of both types) is dictated by how each individual ITSORole object is used. Unlike most of the other objects in our data model, no users (other than the system administrators) inherently have access to the ITSORole objects.
260
Note: For simplicity in the sample application, we have made the customer pseudo-identity slightly more powerful than we would like, and we enforce additional controls at the application level. For example, to be able to make reservations, the customer must have security access to all ITSOIdleActivity records, but our policy is that they can see only their own ITSORentalActivity objects and no other ITSOActivity objects. Furthermore, in some parts of the sample application, we have to supply explicit credentials to authenticate as the customer pseudo-identity. Both of these situations are undesirable as security best practices. A more secure (but, unfortunately, too complex to show in our sample application) implementation would pass all customer access through an EJB method with a configured RunAs role. That is, each EJB method is configured (in the deployment descriptor) to run as the customer pseudo-identity when further J2EE calls are made. This has the advantage of consolidating the logic which enforces additional restrictions on access to objects. We could probably even configure the customer pseudo-identity in the enterprise directory to prohibit logins. EJB RunAs roles is a standard J2EE feature. Actually configuring it has aspects that are specific to application server and is beyond the scope of this book. Nonetheless, it is an important security implementation pattern, and you should consult your application server documentation to learn more about it. Customers do not have records in the the company enterprise directory, whereas all headquarters and franchise employees do. A single customer pseudo-identity is present in the enterprise directory and is used for all access across all franchises. Customer account information is stored as objects in the Content Manager repository. The enterprise directory uses a group structure to organize employees, but it is static and relatively flat. There is a top-level directory group for headquarters and a top-level directory group for each franchise. Within those top-level groups, the enterprise directory does not use further subgroups. Access control security for objects is implemented according to these principals: Customers can see only vehicle information that is intended to be part of Web pages. They cannot see other vehicle information or other business objects. Customers can see all vehicles from all franchises. The application logic allows them to limit or expand their vehicle searches. An employee in one franchise location cannot view the business objects of another franchise location.
261
Different groups of employees may have different types of access to different business objects for the franchise. Appropriate employees of the company headquarters have access to selected business objects for any franchise. Back-end system administrators have access to all objects in the system. All system administrators are part of the company headquarters. Specific mechanisms that are used for security access include direct access control entries (Aces) on objects, standard security inheritance mechanisms (for example, object Aces inherited by an annotation object), and a collection of ITSORole objects acting as security proxies through dynamic security inheritance. The dynamic security inheritance embodied in the ITSORole objects is transitive, so an ITSORole object can itself inherit ACEs from another ITSORole object. Cascading combinations of inheritance can be used to control access to objects. The advantages to this are: ITSORole objects can stand in for a more granular group structure than is available from the enterprise directory. When an employee moves from one role to another (for example, a franchise line employee becoming a franchise supervisory employee), the security for any number of objects may be instantly updated by changing the ACLs on applicable ITSORole objects.
7.6 Workflows
In this section, we describe the workflows implemented for the the company management solution. For a complete business solution, additional elements, such as new workflows, can be identified and implemented across the applications that comprise this solution; however, for the sample application, we provide the following workflow definitions: Vehicle reservation workflow Vehicle maintenance workflow These workflow definitions use a specific isolated region configuration, including a custom roster, event log, and queues. A custom component queue (ITSO_Operations) is also included as part of this configuration to perform certain custom calls within the workflows.
262
Component queues
CE_Operations ITSO_Operations
263
ITSO_Operations Implemented to service a custom Java component to perform certain business operations used by the sample application workflows. This component is also provided as a sample to show how to implement a custom Java component by using Component Integrator. Table 7-13 describes the operations included in this custom Java adaptor.
Table 7-13 ITSO_Operations component queue operations Operation name verifyCustomerCredit Description Performs customer credit card validation by calling a third-party system. The operation simulates the call to the external system, always returning a true value. Retrieves and parses the ITSOCustomer document content to extract certain metadata values and assign them to the workflow data fields. This operation demonstrates how to perform a custom call to CE. Uses certain business rules related to a vehicle maintenance activity and launches the vehicle maintenance workflow, passing all required objects. This operation demonstrates how to perform a custom call to PE.
getCustomerDetailsFromOS
sendVehicleToMaintenance
264
Figure 7-23 shows the main diagram that is used by this workflow definition.
Although workflows can be launched by using workflow subscription events, the ITSO vehicle reservation workflow is launched programmatically by the Reservation Web application in order to pass the required objects as attachment references and avoid unnecessary calls within the workflow. The Kiosk application interacts with this workflow when a customer picks up and returns a vehicle. The vehicle reservation workflow definition is comprised of system, component, and work steps. All system and component steps are executed without human intervention to either perform a task within the workflow or call to an external system.
265
ITSO_Reservation
ITSO_Reservation
Review
ITSO_Malfunction
266
Figure 7-24 shows the main diagram that is used by this workflow definition.
The vehicle maintenance workflow can be launched either from the vehicle reservation workflow when the vehicle is returned and must be sent to maintenance, or from the Fleet Status Manager Web application when a vehicle is manually sent to maintenance. The Fleet Status Manager Web application is also used to process all vehicles sent to maintenance. Table 7-15 describes the work step defined in the vehicle maintenance workflow definition.
Table 7-15 ITSO vehicle maintenance work steps Work step Maintenance queue Work queue ITSO_Maintenance Description The vehicle is sent to maintenance and waits in the queue until it gets assigned and processed. Malfunction step to handle unexpected workflow exceptions.
Review
ITSO_Malfunction
267
268
Registration Success
Login
Register
Register
No
Failed Registration
Valid User?
Yes
ITSOCarRentalHome
Cars Available
ITSOCarSelectionPage1
Car Selected
ITSOCarRentalConfirm
Rental Success
ITSOVehicleReserve
This application consists of the following Java classes: com.itso.MetadataConstants: The MetadataConstants class contains CE and PE property and class names. itso.autorental.ITSOUtil: This class contains various convenience methods. The intent of these methods is mainly to isolate various common interactions with the CE and PE so that it is not spread throughout the other classes. itso.autorental.process.ITSOAutoRentalWorkflow: This class contains methods related to interaction with the PE API. com.itso.bean package: This package consists of JavaBean classes for data objects.
269
itso.autorental.RentalActivityHandler: Convenience methods including creating and deleting various vehicle activities, as follows: createMaintenanceActivity(): This method takes a vehicle ID and franchise code and creates a maintenance activity. createRentalActivity(): This method creates a rental activity for a confirmed reservation. deleteVehicleActivity(): This method removes a vehicle activity (for example, maintenance activity) given the activity ID. The pagecode package contains the JSF backing classes for each JSP.
270
Startup (ApplicationWizard.cs)
Prompt for credentials ApplicationWizard.ApplicationWizard_Shown() P8Prompt.ShowDialog() Connect to CE & PE ApplicationWizard.ConnectToP8() ContentEngineConnector.Connect() ProcessEngineConnector.Connect() Choose Activity: Pickup or Return MainWizardPage Pickup Return Restart
Restart
Prompt For Confirmation Number PickupPage1.cs Failure Lookup Confirmation Number PickupPage1.Lookup() ContentEngineConnector.GetRentalRecord()
The application is responsible for: Pickup Prompting the customer for the rental confirmation ID Finding appropriate rental and displaying rental information to customer Completing the rental by completing the workflow step Return Prompting the customer for the vehicle ID Completing the rental workflow step
271
272
The Fleet Status Manager application is a J2EE application written using Java Server Faces (JSF). It communicates with the CE (using the CE Java API) and the PE (using the PE Java API). Overall program flow is illustrated in Figure 7-27.
login.jsp
Login Type
Mechanic
groupqueueitem.jsp
No
Work complete?
myqueueitem.jsp
Yes
This application consists of the following Java classes: itso.autorental.MetadataConstants: The Constants class contains CE and PE property and class names. itso.autorental.ITSOUtil: This class contains various convenience methods, including: loginToFileNet(): This method establishes connections to CE and PE. loadProperties(): This method loads configuration data from a properties file. getFleetStatus(): This method takes a franchise code and object store and retrieves all cars and their statuses within that franchise. This method returns an array which is used for populating the JSF HtmlDataTable. getQueueWorkItems(): This method retrieves all maintenance activities in a particular franchise code and group queue. This method also returns an array which is used for populating the JSF HtmlDataTable.
273
assignWorkItemToMyQueue(): This method takes a queue name, wob number, and a user name. It assigns the work item to this users queue. reassignWorkItemToGroupQueue(): This method takes a wob number and reassigns the work item back to the group queue. completeWorkItem(): This method takes a wob number and completes the workflow. itso.autorental.ITSOVehicle: This class represents an Vehicle object for this application. itso.autorental.UserRole: This class represents a user role for the logged in user. User can be a maintenance worker or a supervisor. itso.autorental.RentalActivityHandler: This class has convenience methods, including creating and deleting various vehicle activities: createMaintenanceActivity(): This method takes a vehicle id and franchise code and creates a maintenance activity. deleteVehicleActivity(): This method removes a vehicle activity (for example, maintenance activity) given the activity ID. The itso.autorental.fleetstatusmanager.beans package contains the JSF base classes for each JSP.
274
275
276
Application Server 6.1. Because the steps are relatively simple, adjusting for WebLogic or JBoss should be straightforward. The samples are provided in source form, and we also provide prebuilt binaries enabling you to more easily run them before setting up your development environment. The instructions here are focused mainly on how to run the prebuilt binaries, but, where applicable, we offer guidance for using the sources to re-create those binaries. Note: Installing and running these sample applications in a production environment is not advisable. Part of the setup procedure involves introducing changes to the CE and PE servers, and for that reason we strongly recommend using a development environment or other non-critical environment. Getting the sample applications up and running requires the following steps: 1. Download and unpack the samples. The IBM Redbooks publications Web site for this book contains a download link to a file named sg247743-sample.zip. (Refer to Appendix A, Additional material on page 315 for locating the information.) Download that file and extract it in a convenient location on your local system. Depending on the tools you use locally for some of the steps, you might have to ensure that no spaces exist in the path leading to that location. The top-level directory is called sg247743-sample/, and all of our paths in these instructions are relative to that top-level directory. The overall structure is shown graphically in 7.8.1, Application package structure on page 278. 2. Prepare your CE and PE. The sample applications work in coordination with an established environment for the CE (for example, custom classes and properties) and PE (for example, workflow definitions). The downloaded sample applications include artifacts that are used to establish those environments. Specific instructions are provided in 7.8.2, Content Engine artifacts on page 279 and 7.8.3, Process Engine artifacts on page 285. 3. Add P8 and third-party modules. These modules will be added to the environment in locations under sg247743-sample/. Where necessary, specific instructions are provided in sections for specific components. We assume that you have a working P8 installation available locally; P8 components can be copied from that environment. You might also find convenience in running the P8 client installer to obtain a local copy of P8 components. In any case, you should use P8 client-side components that are compatible with the P8 CE and PE servers that you will be using.
277
4. Modify configuration files. The sample applications use configuration files for URIs pointing to the CE and PE, among other things, so that you can use the binary files in the samples. Specific instructions are provided in sections for specific components where necessary. 5. Deploy each sample component. Because we use a variety of technologies to demonstrate various things, there are also a variety of steps needed to install and deploy components of the sample applications.
278
Table 7-16 describes the high-level directory structure for the downloaded sample applications.
Table 7-16 The sample application directory structure Directory CEartifacts/ Description Information related to the metadata used in the CE. Directory includes a set of files to be imported into the CE to establish custom classes, custom properties, and some instance data. Process definitions and other configuration items for the PE. Also includes source files and precompiled binaries for the ITSOOperations connector for Component Integrator. Source files and precompiled binaries for most of the Java-based components of the sample applications. For ITSOReservationSystem and ITSOFleetStatusManager directories, the source files are included in the EAR or WAR files, along with the compiled class files. For the other applications, the sources are in an obvious subdirectory. Source files and precompiled binaries for the Windows-only Kiosk application. Prebuilt WAR file for the sample widget. Because the widget is implemented in JavaScript, the WAR file also contains the source files.
PEartifacts/
Java/
Kiosk/ Widget/
279
classes and properties are described in 7.4, Data model on page 239. We also provide sample instance data for various CE classes that are used by the sample applications. Importing this sample data is not strictly necessary, but you would otherwise have to manually create certain data if you want your exploration of the sample applications to be meaningful. Although the structure of our sample data correctly matches the data model description, it is only sparsely populated. Other than in structure, the data is not intended to be particularly realistic. Even after you have imported the sample instance data, you might want to create additional instance data of your own for the purposes of experimenting with the sample applications. You can add this custom metadata and sample instance data to your ObjectStore through the standard import procedure, as follows: 1. Start the IBM FileNet Enterprise Manager application and log on to the P8 domain. 2. Navigate to the ObjectStore you wish to use for the sample applications, right-click on it, and select All Tasks Import All. See Figure 7-30.
280
3. Enterprise Manager presents an import helper panel. On the Import Options tab (see Figure 7-31), enter the following information: a. In the Import Manifest File field, browse to and select the file:
sg247743-sample/CEartifacts/import/farcasample_CEExport_Manifest.xml
b. Leave the External Content Path field empty. c. For Storage Location for Imported Objects, select Default Database Storage Policy from the drop-down menu. d. For Standard Options, check only Import Object ID and Ignore duplicate error messages during import. Deselect all other boxes. The reason for ignoring duplicates is that a few things in the import data might (or might not) already be present in your ObjectStore. It is also helpful if you have to re-run the import process.
281
282
4. On the Import Items tab (in Figure 7-32), check only Property Templates and Class Definitions. Deselect all other boxes. This step causes only metadata objects to be imported. Instance data will be imported in a later step.
5. On the Advanced tab, make sure all available checkboxes are checked. 6. Click the Import button. The import of metadata should proceed without errors or warnings. If problems occur, consult Enterprise Manager documentation and resolve those problems before going further. 7. Repeat these steps, but on the Import Items tab, deselect only Property Templates and Class Definitions check boxes. Check all other boxes. See Figure 7-33. This step causes instance data to be imported. Depending on your specific version of Enterprise Manager, you might have to repeat the import of instance data to resolve all dependencies. Warnings about duplicated items can be ignored, but errors for missing items must be resolved by repeating the import. You are looking for a summary that says the import was successful, not merely partially successful.
283
Figure 7-33 CE import helper panel Import Items for instance data
284
After the instance import, you should see a structure like Figure 7-34 under the /ITSOAutoRental/ folder in your ObjectStore.
285
d. Ensure that the PE notification settings are properly configured in the Process Task Manager (Figure 7-36). These notification settings are required in order to send e-mail by using the CE_Operations component.
2. Import the ITSOAutoRentalIsolatedRegion.xml file as follows: a. Log onto the Workplace or WorkplaceXT application using an administrator account. b. Open the Process Configuration Console. See Figure 7-37. a. Open a connection on the connection point where the new configuration will be imported. b. Right-click on the selected connection point node and select the Import from XML file option.
286
c. Browse to and select the following file to import: sg247743-sample/PEartifacts/ITSOAutoRentalIsolatedRegion/ITSOAuto RentalIsolatedRegion.xml d. Select Merge as the import type. e. Click the Import button and select Yes from the warning message.
3. Set component queues adaptor security (Figure 7-38) as follows: a. Select the ITSO_Operations component queue from the Component Queues node. b. Open the component properties and navigate to the Adaptor tab. c. Enter a valid user name and password for the JAAS Credentials section and click OK. d. Repeat steps a - c for the CE_Operations component adaptor. e. Commit your changes.
287
4. Add the workflow definitions (.pep files) to the object store by using the Workplace or WorkplaceXT application as follows: a. Create a folder where the workflow definitions are to be added. For example, ITSOAutoRentalWorkflows. b. Add the following workflow definition in the created folder, specifying the document class as Workflow Definition: sg247743-sample/PEartifacts/ITSOAutoRentalWorkflows/ITSO Vehicle Reservation Workflow.pep c. Right-click on the added workflow definition and select the Transfer Workflow action. d. Leave the default prompted name to transfer the workflow definition and click the Transfer button. e. Repeat steps a to d for the ITSO Vehicle Maintenance Workflow.pep workflow definition.
288
5. Copy the contents of the sg247743-sample/PEartifacts/ITSOOperations/ directory to the Application Engine server and configure general settings as follows: a. Log onto the Application Server and create a custom filesystem folder where the ITSOOperations PE artifacts are to be copied. For example, ITSOAutoRental. b. Copy ITSOOperations.jar and log4j.xml files from the sample to the created folder. c. Open the ITSOOperations.jar file with any compression program (for example, WinZip or the Java jar command). d. Locate and open the ITSOAutoRental.properties file with a text editor, and enter the correct property values for your environment. e. Save and update changes performed to ITSOAutoRental.properties (see Example 7-1).
Example 7-1 ITSOAutoRental.properties sample
##########the company General Settings########## # Object Store Name ITSOObjectStore=DemoOS ##########the company Email Settings############ # Sender Email Address [email protected] # Customer Service Email Address [email protected] # Vehicle Maintenance Manager Email Address [email protected] ##############ITSO Malfunction Settings########################## # Debug malfunction flag (default: false) ITSOMalfunctionDebug=false # Retry malfunction flag (default: false) ITSOMalfunctionRetry=false 6. Configure ITSOOperations custom logging. The log4j.xml file provided with the ITSOOperations package is preconfigured on debug level for the specified packages and creates a daily log file at the following location, by default: C:/itso_autorental_ops.log
289
Logging parameters may be changed within the log4j.xml file according to your environment (Example 7-2). If you are not running on Windows, you should at least change the daily log file name.
Example 7-2 Provided log4j.xml file for the ITSO_Operations component .. <!-- ITSO_Operations Trace Dated Log File --> <appender name="ITSOOpsTraceDatedLogFile" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="c:/itso_autorental_ops.log"/> <param name="DatePattern" value=".dd-MM-yyyy"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d %p [%t] %c (%M:%L) %m%n"/> </layout> </appender> ... <!-- ITSO_Operations package logging --> <logger name="itso.autorental.components" additivity="false"> <level value="debug"/> <appender-ref ref="ITSOOpsTraceDatedLogFile"/> <appender-ref ref="console"/> </logger> ...
7. Add ITSOLogin login context to the taskman.login.config file: a. ITSO_Operations component uses a custom login context named ITSOLogin. The following sample file is provided, to show you how this custom login is implemented: sg247743-sample/PEartifacts/ITSOOperations/taskman.login.config.s ample b. Navigate to the taskman.login.config file that is used by the Component Manager. For example, the file might be in this location: E:\Program Files\FileNet\WebClient\Router\taskman.login.config c. Append the ITSOLogin login context, as shown in Example 7-3.
Example 7-3 ITSOLogin login context ITSOLogin { filenet.vw.server.VWLoginModule required; itso.autorental.components.authentication.ITSOLoginModule required debug=true; };
290
8. Add ITSO_Operations required library and configure the JRE parameters: a. Open the Process Task Manager and select the Required Libraries tab on the Component Manager node. See Figure 7-39. b. Add the following file to the list of Component Manager required libraries: sg247743-sample/PEartifacts/ITSOOperations/ITSOOperations.jar c. Click Apply.
d. Select the Advanced tab (Figure 7-40) on the Component Manager node and add the following required JRE parameter, which is the location of the ITSO_Operations log4j.xml file: itsolog4j.configuration For example: -Ditsolog4j.configuration=E:/Program Files/FileNet/ITSOAutoRental/log4j.xml e. Click Apply.
291
9. Start the Component Manager and verify that all component queues have started, with no errors. See Figure 7-41.
292
4. Unpack the WAR file by using a tool that understands ZIP format (for example, WinZip or the Java jar command). For the purposes of this explanation, we assume you unpacked it to the ITSOCarRentalApp.war directory. 5. Navigate to the ITSOCarRentalApp.war/WEB-INF/classes/ directory. 6. Edit the SampleCarRental.properties file and set each parameter appropriately for your FileNet environment. Because this application runs inside a J2EE application server, the simplest approach is to configure the CE connection URI to use EJB transport. 7. Navigate to the ITSOCarRentalApp.war/WEB-INF/lib directory. You might have to create the lib subdirectory. 8. Add the CE and PE API JAR files from your P8 environment, as described in Chapter 2, Setting up development environments on page 13. Because you are using CE EJB transport, the CE JAR files are limited to: Jace.jar log4j.jar The PE JAR files are: pe.jar pe3pt.jar peResources.jar 9. Re-create ITSOCarRentalApp.war, including the changes to the properties file and the addition of the API JAR files. 10.Re-create ITSOCarRentalApp.ear, including the changes to the ITSOCarRentalApp.war file. 11.Continue with deployment, as described in the Deployment section. In those deployment instructions, we assume that you replaced the original ITSOCarRentalApp.ear file with the modified version in the original location.
Deployment
Details of deploying a Web application vary from application server to application server, and details can be different for different releases of the same application server brand. To simplify the explanation, we give the steps to deploy the Reservation Web application in WebSphere Application Server 6.1, as follows: 1. Make sure that you have performed the preparation steps as described in the EAR file preparation on page 292. 2. Log on to the WebSphere administrative console
293
3. Install the ITSOCarRentalApp.ear file as follows: a. Select Applications Install New Application. b. Click Browse and navigate to the file: sg247743-sample/Java/ITSOReservationSystem/ITSOCarRentalApp.ear c. Click Next. Keep all defaults for each dialog page by clicking Next, and click Finish on the last dialog page. Save all your changes. 4. Configure the class loading and updating information: a. Select Applications Enterprise Applications. b. Select the ITSOCarRentalApp link. c. Select Class loading and update detection. d. For the Class loader order field, select Classes loaded with application class loader first. e. Accept the default value for the Polling interval for updated files field. f. Click OK. Click Save. 5. Configure class loader order information: a. Select Applications Enterprise Applications. b. Select the ITSOCarRentalApp link. c. Click Manage Modules. d. Select the ITSOCarRentalWeb link. e. For the Class loader order field, select Classes loaded with application class loader first. f. Click OK. Click Save. 6. If you are using CE EJB transport, no extra JVM parameters are required. If you are using CEWS transport with a CE release before 4.5.1, set up the JVM parameters: a. Go to the WebSphere administrative console. b. Select Servers Application servers. c. Click on your server (for example, server1). d. Select Java and Process Management Process Definition Java Virtual Machine. e. On the Generic JVM Arguments tab, enter the JVM parameters that are applicable to CEWS transport, as described in Chapter 2, Setting up development environments on page 13. f. Click OK. Click Save to save your changes.
294
7. Start your application in WebSphere: a. Select Applications Enterprise Applications. b. Select the ITSOCarRentalApp check box. c. Click Start. Your application should start properly. 8. Launch your application from a browser: a. Open a Web browser. b. Navigate to: http://<YourAppServer:port>/ITSOCarRentalWeb/Login.faces c. Log in using a customer account. The first time, you have to follow the registration link to create a customer account.
295
2. Unpack the EAR file using a tool that understands ZIP format (for example, WinZip or the Java jar command). For the purposes of this explanation, we assume you unpacked it to the following directory: ITSOFleetStatusManagerApp.ear 3. Navigate to the ITSOFleetStatusManager.ear directory and locate the following WAR file: ITSOFleetStatusManager.ear/ITSOFleetStatusManager.war 4. Unpack the WAR file by using a tool that understands ZIP format (for example, WinZip or the Java jar command). For the purposes of this explanation, we assume you unpacked it to the following directory: ITSOFleetStatusManagerApp.war 5. Navigate to the ITSOFleetStatusManager.war/WEB-INF/classes/ directory. 6. Edit the SampleCarRental.properties file and set each parameter appropriately for your FileNet environment. Because this application runs inside a J2EE application server, the simplest approach is to configure the CE connection URI to use EJB transport. 7. Navigate to ITSOFleetStatusManager.war/WEB-INF/lib directory. You might have to create the lib subdirectory.
296
8. Add the CE and PE API JAR files from your P8 environment, as described in Chapter 2, Setting up development environments on page 13. Because you are using CE EJB transport, the CE JAR files are limited to: Jace.jar log4j.jar The PE JAR file are: pe.jar pe3pt.jar peResources.jar 9. Re-create the ITSOFleetStatusManagerApp.war file, including the changes to the properties file and the addition of the API JAR files. 10.Re-create the ITSOFleetStatusManagerApp.ear file, including the changes to ITSOFleetStatusManagerApp.war file. 11.Continue with deployment, as described in the section Deployment. In those deployment instructions, we assume that you replaced the original ITSOFleetStatusManagerApp.ear with the modified version in the original location.
Deployment
Details of deploying a Web application vary from application server to application server, and details can be different for different releases of the same application server brand. To simplify the explanation, we give the steps to deploy the FleetStatusManager Web application in WebSphere Application Server 6.1. 1. Make sure that you have performed the preparation steps as described in the section EAR file preparation on page 296. 2. Log on to the WebSphere administrative console 3. Install the ITSOFleetStatusManager.ear file: a. Select Applications Install New Application. b. Click Browse and navigate to the file:
sg247743-sample/Java/ITSOFleetStatusManager/ITSOFleetStatusManager.ear
c. Click Next. Keep all defaults for each dialog page by clicking Next, and click Finish on the last dialog page. Save all your changes. 4. Configure the class loading and updating information: a. Select Applications Enterprise Applications. b. Select the ITSOFleetStatusManagerApp link. c. Select Class loading and update detection.
297
d. For the Class loader order field, select Classes loaded with application class loader first. e. Accept the default value for Polling interval for updated files field. Click OK. Click Save. 5. Configure class loader order information: a. Select Applications Enterprise Applications. b. Select the ITSOFleetStatusManagerApp link. c. Click Manage Modules. d. Select the ITSOFleetStatusManager link. e. For the Class loader order field, select Classes loaded with application class loader first. f. Click OK. Click Save. 6. If you are using CE EJB transport, no extra JVM parameters are required. If you are using CEWS transport with a CE release before 4.5.1, set up the JVM parameters: a. Go to the WebSphere administrative console. b. Select Server Application servers. c. Click on your server (for example, server1). d. Select Java and Process Management Process Definition Java Virtual Machine. e. On the Generic JVM Arguments tab, enter the JVM parameters that are applicable to CEWS transport, as described in Chapter 2, Setting up development environments on page 13. f. Click OK. Click Save to save your changes. 7. Start your application in WebSphere: a. Select Applications Enterprise Applications. b. Select the ITSOFleetStatusManager check box. c. Click Start. Your application starts. 8. Launch your application from a browser: a. Open a Web browser. b. Navigate to: http://<YourAppServer:port>/ITSOFleetStatusManager/login.faces c. Log in by using a valid LDAP account.
298
2. Extract the swt.jar file (from the downloaded SWT ZIP archive) into the lib/ subdirectory. 3. Copy CE client JAR files to the lib/ subdirectory. JAR files include Jace.jar, log4j.jar, and other transport-dependent JAR files. For our sample setup, we use CEWS transport, assuming a P8 4.5.1 environment. Therefore, copy the applicable JAR files into the lib/ subdirectory. JAR files include stax-api.jar, xlxpScanner.jar, and xlxpScannerUtils.jar file. If you want to use EJB transport or use CEWS transport with a pre-4.5.1 environment, consult general setup instructions for those environments in Chapter 2, Setting up development environments on page 13.
299
2. Edit file billing_wsi.bat file. Ensure that the paths and environment variable values are correct for your environment. The script assumes that your current directory is the deploy/ directory and that dependent JAR files are located in the lib/ subdirectory. At a minimum, you should supply appropriate values for an ObjectStore name and the CE connection URI. 3. Run the billing_wsi.bat file. Further details of the running application are given in 7.3.5, User view: Billing Report application on page 237.
300
If you have chosen to follow our example and prepared the deploy/lib/ subdirectory with CEWS transport JARs for a P8 4.5.1 environment, all dependencies in the Eclipse project will probably be resolved automatically. Otherwise, you will have to make adjustments to the Eclipse build path for the project. We do not describe that here. Your view of the BillingReportApplication project in the Eclipse project explorer should look like Figure 7-43. Depending on your exact Eclipse version and your personal preference settings, the view could be somewhat different.
301
The BillingReportApplication project in Eclipse is set up to find source files in the src/ directory and compile them into the deploy/classes/ directory (which does not ordinarily show up in the Eclipse project explorer view). Dependent JAR files are found in the deploy/lib/ subdirectory. From the project explorer view, you can examine the source files at your leisure.
302
2. From the Eclipse menu bar, select Run Run Configurations. 3. The ReportApplication project should already be selected. If it is not, navigate to it. On the Main tab, the following Main class should already be filled in: itso.autorental.billingreport.ReportApplication If it is not filled in, enter that value. 4. Click the Arguments tab and provide the VM arguments setting, as shown in Figure 7-45. Be careful to put these in the VM arguments box and not the Program arguments box. Notice that these arguments are very similar to those used in the BAT file for the command line procedure in Running from the command line on page 300. They include (with values that must be adjusted for your environment): -Ddefault.objectstore.name=MyObjectStore -Djaas.stanza=FileNetP8WSI -Dce.uri=http://server.example.com:9080/wsi/FNCEWS40MTOM -Djava.security.auth.login.config="jaas.conf.WSI" 5. In the Working directory subpanel, select Other, click the Workspace button, and navigate to the BillingReportApplication/deploy/ directory. This is the same working directory we used when running from the command line.
303
6. Click Apply and click Close. You now have the correct run configuration for the Billing Report application. 7. Back in the Eclipse project, right-click the ReportApplication.java and select Run as Java application to run the Billing Report application. You should now see the main window of the Billing Report application. Further details of the running application are given in 7.3.5, User view: Billing Report application on page 237.
304
Chapter 8.
305
8.1 Logging
In this section, we describe how to enable logging for various FileNet APIs, including CE and PE Java API, CE .NET API, and Content Engine Web Services (CEWS). We also present several examples of interpreting the client-side API log files.
306
The benefit of this JVM argument method is the ability to change log4j log levels dynamically by simply modifying the log4j.properties file and does not require restarting the JVM.
307
DEBUG [WebContainer : 1] - Configuration for:BuildVersion value:dap440.247 applied This BuildVersion is useful to determine the exact CE API patch level you are using, and which helps when you are trying to identify a particular patch level that you must be on for a particular bug fix. This BuildVersion is also useful in determining whether your client CE APIs are of the same version as your CE server. CE server also outputs the build number when logging is enabled. You also see a message similar to Example 8-2 in your CE servers p8_server_trace.log file if the client and servers build versions do not match. The local version is always the version (from the point of view of the component) that is producing the log line.
Example 8-2 Mismatch build version message in CE Server trace file
2008-04-24T20:56:49.314Z B129CD3B API - The transport build version does not match the local build version: transport=dap000.441, local=dap435.029
Thread Identifiers
Because client applications are likely to be multithreaded, multi-user environments, the CE Java API logs can become inundated with data across various threads and users. To follow the log entries for a particular thread, look at the thread ID, such as thread ID 3 in Example 8-3. The thread ID, which appears in all log lines, is the part inside [square brackets]. Formats of thread IDs vary from one application server to another.
Example 8-3 Thread identifier
DEBUG [WebContainer : 3] - UserContext.set() invoked in its creator Thread <885535944> for UserContext <null>.
Request / Response
The request and data that are sent to the CE server, as well as the resulting response, can be useful when troubleshooting issues. Example 8-4 on page 309 shows an example of an outgoing executeSearchRequest call and Example 8-5 on page 309 shows the corresponding result. The format of the logged data is
308
logically similar to, but not the same as, the corresponding CEWS data on the wire. When similar data is logged on the CE server, the hard line breaks are replaced with the character sequence \n so that logging stays on a single line.
Example 8-4 executeSearchRequest call
2009-03-25 14:08:16,078 DEBUG [WebContainer : 3] <executeSearchRequest clientCaller="com.filenet.ae.bean.datasource.CeQuery.executeQuery(CeQue ry.java:191)" maxElements="200" continueable="true" rid="1"> <searchMode type="SearchMode" value="1" rid="2"/> <searchScope type="ObjectStoreScope" rid="3"> <objectStore type="GlobalIdentity" classIdentity="ObjectStore" identity="{5B4ADE2D-2FCC-4D8E-AFFC-B406A7123235}" rid="4"/> </searchScope> <search type="RepositorySearch" searchSQL="SELECT [VersionStatus], [IsReserved], [Id], [MajorVersionNumber], [DateLastModified], [DocumentTitle], [MinorVersionNumber], [ContentSize], [CompoundDocumentState], [ClassDescription], [IsCurrentVersion], [VersionSeries], [LastModifier], [MimeType] FROM Document WHERE THIS INFOLDER '{4DC50869-7E4E-4EFF-9CEA-0D413B0E48EB}' ORDER BY DocumentTitle" rid="5"> <propertyFilter type="PropertyFilter" rid="6"> <includePropertyList size="0" rid="7"/> <includeTypeList size="0" rid="8"/> <excludePropertyList size="0" rid="9"/> </propertyFilter> </search> </executeSearchRequest>
Example 8-5 Corresponding executeSearchResponse
2009-03-25 14:08:16,078 DEBUG [WebContainer : 3] <executeSearchResponse elapsed="0" rid="1"> <value type="RepositoryRowCollection" stale="false" rid="2"> <list size="2" rid="3"> <entry type="RepositoryRow" rid="4"> <properties type="RepositoryRowProperties" rid="5"> <property type="PropertyInteger32" name="VersionStatus" dirty="false" access="1" rid="6"> <value>1</value> </property> <property type="PropertyBoolean" name="IsReserved" dirty="false" access="1" rid="7"> <value>false</value> </property>
309
<property type="PropertyId" name="Id" dirty="false" access="1" rid="8"> <value type="Id">{C9712786-4B17-4512-9E13-9F4154B35FC2}</value> </property> <property type="PropertyInteger32" name="MajorVersionNumber" dirty="false" access="1" rid="9"> <value>1</value> </property> <property type="PropertyDateTime" name="DateLastModified" dirty="false" access="1" rid="10"> <value>2009-03-19T20:16:31.406Z</value> </property> <!-- ... portions omitted ... --> <paging type="DefaultPaging" rid="44"> <connection type="Connection" uri="iiop://hqdemo1:2810/FileNet/Engine" asURI="iiop://hqdemo1:2810/FileNet/Engine" rid="45"> <parameters type="ConfigurationParameters" rid="46"> <values size="0" rid="47"/> </parameters> </connection> </paging> </value>
</executeSearchResponse>
310
311
8.2 Troubleshooting
In this section, we describe troubleshooting techniques for CE and PE. We also discuss the data that you must gather so that the IBM support team can help you with troubleshooting.
312
If you do not see these lines, most likely log4j is configured but the log4j.properties file is being picked up in a different location. This can occur when a custom application uses its own packaging of log4j. To determine that information, you can enable log4js debug mode by setting the following JVM parameter: -Dlog4j.debug=true This setting generates output in System.out similar to Example 8-8.
Example 8-8 log4j debug output log4j: Trying to find [log4j.xml] using context classloader sun.misc.Launcher$AppClassLoader@a39137. log4j: Trying to find [log4j.xml] using sun.misc.Launcher$AppClassLoader@a39137 class loader. log4j: Trying to find [log4j.xml] using ClassLoader.getSystemResource(). log4j: Trying to find [log4j.properties] using context classloader sun.misc.Launcher$AppClassLoader@a39137. log4j: Using URL [file:/C:/classpath/log4j.properties] for automatic log4j configuration. log4j: Reading configuration from URL file:/C:/whatever/log4j.properties ...
Writing great code with the IBM FileNet P8 APIs, Part 2: Spying on your handiwork Techniques for seeing what you're putting on the wire
http://www.ibm.com/developerworks/data/library/techarticle/dm-0902carpenter
313
314
Appendix A.
Additional material
This book refers to additional material that can be downloaded from the Internet as described below.
315
316
Related publications
The publications listed in this section are considered particularly suitable for a more detailed discussion of the topics covered in this book.
IBM Redbooks
For information about ordering these publications, see How to get Redbooks on page 318. Note that some of the documents referenced here may be available in softcopy only. IBM FileNet Content Manager Implementation Best Practices and Recommendations, SG24-7547 Introducing IBM FileNet Business Process Manager, SG24-7509 IBM FileNet P8 Platform and Architecture, SG24-7667 Understanding IBM FileNet Records Manager, SG24-7623 IBM Content Manager OnDemand Web Enablement Kit Java APIs: The Basics and Beyond, SG24-7646
Online resources
These Web sites are also relevant as further information sources: IBM FileNet P8 Platform main information page
http://www.ibm.com/software/data/content-management/filenet-p8-platform
IBM FileNet P8 Platform product documentation http://www.ibm.com/support/docview.wss?rs=3247&uid=swg27010422 The above URL includes links to all expansion IBM FileNet P8 products. IBM FileNet Content Manager
http://www.ibm.com/software/data/content-management/filenet-content-manager
317
IBM FileNet Business Process Manager http://www.ibm.com/software/data/content-management/filenet-business -process-manager IBM InfoSphere Enterprise Records http://www.ibm.com/software/data/content-management/filenet-recordsmanager/
318
Index
Symbols
.NET environment setup 29 .NET API 34, 40, 48, 55, 270, 306, 310 126, 132, 188189, 192 Java Compatibility Layer, Content Engine (CE) 6 Java, Content Engine 14 Java, IBM InfoSphere Enterprise Records 8 Java, Process Engine 7, 114, 121, 124 log file, IBM FileNet 305 PE API 269, 293, 297 PE API classes, functional relationship 118 PE API, core classes 116 PE error handling class 117 PE REST API 112113, 140, 144, 150 PE REST API, scenario 188 PE REST API, service 207, 215 PE retrieve work status classes 117 PE search work classes 117 PEWS API 114 Process Engine (PE) 114115, 119 REST API 7, 112, 114, 123, 188, 190, 193 REST Services, Process Engine 7 workflow definition related 113 API set 4, 67 Application Engine (AE) 2, 9, 100, 168, 312 application environment 299 application programming interface See API application server 10, 4445, 48, 119120, 123, 127, 142, 146, 176, 188, 191, 276, 285, 289, 306, 308, 311 container 154, 160, 193 documentation 261, 292, 296 application space 187 architecture ECM Widgets 205 sample applications 268 association property 94 Attachment widget 202, 205, 208 authentication in .NET 45 in Java 44 PE 120 authorization 88 accessing REST operations 123
A
access 88 access control entry 88, 108, 257 access control list (ACL) 88, 258 access permission manipulation in C# 89 manipulation in Java 88 accessing Document content in C# 63 in Java 62 AccessPermission 88 AccessRight.DELETE permission 8889 active content 102 Admin package CE API 41 administration API API administration related 113 advanced document recognition (ADR) 9 annotation 99100 annotations property 94 API 1, 34, 13, 3941, 80, 88, 94, 96, 111114 .NET 34, 40, 48, 55, 270 .NET API 306, 310 CE .NET API, installing 30 CE API, patch level, 308 CE Java 268, 273 CE Java API 306308 CE Java API code 306 CE Java API log 308 CE Java API log4j environment 306 CE Java API trace file 308 COM Compatibility Layer 67 configuration 113 eForms 8 exception 123 Java 34, 67, 40, 44, 48, 104, 112114, 124,
319
B
batch refresh versus no refresh 81 retrieval 81 retrieving items in batch 83 transactional operation 81 updates 81 updating objects in batch 82 Billing Report application 224, 237239 architecture 274 user view 237 binary 279 BOOTSTRAP_ADDRESS 17 building SQL using IBM FileNet Enterprise Manager 72
C
cache, metadata 106 callback 103, 127128, 142143, 179, 189, 191, 194 cascading style sheet (CSS) 97, 211 CE 25, 13, 3940, 72, 87, 119, 121, 168, 176, 239, 263264, 272, 275, 305 API class model 40 gather information for troubleshooting 314 Java API 4, 7, 14 Java Compatibility Layer API 6 Query Builder 73 sample Java application setup 22 URI 120, 125 Web service 5 WSDL 5 CE .NET API installing 30 CE API class model 40 Core package 41 Events package 42 patch level 308 type 40 CE Java API 268, 273, 306308 code 306 log 308 log4j environment 306 trace file 308 CE_Operations 176, 263 CEWS 31, 306 CEWS transport 6, 14, 21, 23, 4546, 294,
298299, 310 requirements 1819 CFS-IS 9, 100 check in document 90 document in C# 93 document in Java 92 check out document in C# 93 document in Java 92 class model CE API 40 client thick versus thin 15 Collection package CE API 42 collection properties 54 COM Compatibility Layer API 67 programming 7 component association 171 document 97 operation 171 package 172 Component Manager 176, 184186, 286, 290291 configuration 185 parameters 185 component queue 168, 170171, 182, 184, 263, 287288 configuring and testing 182 programmatic creation 182 ComponentRelationship 97 compound document manipulation 97 configurable set 306, 311 configuration API 113 connection 43 initial connection 43 initial connection in C# 49 initial connection with EJB transport in Java 47 initial connection with Web services transport in Java 47 making initial connection 44 connection point 119 connectivity troubleshooting 21 containment relationship 95 CONTAINS 76
320
content active content 102 retrieving 6162 content element 6163, 65, 99, 247 metadata items 62 volatile position number 99 working with, in C# 65 working with, in Java 63 Content Engine See CE Content Engine (CE) troubleshooting 313 Content Engine (CE) API Admin package 41 Collection package 42 Meta package 41 Property package 42 Query package 42 Security package 41 Content Engine Web Services See CEWS Content Federation Services for Image Services See CFS-IS content repository IBM FileNet 8 content search 76 content size 62 content type 62 content-based retrieval (CBR) 76 ContentElement using 63 contents.iterator 173 ContentUrl 79 context root deployed Web application 218 convenience method 44, 65, 269, 273 convertMethod() 116 Core package CE API 41 corresponding ITSORole object user populations 260 create instance 82 createMethod() 116 creating object in C# 53 in Java 53 custom class 181 custom database 172 custom inheritance 110
Custom object 44, 52, 58, 94, 149, 169170 properties collection 57 custom widget building 206
D
Data Access Object (DAO) 172 data type 105, 144, 149150, 168 definition 106 deleting object 60 in C# 61 in Java 60 Demo_Java.zip 23 deployed Web application context root 218 deploying widget 217 deployment, sample applications 276 description 106 development setup for PE REST API sample code 33 setup, ECM Widgets 38 development environment setup,Java 13 discover metadata at runtime 105 DNS 17 document check in and out in C# 93 check in and out in Java 92 checked-in 90 compound document, manipulation 97 filing in a folder in C# 97 filing in a folder in Java 96 retrieve a document 92 viewing 78 Document content direct accessing in C# 63 direct accessing in Java 62 Document doc 60, 77, 84, 173 document file type 78 Document object 4, 62, 77, 90, 169 DocumentSet document 173 Dojo library 33 Dojo toolkit 210 client 127, 142, 146, 188, 191, 193 domain 44 doMethod() 116 DynamicReferentialContainmentRelationship (DRCR) 96
Index
321
E
Eclipse 22 ECM Widget 38, 201202, 205 development setup 38 mashup page 202 system architecture 205 eForms API 8 EJB transport 14, 20, 47, 176, 293294, 296 requirement 20 element sequence number 62 EngineRuntimeException 49 Enterprise Information System (EIS) 168 Enterprise JavaBeans See EJB transport environment setup for .NET 29 setup, Java 13 error callback 128, 143, 189, 191, 194 error recovery 123 event handler 104 asynchronous 103 synchronous 103 event log 117, 129, 137, 162, 262 optimizing query 139 retrieving work items 138 work items 139 event logging categories 137 event subscription 103 Events package CE API 42 exception API 123 runtime 49 exception handling in C# 50 in Java 50 Process Engine (PE) 124 exception handling, Process Engine (PE) 123
FetchInstance() 71 fetchless instantiation 71 performance advantage 71 fetchMethod() 116 fetchProperties 58 filing a document in folder in C# 97 in folder in Java 96 filter.addIncludeProperty 6768, 84 Fleet Status Manager Web application architecture 272 deployment 296 fnlog4j.properties 311 folder 95 filing a document in C# 97 filing a document in Java 96 franchise location 109, 225, 257 business objects 261 maintenance employees 110 maintenance records 110 FREETEXT 76 full-text search 76
G
Get Next widget 208, 210 building 206 building solution with 219 defining 211 rendering 215 use case 207 getInstance 4649, 58, 70 getMethod() 116 graphical user interface (GUI) 202, 302 thick desktop Java application 299
H
HTTP GET 154 HTTP PUT 154
F
Factory.Domain.getInstance 4648, 6061, 84, 9697 fetching object in C# 59 in Java 59 fetching queue element 215 fetchInstance 58
I
IBM FileNet API 223, 305 log file 305 API library 80 Business Process Manager 7 Capture 2, 8 Content Manager 46
322
content repository 8 Enterprise Manager 2, 168 Image Services 9 P8 deployment 1 Platform 2, 9, 168, 187 IBM FileNet Business Process Manager 111, 125 IBM FileNet Content Manager 67, 90, 108 IBM FileNet Enterprise Manager 280, 295, 310 building SQL 72 CE server logging 310 Query Builder 73 IBM FileNet P8 5, 7, 233, 238239 deployment 1 object Id 53 Platform 12, 5, 177 Platform documentation 72 product 3 resource 44 support site 308 IBM InfoSphere Enterprise Records 2, 4, 8 Java API 8 identity code 244245 ninth position 244 other types 245 vehicle 244 IdleActivity 53 Image Services (IS) 9 CFS-IS in-basket 187, 202 In-basket widget 204 IndependentlyPersistableObject 81 IndependentObject 81 inheritance custom inheritance, security 110 security 108 initial connection 44, 47, 121, 272, 275 integrated development environment (IDE) 299 INTERSECTION merged scope search 75 iScope Dojo class 213 isMethod() 116 isolated region 137 ITSO_Operations 264 ITSOChargesSchedule 245 ITSOCustomObject 249, 257 ITSOFranchiseCode 244, 257258 ITSORentalActivity 245 ITSORole object 110, 244, 258260, 262
same set 258 ITSOVehicle 244 ITSOVehicleActivity 248250, 252253 iWidget specification 202, 205, 211
J
J2EE application 4, 10, 168, 225, 268, 273 server 293, 296 server container 103 JAAS 4, 44, 46, 48, 172, 176, 182 JAAS stanza 46 Jace.jar 14 Java adapter 170, 172 Java API 34, 6, 40, 44, 48, 104, 112114, 124, 126, 132, 188189, 192 Java application setup for sample, Content Engine 22 stand-alone 15 Java archive (JAR) resource 182 Java Authentication and Authorization Service See JAAS Java business class 172 Java component 170 Java development environment setup 13 Process Engine 28 setup 27 Java gateway class 175 Java Messaging System (JMS) 168 Java virtual machine See JVM JavaScript Object Notation See JSON JOIN, merged scope search 75 JSON MIME type 112 object 127, 142 JVM 28, 121, 294, 298, 304, 306307, 313 JVM parameter required for thick client application 16
K
Kiosk application 62, 224, 231 user view 230
L
LDAP registry 123
Index
323
local cache property 58 log file API 305 size and rollover 307 thread identifier 308 log4j environment 306 log4j.jar 14 log4j.properties 306307, 313 login 176
M
maintenance employee 109110, 233, 253, 257 major version 90, 92 manipulation of compound document 97 mashup container 202 mashup page 202, 204, 206 widget 218 merged scope search 75 Meta package CE API 41 metadata 53 cache 106 discover at runtime 105 object 41, 283 minor version 90 multi-page file 61 multi-page scanned document 61 multi-valued property 54 property, setting 55 property, setting in C# 56 property, setting in Java 56 multi-valued object-valued property See MVOVP MVOVP 94, 243, 245246 My Work Page 202
deleting object 60 fetching, in C# 59 fetching, in Java 59 retrieving 42, 58 object store 4, 4344, 46, 72, 74, 104, 149, 151, 153, 168, 263, 272273, 275, 288289 search cross object stores 75 ObjectChangeEvent event (ONEVENT) 104 object-valued property (OVP) 54, 94, 109, 243244, 249 optimizing event log query 139 optimizing queue query 135 optimizing, queue 135 ORDER BY, merged scope search 75
P
p8_api_trace.log 307 paging support, result set 76 PE 13, 105, 111113, 126, 132, 135, 167168, 170, 187, 235, 270, 272, 305, 311 authentication 120 connection point 295 exception handling 123124 gather information for troubleshooting 314 Java API 7, 114, 121, 124 Java development project 28 Java development setup 27 maintenance queue 175 object 163 REST API 112, 199 REST Services API 7 server 121 session 119, 121, 125, 139 troubleshooting 313 Web service 7 Web Service Policy object 122 Web services 112 PE API 114115, 119, 121, 124, 269, 293, 297 application polling component queue 184 core classes 116 object 119 object method 115 other sets 112 usage tip 119 PE API classes functional relationships 118 PE error handling class 117 PE query, optimizing 130
N
Next widget 207, 210211
O
object creating object 52 creating object in C# 53 creating object in Java 53 deleting in C# 61 deleting in Java 60
324
PE REST API 113, 140, 144, 150 PE REST API sample code development setup 33 scenario 188 PE REST sample application 33 PE REST service 207, 215, 312 PE retrieve work status classes 117 PE search work classes 117 PE session class 116 establish 119 object 181 PEComponentQueueHelper 183 pending action 52 performance boost, property filter 66 eliminating round trips 68 eliminating round trips in C# 69 eliminating round trips in Java 69 getInstance() versus fetchInstance() 71 limiting returned properties in C# 68 limiting returned properties in Java 67 optimizing PE queries 130 permission AccessRight.DELETE 8889 PEWS 32, 112, 119, 131, 158, 311 PEWS API 114 PEWS client 126, 132, 135 PEWS RequestSoapContext header creating 122 Post Once Exactly (POE) 127128 precompiled binary 279 process application 143 Process Configuration Console 137, 187 Process Designer 187 Process Engine See PE Process Engine Web Service See PEWS process history, retrieving 162 process status 162 Process Task Manager 170 programming COM Compatibility Layer 7 programming language 94 properties collection 54, 95, 104 property 53 annotations 94
association property 94 limiting returned properties for performance in C# 68 limiting returned properties for performance in Java 67 local cache 58 multi-valued 54 reflective property 94 single-valued 54 property filter 58, 6669, 71 boost performance 66 eliminate round trips for performance 68 eliminate round trips for performance in C# 69 eliminate round trips for performance in Java 69 limiting returned properties for performance in C# 68 limiting returned properties for performance in Java 67 Property package CE API 42 property value 42 retrieving 56 retrieving in C# 57 retrieving in Java 57 PropertyFilter 58
Q
query 135 building with SearchSQL 72 building with SearchSQL in C# 72 building with SearchSQL in Java 72 optimizing event log 139 optimizing, PE 130 queues 134 Query Builder Content Engine (CE) 73 IBM FileNet Enterprise Manager 73 Query package CE API 42 queue optimizing query 135 query 134 queue element 114, 195197, 207, 212 fetching 215 first page 197 queue name 114, 119, 135136, 141142, 190, 192, 194
Index
325
R
RCR 96 Redbooks Web site 318 Contact us xviii ReferentialContainmentRelationship (RCR) 96 reflective property 94 refresh batch 81 relationship containment relationship 95 repository IBM FileNet 8 Representational State Transfer (REST) 7, 112 request URI 127, 142, 146 reservation 91 reservation state 90 Reservation Web application 224, 264, 268 program flow 268 user view 226 ReservationType.EXCL USIVE 92 reserved state 91 resource navigation 199 REST API 7, 112, 114, 123, 188, 190, 193 resource 112 resource request 123 scenario 154, 188, 197 REST operation authorization for accessing 123 result set, paging support 76 retrieval name 62 retrieve items in batch 83 retrieving batch 81 retrieving content 6162 using Document object 62 retrieving object 42, 58 retrieving property value 56 in C# 57 in Java 57 retrieving work items 138 role 187 retrieving role description 189 retrieving role list 188 role-based access control (RBAC) 109 round trips eliminating for performance 68 eliminating for performance in C# 69 eliminating for performance in Java 69 runtime exception 49
S
sample application 96, 100, 104, 106, 122, 172, 223224, 226, 232233, 238239, 245, 250, 316 architecture 268 Billing Report application 224, 237239 Billing Report application, architecture 274 Billing Report application, user view 237 business use cases 224 data import files 240 deployment 276 distinct purposes 258 Fleet Status Manager Web application, architecture 272 Fleet Status Manager Web application, deployment 296 Java-based components 279 Kiosk application 62, 224, 231 Kiosk application, user view 230 metadata customization 279 PE REST sample application 33 Reservation Web application 224, 264 Reservation Web application, program flow 268 Reservation Web application, user view 226 security 249 security model 261 workflow 262 sample code 212, 215, 217, 224, 226 search 71 content search 76 cross object stores 75 example in C# 74 example in Java 73 INTERSECTION 75 JOIN 75 merged scope search 75 ORDER BY 75 result set, paging support 76 UNION 75 WHERE 75 work items from workbasket 194 search object 170 search operation 129 search scope 7475 SearchScope class 71 SearchSQL 69, 7174, 77, 107108, 173 security 90 custom inheritance 110 dynamic inheritance 108 sample applications 249
326
security model, sample applications 261 Security package, CE API 41 security proxy property 110 security template 170 send mail 170 session 116 PE session, establish 119 session object 126, 132, 135, 141, 144, 150, 177, 181, 188, 190, 192, 195 setMethod() 116 SetProcessSecurityToken 45 SetThreadSecurityToken 45 setting property value multi-valued property 55 multi-valued property, in C# 56 multi-valued property, in Java 56 single-valued property 54 single-valued property, in C# 55 single-valued property, in Java 55 Single Page 202 single-valued property 54 property, setting 54 property, setting in C# 55 property, setting in Java 55 SOAP header request 119, 122 source object 103 SQL building using IBM FileNet Enterprise Manager 72 SQL statement 7173 Standard Widget Toolkit (SWT) 274, 299 Step Completion widget 204 step element 114, 140, 142, 148 parameter values updating 154 parameters 143 parameters retrieving 144, 146 retrieving 140141 step processor 113, 138, 140, 156 Step Processor Page 203 String password 179 subscription event 103 workflow 105 synchronous event handler 103 system queue 134
CEWS transport requirements 1819 required JVM parameters 16 thin client 15, 22 CEWS transport library requirements 22 CEWS transport requirement 21 EJB transport requirement 20 thread Identifier log file 308 trace log p8_api_trace 307 REST Service, Application Engine 312 transactional operation, batch 81 transport 2021, 46 CEWS requirements 1819 CEWS transport 21, 294, 298299, 310 EJB transport 14, 20, 45, 47, 176, 293294, 296 protocols 14 troubleshooting 312 CE server logging 310 connectivity 21 Content Engine (CE) 313314 Process Engine (PE) 313314
U
unfile object 169 Uniform Resource Identifier (URI) 15, 43, 119120, 188189, 191 UNION, merged scope search 75 update objects in batch 82 updating batch 81 user queue 134 user token 80 UserContext 44
V
vehicle barcode 232 identity code 244 See also VIN version 90 version series object 90 Viewer widget 202, 205 VIN 245246 VisualStudio.NET, configuring 30 VWAttachmentType 115 VWFetchType 115 VWQueue 115 VWQueue queue 135, 141, 174, 192, 195
T
thick client 15, 22
Index
327
VWQueueDefinition 115 VWQueueElement 115 VWRoster 115 VWRosterDefinition 115 VWRosterElement 115 VWSession object 117, 119120, 188189, 192 VWQueue object 192, 194 VWRole object 189 VWWorkObjectNumber 132, 135, 141
W
WcmApiConfig.properties 28, 120 Web application 7, 9, 209210, 218, 233, 292, 296 applicable JSF configuration 292, 296 Web service 3, 56, 4546, 48, 112, 119120, 168, 176 Content Engine (CE) 5 Process Engine (PE) 7 Web Service Definition Language See WSDL Web services interface (WSI) 5, 46 WebSphere Business Space 202 WHERE, merged scope search 75 Widget ECM 202 ECM Widget 201, 205 ECM Widgets, development setup 38 widget 202, 221, 274, 279, 299 Attachment widget 202, 205, 208 building custom widget 206 deploying 217 Get Next 215 Get Next widget 208, 210 Get Next widget defining 211 Get Next widget use case 207 Get Next widget, building solution 219 In-basket widget 204 mashup page 218 Next widget 207, 210211 Step Completion widget 204 Viewer widget 202, 205 wiring widget 202 Work Data widget 202, 205 WOB Number 274 Work Data widget 202, 205 displays customer-defined field 205 work item 170, 187, 204, 221, 235, 263 completing 156, 160
helper data 130 query first page 194 query from workbasket 194 retrieving 138 work object 113, 127, 132, 184 participant information 162 resource URL 127 VWProcess object 162, 165 work object number 142 work performer 140 work queue 134, 236, 266267 work search operation 129 workbasket 187, 191, 193, 200202 retrieving 192 workbasketName 191, 193, 197 workbasketURI 199 workflow 129, 139, 162, 262263 activity tracking 162 attachments 148 logs 139 participants 148 response list 204 roster 129 sample applications 262 workflow definition 105, 112113, 125, 140, 148, 168, 262, 265, 267, 288 data fields 168 specific step 140 workflow definition API 113 workflow event action 105 tracking 137 workflow history 162164 step history objects 162 workflow milestone 162 retrieving 165 workflow process 117, 125127 milestones definition 165 retrieving and launching 125 step history data 117 workflow subscription 105 WorkplaceRootUrl 79 WSDL 5, 29, 112, 121 Content Engine (CE) 5
328
Back cover
Content Engine basic and advanced APIs Process Engine basic and advanced APIs REST API, ECM Widgets, sample applications, and more
This IBM Redbooks publication can help you develop content and process management applications with IBM FileNet APIs. The IBM FileNet P8 suite of products contain a set of robust APIs that range from core platform APIs to supporting application APIs. This book focuses specifically on Content Engine and Process Engine APIs. Content Engine API topics that we discuss include creating, retrieving, updating, and deleting objects; querying and viewing documents; and batching and batch execution. We also explore more complex topics, including permissions and authorization, versioning, relationships, annotations, workflow subscriptions and event actions, metadata discovery, and dynamic security inheritance. Process Engine API topics that we discuss include launching a workflow, searching for and processing work items, and working with process status. The more complex topics we cover include, Component Integrator application space, role, workbasket, resource navigation in Process Engine REST API, ECM Widgets, and building a custom Get Next In-basket widget. To help you better understand programming with IBM FileNet APIs, we provide a sample application implemented for a fictional company. We include the data model, security model, workflows, and various applications developed for the sample. You can download them for your reference. This book is intended for IBM FileNet P8 application developers. We recommend using this book in conjunction with the online ECM help.
BUILDING TECHNICAL INFORMATION BASED ON PRACTICAL 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.