WebSphere Business Integration Server Foundation Using the programming API

advertisement

Front cover

WebSphere Business Integration

Server Foundation

Using the programming API and the Common Event Infrastructure

Understanding the business process engine API

Using the common event infrastructure

Code examples and solutions

Bill Moore

Michael Bader

Jing Liu

Reynaldo Mincov

Venkatesh Patil

Red

paper

ibm.com/redbooks

International Technical Support Organization

Using the WebSphere Business Integration Server

Foundation Programming APIs

April 2005

Note: Before using this information and the product it supports, read the information in

“Notices” on page vii.

First Edition (April 2005)

This edition applies to Version 5.1.1 of WebSphere Business Integration Server Foundation and

Version 5.1.1 of WebSphere Studio Application Developer Integration Edition for use on

Windows.

Note to U.S. Government Users Restricted Rights -- Use, duplication or disclosure restricted by GSA ADP

Schedule Contract with IBM Corp.

Contents

Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii

Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . viii

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

The team that wrote this Redpaper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

Become a published author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xii

Comments welcome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xii

Chapter 1. Business Process Engine programming . . . . . . . . . . . . . . . . . . 1

1.1 Business Process Engine API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

1.1.1 BPE API overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

1.2 Developing applications for BPEL based processes . . . . . . . . . . . . . . . . . 27

1.2.1 Accessing the session API bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

1.2.2 Accessing the Business Process Choreographer JMS interface . . . 29

1.2.3 Starting a process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

1.2.4 Claiming work items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

1.2.5 Canceling work items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

1.2.6 Completing work items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

1.3 Authorization and security using the API. . . . . . . . . . . . . . . . . . . . . . . . . . 42

1.3.1 Process authorization authorities . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

1.3.2 Authorization for the EJB API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

1.3.3 Authorization for the JMS API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

1.3.4 Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

1.4 Exception and fault handling using the API. . . . . . . . . . . . . . . . . . . . . . . . 47

1.4.1 Handling API exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

1.4.2 Handling faults using the BPE API . . . . . . . . . . . . . . . . . . . . . . . . . . 50

1.5 API reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

1.5.1 Process templates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

1.5.2 Starting and terminating processes. . . . . . . . . . . . . . . . . . . . . . . . . . 54

1.5.3 Details for process instances and activities . . . . . . . . . . . . . . . . . . . 61

1.5.4 Variables and custom properties. . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

1.5.5 Message handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

1.5.6 Work items, staff activities, and administration methods . . . . . . . . . 69

1.5.7 Queries and worklists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

1.5.8 Other API methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

1.6 Sample scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

Chapter 2. Common Event Infrastructure programming . . . . . . . . . . . . . . 93

2.1 CEI introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

© Copyright IBM Corp. 2004. All rights reserved.

iii

2.1.1 Business level event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

2.1.2 Common Base Event model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

2.1.3 CEI architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

2.2 Working with events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

2.2.1 Creating an event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112

2.3 Event source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118

2.3.1 Different ways of event generation . . . . . . . . . . . . . . . . . . . . . . . . . 118

2.3.2 Using Java code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118

2.4 Event monitoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

2.4.1 Viewing events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

2.4.2 Event consumer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134

2.5 Correlation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154

2.6 Sample code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161

2.6.1 Event source sample code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161

2.6.2 Event consumer sample code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

2.6.3 Purging events sample code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163

Chapter 3. Business Process Choreographer and CEI . . . . . . . . . . . . . . 165

3.1 Business processes and CEI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166

3.2 Emitting Business Process Choreographer events . . . . . . . . . . . . . . . . . 168

3.3 Using Business Process Choreographer events . . . . . . . . . . . . . . . . . . . 169

3.3.1 Using the CBE viewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170

3.3.2 Retrieving events from the data store . . . . . . . . . . . . . . . . . . . . . . . 170

3.3.3 Retrieving events from topics and queues . . . . . . . . . . . . . . . . . . . 171

3.4 Business Process Choreographer event reference. . . . . . . . . . . . . . . . . 172

3.4.1 CBE properties common to Business Process Choreographer events.

173

3.4.2 Process instance events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175

3.4.3 Activity events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

3.4.4 Variable event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180

3.4.5 Link events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181

3.5 Sample scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182

3.5.1 Calculating statistics for processes and activities . . . . . . . . . . . . . . 182

3.5.2 Triggering actions on specific events . . . . . . . . . . . . . . . . . . . . . . . 192

Appendix A. Additional material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197

Locating the Web material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197

Using the Web material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197

System requirements for downloading the Web material . . . . . . . . . . . . . 198

How to use the Web material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198

Appendix B. Configuration and setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199

Configuring CEI on unit test environment. . . . . . . . . . . . . . . . . . . . . . . . . . . . 200

Creating a CEI Enabled server and server configuration . . . . . . . . . . . . . . . . 200

iv Using the WebSphere Business Integration Server Foundation Programming APIs

Setting a JMS provider for the server configuration . . . . . . . . . . . . . . . . . . . . 202

Configuring WebSphere Embedded Messaging as the JMS provider . . . 203

Configuring MQ Simulator for Java developers as the JMS provider . . . . 205

Configuring security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207

Configuring for working with Message Driven Bean event consumer . . . . . . 209

Installing and setting up the Redpaper samples . . . . . . . . . . . . . . . . . . . . . . 212

Importing the sample code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212

Setting up sample projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217

Abbreviations and acronyms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221

Related publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223

IBM Redbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223

Online resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223

How to get IBM Redbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224

Help from IBM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224

Contents v

vi Using the WebSphere Business Integration Server Foundation Programming APIs

Notices

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

IBM may not offer the products, services, or features discussed in this document in other countries. Consult your local IBM representative for information on the products and services currently available in your area.

Any reference to an IBM product, program, or service is not intended to state or imply that only that IBM product, program, or service may be used. Any functionally equivalent product, program, or service that does not infringe any IBM intellectual property right may be used instead. However, it is the user's responsibility to evaluate and verify the operation of any non-IBM product, program, or service.

IBM may have patents or pending patent applications covering subject matter described in this document.

The furnishing of this document does not give you any license to these patents. You can send license inquiries, in writing, to:

IBM Director of Licensing, IBM Corporation, North Castle Drive Armonk, NY 10504-1785 U.S.A.

The following paragraph does not apply to the United Kingdom or any other country where such provisions

are inconsistent with local law: INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES

THIS PUBLICATION "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,

INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,

MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Some states do not allow disclaimer of express or implied warranties in certain transactions, therefore, this statement may not apply to you.

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

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

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

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

This information contains examples of data and reports used in daily business operations. To illustrate them as completely as possible, the examples include the names of individuals, companies, brands, and products.

All of these names are fictitious and any similarity to the names and addresses used by an actual business enterprise is entirely coincidental.

COPYRIGHT LICENSE:

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

© Copyright IBM Corp. 2004. All rights reserved.

vii

Trademarks

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

Eserver ®

E server ®

Redbooks (logo)

Eserver® ibm.com®

™ z/OS®

Cloudscape™

DB2®

ETE™

IBM®

Perform™

Redbooks™

Redbooks (logo)™

RUP®

WebSphere®

The following terms are trademarks of other companies:

Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun

Microsystems, Inc. in the United States, other countries, or both.

Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the

United States, other countries, or both.

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

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

viii Using the WebSphere Business Integration Server Foundation Programming APIs

Preface

This Redpaper describes the application programming interfaces (APIs) used to interact with the WebSphere Business Integration Server Foundation V5.1

Business Process Container. It also investigates how to use the Common Event

Infrastructure (CEI) API to log, retrieve, and manage events from the Business

Process Container. We wrote this Redpaper as a practical guide for developers who need to write code that uses these APIs. We provide practical code examples and implementation samples so that developers can understand how to code using the available APIs.

Our Redpaper assumes that readers are already familiar with WebSphere

Business Integration Server Foundation and WebSphere Studio Application

Developer Integration Edition. We do not attempt to provide extensive background on these prerequisite products, so if you need a more comprehensive introduction to WebSphere Business Integration Server

Foundation and development with WebSphere Studio Application Developer

Integration Edition read the IBM Redbook WebSphere Business Integration

Server Foundation V5.1 Handbook, SG24-6318.

The team that wrote this Redpaper

This Redpaper was produced by a team of specialists from around the world working at the International Technical Support Organization, Raleigh Center.

Bill Moore is a WebSphere specialist at the International Technical Support

Organization, Raleigh Center. He writes extensively and teaches classes on

WebSphere and related topics. Before joining the ITSO, Bill was a Senior AIM

Consultant at the IBM Transarc laboratory in Sydney, Australia. He has 19 years of application development experience on a wide range of computing platforms and using many different coding languages. He holds a Master of Arts degree in

English from the University of Waikato, in Hamilton, New Zealand. His current areas of expertise include application development tools, object-oriented programming and design, and e-business application development.

Michael Bader is an IT specialist working in the WebSphere Solution Centre - lab-based services department in Boeblingen, Germany. He has worked with

IBM for more than six years, starting as a Software Engineer developing the

WebSphere Adapter for mySAP.com. His areas of expertise include Business

Process Choreographer, WebSphere Business Integration Server Foundation, ix © Copyright IBM Corp. 2004. All rights reserved.

J2EE technologies, JCA, and SAP. Michael holds a Diplom-Informatiker degree in Computer Science from the University of Stuttgart, Germany.

Jing Liu is an advisory software engineer in IBM Business Partner Technical

Enablement - WebSphere Competency Center. Jing has 9 years experience in software design, development, and service. She was with IBM WebSphere

Application Server development team since early 1999 and was involved with

WebSphere Portal proof of concept projects. Currently she provides developer-to-developer technical support and enablement services to premier

IBM business partners for the IBM WebSphere family products. Jing holds a

Masters degree in Electric Engineering from Shanghai Jiao Tong University,

China.

Reynaldo Mincov Junior is an IT Specialist at IBM Brazil, São Paulo. He holds a

Bachelor of Computer Science from Unifai - Centro Universitário Assunção, São

Paulo, Brazil. He joined IBM in 1999 and works as an analyst / programmer developing problem, incident, and change applications using ITIL (IT

Infrastructure Library) foundations.

Venkatesh Patil is a Software Architect working in IBM India Software Labs in

Bangalore. His areas of interest include business integration, software architecture, and industry solutions. He specializes in Java™, J2EE technology and is an IBM Certified Solution Developer for WebSphere Portal V5.0.

Venkatesh has worked with IBM for 2 years. He holds a graduate degree in

Mechanical Engineering from Karnataka Regional Engineering College,

Surathkal.

Figure 0-1 The authors: Venkatesh Patil, Michael Bader, Bill Moore, Reynaldo Mincov x Using the WebSphere Business Integration Server Foundation Programming APIs

Figure 0-2 Author: Jing Liu

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

Peter Kovari

International Technical Support Organization, Raleigh Center

Alexander Koutsoumbos

IBM Costa Mesa

Tian Chao

IBM Watson

Kurt Fleckenstein

Ulrike Knapp

Anke Robeller

IBM Germany

Special thanks to Neil Kolban (IBM Dallas) for permission to reuse material from his WebSphere Business Integration Server Foundation writings. Redpaper readers with access to the IBM intranet can view Neil’s writing at the following

Web address: http://submit.boulder.ibm.com/dd/wsdd/asis/502067/502067.html

Preface xi

Become a published author

Join us for a two-to-six week residency program! Help write an IBM Redbook dealing with specific products or solutions, while getting hands-on experience with leading-edge technologies. You will team with IBM technical professionals,

Business Partners, and customers.

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

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

ibm.com/redbooks/residencies.html

Comments welcome

We welcome your comments!

We want our Redpapers to help you. Send us your comments about this

Redpaper or other IBM Redbooks in one of the following ways:

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

ibm.com/redbooks

򐂰 Send your comments in an e-mail to: redbook@us.ibm.com

򐂰 Mail your comments to:

IBM Corporation, International Technical Support Organization

Dept. HZ8 Building 662

P.O. Box 12195

Research Triangle Park, NC 27709-2195 xii Using the WebSphere Business Integration Server Foundation Programming APIs

1

Chapter 1.

Business Process Engine programming

This chapter discusses the Business Process Engine API for use with Business

Process Choreographer applications running within WebSphere Business

Integration Server Foundation.

© Copyright IBM Corp. 2004. All rights reserved.

1

1.1 Business Process Engine API

The Business Process Choreographer is a powerful tool and runtime to develop and run business processes in a Java 2 Platform, Enterprise Edition(J2EE) environment. You can use these processes to integrate J2EE resources, Web services, and activities that require human interaction (Staff activities). Business

Process Choreographer manages the life cycle of business processes, navigates through the associated process model, invokes the appropriate Web services, and involves human persons to handle Staff activities. The business process runtime is provided by the Business Process Container that is part of WebSphere

Business Integration Server Foundation, the tool to model and develop business processes comes with WebSphere Studio Application Developer Integration

Edition.

After business processes are developed and deployed in WebSphere Business

Integration Server Foundation, the question of how to interact with these processes arises. Thus, the following actions require attention:

򐂰 The processes must be started.

򐂰 Staff activities have to be claimed and completed.

򐂰 Processes may wait for incoming messages (when using a Receive or Pick activity in the process model).

򐂰 Someone may be interested in the state of running or finished processes.

򐂰 An administrator may want to terminate certain process instances.

Business Process Choreographer provides several ways to achieve these actions. One possibility is to use the Business Process Web Client that comes with Business Process Choreographer. This is a JavaServer Pages (JSP) based client that can work with and administer processes and associated entities

(activities, work items, and so on.). Figure 1-1 on page 3 shows a screen shot of

the Web Client. The look and feel of the Business Process Web Client can be customized by providing user written JSPs.

2 Using the WebSphere Business Integration Server Foundation Programming APIs

.

Figure 1-1 Business Process Web Client

Note: You can find an article describing how to customize the Web Client at the following Web address: http://www-106.ibm.com/developerworks/websphere/library/techarticles/wasid/W

PC_Client1/WPC_Client1.html

In many cases the functionality provided by the Web Client is not suitable for customized solutions. For example, the Web client is not suitable in the following situations:

򐂰 A client requires a different look and feel.

򐂰 A portal client is needed.

򐂰 A console based or Java Swing based client is needed.

򐂰 Functionality to interact with processes and the Business Process Engine that hosts them is required in other J2EE components.

Business Process Choreographer fulfills such needs by providing a generic API,

Business Process Engine (BPE) API, that can be accessed via a stateless session enterprise bean (the Session API bean) and a Message Driven Bean listening to the BPE API queue. Whereas the Session API bean provides access to all available API methods, only a small subset of the methods (sendMessage, forceTerminate, call, and initiate) is supported via the Java Message Service

(JMS).

Chapter 1. Business Process Engine programming 3

Figure 1-2 shows the architecture of the Business Process Engine. On the left

side, you can recognize the BPE API exposed via a session and a Message

Driven Bean.

Note: In this Redpaper we assume that you are familiar with concepts and the architecture of Business Process Choreographer. We also assume that you are experienced in developing, deploying, and running business processes.

Please use the following references for details about those topics:

򐂰 http://www.ibm.com/developerworks/websphere/zones/was/wpc.html

򐂰 WebSphere Business Integration Server Foundation V5.1 Handbook,

SG24-6318

Figure 1-2 Business Process Engine architecture

When you generate deploy code for a process, a façade Enterprise JavaBean

(EJB) generates. This enterprise bean is process specific and can also interact with the process. The EJB contains methods to start a process instance and send messages to that instance; however, it does not support methods to claim and complete Staff activities that may be contained in that process. The rest of this chapter describes only the generic BPE API. Additionally, we only cover the

API methods dealing with BPEL processes.

4 Using the WebSphere Business Integration Server Foundation Programming APIs

Note: We only cover API methods to interact with Business process execution language (BPEL) processes. Interaction with Flow definition markup language

(FDML) processes are not described in this paper.

1.1.1 BPE API overview

This section gives a functional overview of the BPE API methods. For a better understanding, the methods are divided into several groups.

Several API methods make sense only when the activity or process instance to be manipulated by the API call is in a certain state. For example the repair functions for stopped activities require that the activity to be repaired is in the

stopped state. Please look at the BPE API Javadoc or use Figure 1-3 on page 6 and Figure 1-4 on page 6 containing process and activity state diagrams as a

hint.

Note: You can find the BPE API Javadoc in the WebSphere Infocenter and the WebSphere Studio Application Developer Integration Edition online help:

WebSphere Business Integration

Reference

Javadoc

Enterprise Extensions API

com.ibm.bpe.api

Please use the BusinessProcessService class to look at the API methods.

The following section in the online help also provides useful information:

WebSphere Business Integration

Developing

Applications

Process Choreographer

Developing applications for BPEL-based processes

The user calling the API method must have the necessary access rights. 1.3,

“Authorization and security using the API” on page 42 provides more details on

that topic.

Figure 1-3 on page 6 shows the possible states for a BPEL process.

Chapter 1. Business Process Engine programming 5

Figure 1-3 Process states

Figure 1-4 shows the possible states for an activity in a BPEL process.

Figure 1-4 Activity states

6 Using the WebSphere Business Integration Server Foundation Programming APIs

Process templates

There are two methods for retrieving process template data, and they are shown

in Table 1-1. The getProcessTemplate method returns the ProcessTemplateData

instance of the specified process template. The ProcessTemplateData instance contains information about the process template, for example the ValidFromDate, the process template ID, a description of the process template, the state of the

AutoDelete flag, and so on. Some of these properties are necessary to start a process.

The second method, queryProcessTemplates, retrieves process templates that match certain criteria. The arguments are similar to the ones of the query() call

described later in this chapter in the section “Queries” on page 17. Unlike the

query() method the queryProcessTemplates() method has no selectClause argument. The getProcessTemplate returns an array of ProcessTemplateData instances.

1.2, “Developing applications for BPEL based processes” on page 27 provides

some sample code using process templates.

Table 1-1 API methods for process templates

Method Description getProcessTemplate Retrieves the specified process template queryProcessTemplates Retrieves process templates persistently stored in the database

Starting processes

The Business Process Engine API offers a variety of methods to start the

process instances listed in Table 1-2 on page 8.

The call() method creates and executes a process instance. The caller waits synchronously for the result that is returned by the call() method via a

ClientObjectWrapper instance (this class will be explained in “Messages” on page 10). Since the call() method waits for the result, the started process has to

be non-interruptible (that is not long-running).

The callWithUISettings() method has the same characteristics as the call() method. Additionally, not only the result of the process execution is returned, but also the client UI settings. Latter properties can be used to render the result appropriately.

The callWithReplyContext() method also creates and executes a process instance, but it does not synchronously wait for the reply; instead, the caller can access the result via the passed ReplyContext at a later point in time.

Chapter 1. Business Process Engine programming 7

The initiate() method creates and initiates the execution of a process instance. It does not wait for the result of the process execution but returns immediately with the process instance ID (PIID) of the created process. This PIID can later be used to retrieve the state or the result of the process execution.

The API methods described above explicitly create process instances, but in

BPEL it is also possible to implicitly create process instances by sending messages to the Business Process Engine. If the addressed Receive or Pick activity in a BPEL process has the ‘Create a new process instance if one does not exist’ flag set to true, and there is no other process instance matching the correlation set values of the sent message, a new process instance is created and executed.

Of course the sendMessage() method sends messages to already existing processes waiting for input.

We did not have a look at the parameters passed to the methods that create and execute a process. In case the process template has a unique starting activity, you can pass the process template ID and the input message API methods to start processes (the initiate method has an additional parameter for the process instance name).

In case the process template has multiple starting activities, use the getStartingActivities() or the getActivityServiceTemplate() method to retrieve the desired starting service and pass it to the API methods for creating and executing a process.

“Developing applications for BPEL based processes” on page 27 provides some

code samples.

Table 1-2 API methods to start processes

Method Description call Creates and executes a process instance callWithReplyContext callWithUISettings initiate

Creates and executes a process instance from the specified process template and asynchronously waits for the result

Creates and executes a process instance and returns the output message as well as its client UI settings

Creates a process instance and initiates processing of the process instance

8 Using the WebSphere Business Integration Server Foundation Programming APIs

Method sendMessage getStartActivities (for processes with non-unique starting service) getActivityServiceTemplate

(for processes with non-unique starting service)

Description

Sends the specified message to the specified activity service and process instance

Returns information about activities that can start a BPEL process instance from the specified process template

Retrieves the specified activity service template

Terminating and deleting processes

Use the forceTerminate method to terminate a process. This method also terminates subprocesses and running, claimed, or waiting activities contained in the process. The caller of this method must be a process administrator.

When the autoDelete flag of the corresponding process template is set to false, finished, terminated, compensated, and failed, process instances stay in the BPE database. You can delete those instances using the delete() method. The caller

must be an administrator of the process instance. Table 1-2 on page 8 lists the

available termination and delete methods.

Table 1-3 API methods to terminate and delete processes

Method Description delete forceTerminate

Deletes the specified top-level process instance and its sub

Terminates the specified top-level process instance, its subprocesses, and its running, claimed, or waiting activities

Details for process instances and activities

In many cases you need more information about certain process or activity instances. Usually you have the process instance ID (PIID) or the activity instance ID (AIID) of the process or activity instance in which you are interested.

The getProcessInstance and getActivityInstance methods return instances of the

ProcessInstanceData or ActivityInstanceData class containing properties of the respective process or activity. For example the ProcessInstanceData contains information about the process state, the starter of the process, a description of the process, the process template name, and a lot more properties. The

ActivityInstanceData contains the process instance ID of the process, the activity

Chapter 1. Business Process Engine programming 9

kind, the owner of the activity, a description of the activity, and so on. Please review the Javadoc for the full range of provided properties.

Table 1-4 lists the methods that retrieve process and activity details.

Table 1-4 API methods to retrieve details for process instances and activities

Method Description getProcessInstance getActivityInstance

Retrieves information about the specified process instance

Retrieves information about the specified activity instance

Messages

The interaction with processes involves the exchange of messages. For example when starting a process you must provide an input message when dealing with a

Staff activity. The input data is provided via a message and you have to send the result of the Staff activity back to the Business Process Engine in the form of a message.

The Business Process Engine API provides get methods to retrieve input, output, and fault messages from activity and process instances. There are also createMessage methods available to create empty messages of the specified type.

In WebSphere Business Integration Server Foundation version 5.1.x messages are implemented as Web Services Invocation Framework (WSIF) messages. All

Business Process Engine API methods returning or passing messages as

parameters (not only the ones listed in Table 1-5 on page 11, but for example

also the methods to start a process) do not pass or expect the messages directly, but instead use the ClientObjectWrapper class. The ClientObjectWrapper class has a constructor taking a java.lang.Object argument and a getObject() method to retrieve the contained object.

Therefore when retrieving a message, you get a ClientObjectWrapper instance.

By invoking the getObject() method on that instance, the contained message can be retrieved. On the other hand, when passing a message, you have to wrap it in a ClientObjectWrapper instance by using the ClientObjectWrapper constructor with the message as argument.

When using the getObject() method on ClientObjectWrapper instances, cast the result to the appropriate message type. The Java classes for the message types reside in the service project of the process in the Java package ending with’_msg’.

10 Using the WebSphere Business Integration Server Foundation Programming APIs

Table 1-5 lists the methods used to interact with messages.

Table 1-5 API methods for message handling

Method Description createMessage Creates a message defined by the specified process template, process instance, or activity instance getInputMessage getOutputMessage getFaultMessage

Retrieves the input message of the specified activity or process instance

Retrieves the output message of the specified activity or process instance

Retrieves the fault message of the specified activity or process instance

As an alternative you can use the WSIFMessage interface directly to manipulate the message. This interface contains get/set methods for primitive data types, for example get/setBooleanPart, get/setIntPart, and so on, and arbitrary Java objects (get/setObjectPart). There is also a method to get hold of meta information about the message (getMessageDefinition). The code snippet in

Example 1-1 creates a message and sets the message part ‘input’ via the

setObjectPart() method.

Example 1-1 Create a message

...

IncidentInput inp = new IncidentInput(); inp.setName(name); inp.setStreet(street); inp.setCity(city);

...

ProcessTemplateData ptd = bp.getProcessTemplate("IncidentReport");

ClientObjectWrapper input = bp.createMessage(ptd.getID(), ptd.getInputMessageTypeName());

WSIFMessage msg = (WSIFMessage)input.getObject(); msg.setObjectPart("input", inp);

...

Variables and custom properties

The Business Process Engine API provides a get and a set method to retrieve and set values for BPEL variables. In WebSphere Business Integration Server

Foundation version 5.1.x ,variables are implemented as WSIF messages.

Therefore the get/setVariable methods return/expect a ClientObjectWrapper containing a WSIFMessage that matches the variable type. The code snippet in

Chapter 1. Business Process Engine programming 11

Example 1-2 shows how to retrieve a variable (in this case the BPEL variable

contains a part named ‘input’ of type IncidentInput).

Example 1-2 Retrieving a variable

...

BusinessProcess process = ...

PIID piid = ...

ClientObjectWrapper wrapper = process.getVariable(piid, "InputVariable");

WSIFMessage msg = (WSIFMessage)wrapper.getObject();

IncidentInput inp = (IncidentInput)msg.getObjectPart("input");

...

The API also offers the possibility to associate and retrieve named properties

with or from process and activity instances as listed in Table 1-6. Custom

property names and values must be of type java.lang.String. Custom properties

can be used in queries (explained later in this chapter in “Queries” on page 17).

Unfortunately in the current implementation, queries can include at most one custom property.

Table 1-6 API methods for variables and custom properties

Method Description getVariable setVariable

Retrieves the specified variable

Sets the specified variable getCustomProperty setCustomProperty

Retrieves the named custom property of the specified activity or process instance

Stores custom-specific values for the specified activity or process instance

Work items

Whenever the Business Process Engine needs to deal with human interaction, for example when executing a Staff activity or when waiting for an event in a

Receive or Pick activity, it creates appropriate work items. As shown in Figure 1-5 on page 13, a work item represents a relationship between a user, a reason or

role and a Business Process Choreographer entity (process or activity instance).

12 Using the WebSphere Business Integration Server Foundation Programming APIs

Figure 1-5 Work item as relation between a user, a reason, and an activity or process.

A work item allows a specific user to act on the respective activity or process instance according to the specified role. For example let us assume user U was assigned a work item W with reason Potential Owner for Staff activity A by the

Business Process Engine. This work item enables user U, for example, to claim and complete the Staff activity A.

Usually work items are created by the Business Process Engine according to the

staff assignments specified in the process model. Table 1-7 summarizes the

events that cause the Business Process Engine to create work items. The table also lists the work items created for each event.

Table 1-7 Creation of work items

Event Work items created for

A process is started 򐂰 The process starter

򐂰 Each process reader

򐂰 Each process administrator

A staff activity becomes ready 򐂰 Each potential owner of the activity

򐂰 Each reader of the activity

򐂰 Each reader of the process

򐂰 Each editor of the activity

A staff activity is claimed Activity owner

The claim of a staff activity is cancelled

A receive/pick activity is activated

An unhandled failure occurs in an activity of a process

The work item for the activity owner is deleted

Each potential sender of the event

Process administrator

Beyond the process model driven creation of work items, Business Process

Choreographer also offers the possibility to create, delete, and transfer work

Chapter 1. Business Process Engine programming 13

items manually by using appropriate API methods as listed in Table 1-7 on page 13. For example, imagine the case where an employee leaves the company

and his/her work items have to be deleted or transferred to other people, or when the staff query specified in the process model results in an empty set of persons, in that case the process administrator can manually create work items.

The getWorkItems method retrieves all work items for the logged-on user. In order to execute the getAllWorkItems method the caller must have reader authority for the associated process instance, be the process administrator, or be the business process administrator. getAllWorkItems returns all work item assignments associated with the specified activity or process instance.

Table 1-8 API methods for work items

Method Description createWorkItem Creates a work item deleteWorkItem transferWorkItem getWorkItems getAllWorkItems

Deletes the specified work item

Transfers a work item for a specified user

Retrieves work item assignments for the logged-on user

Retrieves all work item assignments

Business Process Choreographer offers the possibility to manually refresh staff assignments by executing a script coming with the product

(refreshStaffQuery.jacl). The Business Process Engine considers previous createWorkItem, deleteWorkItem, and transferWorkItem calls as shown in

Figure 1-6 on page 15.

Note: You can find details on how to run the refreshStaffQuery.jacl script in the WebSphere Infocenter:

WebSphere Business Integration Server Foundation

Administering

Applications

Process Choreographer

Refreshing staff entries that are cached in the database

14 Using the WebSphere Business Integration Server Foundation Programming APIs

Figure 1-6 Refreshing staff queries

Staff activities

When the Business Process Engine navigates a Staff activity, it creates work items for each potential owner, reader, editor, and so on, and puts the Staff activity in the Ready state where it waits till one of the potential owners claims this activity, indicating that he or she takes responsibility for completing the work assignment. The person that claimed the activity becomes the owner of the Staff activity. At every point in time, at most one person can be the owner of a Staff activity, that is if another person tries to claim an already claimed activity this results in an exception.

The owner of a Staff activity can cancel the claim, allowing other potential owners to claim this activity. The owner can also transfer the work item to other potential owners. Owner and editors of the Staff activity can modify the output message (result) of the Staff activity and save it in the Business Process Engine database, for example if the human task represented by the Staff activity is rather complex and intermediate results should be persistently stored. At some point in time the owner of the Staff activity can complete the human task by invoking the complete method and passing the result in form of the output message to the

Business Process Engine.

Table 1-9 on page 16 list methods in the BPE API for working with staff activities.

Chapter 1. Business Process Engine programming 15

Table 1-9 API methods for staff activities

Method Description claim cancelClaim

Claims a ready activity instance for user processing

Cancels the claim of an activity instance complete setOutputMessage

Completes a claimed activity instance

Stores the output message of the specified activity instance in the database

Repairing stopped activities

For Invoke activities, the Business Process Choreographer offers the possibility to specify the Continue On Error flag. If this flag is set to false and an unhandled error occurs while executing the Invoke activity, the Business Process Engine puts the Invoke activity in the Stopped state and creates a work item for the

process administrator. You can use the methods listed in Table 1-10 to repair the

stopped activity.

The process administrator can call the forceRetry method to cause the Business

Process Engine to execute the Invoke activity again. Or he can set the output message or an appropriate fault message (via setOutputMessage / setFaultMessage) and call the forceComplete method. Depending on the message, the Business Process Engine puts the Invoke activity in completed or failed state and continues the execution of the process instance. Please also see

Figure 1-4 on page 6, particularly the outgoing arrows from the stopped state.

Table 1-10 API methods to repair stopped activities

Method Description forceComplete (invoke) forceRetry

Forces the completion of a stopped activity instance

Forces the repetition of a stopped activity instance setFaultMessage setOutputMessage

Stores the specified fault message for the specified activity instance in the database

Stores the output message of the specified activity instance in the database

The Continue On Error flag and the associated repair functions can, for example, be used in a long running process where an Invoke activity fails from time to time

16 Using the WebSphere Business Integration Server Foundation Programming APIs

in rare cases; however, the effort to model compensation and fault handling is often high or not possible.

Queries

Business Process Choreographer provides a very powerful query() method to retrieve information about process or activity instances. For example this method retrieves the work items of the currently logged-on user, or gets all process instances that are in a certain state.

The query is executed against the Business Process Engine database. There are several predefined views that are used for queries:

򐂰 PROCESS_TEMPLATE

򐂰 PROCESS_INSTANCE

򐂰 PROCESS_ATTRIBUTE

򐂰 ACTIVITY

򐂰 ACTIVITY_ATTRIBUTE

򐂰 ACTIVITY_SERVICE

򐂰 WORK_ITEM

The columns of these views are described in Table 1-12 on page 20, Table 1-13

on page 21, Table 1-14 on page 21, Table 1-15 on page 22, Table 1-16 on

page 23, Table 1-17 on page 24, and Table 1-18 on page 24.

Note: The article at the following Web address describes the query API in detail: http://ibm.com/developerworks/websphere/library/techarticles/wasid/WPC_Queri es/WPCQueries.html

The query() method takes five arguments: a select clause, a where clause, an orderBy clause, a threshold, and a time zone. The select clause specifies the columns of the views in which you are interested. The where clause specifies filter criteria and the orderBy clause defines the ordering of the returned result.

All clauses are specified in a SQL like syntax.

The query() call returns a QueryResultSet instance that is used similar to a

JDBCResultSet to retrieve the rows and columns of the result. In particular cursor based navigation is used to access the rows of the result set.

After positioning the cursor on the desired row via next(), first(), last(), and previous(), you can call type specific get methods to retrieve the values of the row. For example getString(columnIndex) gets a String value, getOID(columnIndex) to get PIIDs, AIIDs, and so on.

Chapter 1. Business Process Engine programming 17

Note: Please see the article at http://ibm.com/developerworks/websphere/library/techarticles/wasid/W

PC_Queries/WPCQueries.html

or the query() Javadoc for a detailed description.

Important: As for SQL, column indices start with ‘1’ instead of ‘0’.

The code snippet in Example 1-3 shows an example query. It queries AIID, PIID,

the process instance name, and the value of a custom property named ‘abstract’ for activities of template ‘AssessIncident’ that are in the Ready state and the currently logged-on user is a potential owner.

Example 1-3 Using the query() method

BusinessProcess process = getBusinessProcessEjb();

QueryResultSet result = process.query(

"ACTIVITY.AIID, ACTIVITY.PIID, PROCESS_INSTANCE.NAME,

PROCESS_ATTRIBUTE.VALUE",

"ACTIVITY.STATE = ACTIVITY.STATE.STATE_READY

AND WORK_ITEM.REASON = WORK_ITEM.REASON.REASON_POTENTIAL_OWNER

AND PROCESS_ATTRIBUTE.NAME='abstract'

AND ACTIVITY.TEMPLATE_NAME='AssessIncident'", null, null, null); while (result.next()) {

AIID aiid = (AIID) result.getOID(1);

PIID piid = (PIID) result.getOID(2);

String processInstanceName = result.getString(3);

String abstract = result.getString(4);

// process data

...

}

If you are familiar with SQL you may have wondered about the missing from clause. The implementation of the query() method derives the from clause from the information given in the select and where clauses and joins the appropriate tables. It implicitly also joins the WORK_ITEM table, ensuring that the query result only contains items for which the currently logged-on user has the necessary rights.

18 Using the WebSphere Business Integration Server Foundation Programming APIs

Note: In case the returned QueryResultSet contains less rows than you expected, you may not have the necessary rights to see the missing ones.

Tip: In case the QueryResultSet contains unexpected results, you can turn on tracing with trace specification set to com.ibm.bpe.data=all=enabled. This causes the Business Process Engine to print out the calculated SQL statement in the trace file. You can analyze this statement and maybe adjust your query. For example in some rare cases the join condition of the tables is wrong resulting in an empty result set. You can circumvent this by providing certain additional columns in the select clause, which leads to additional tables being considered that may correct the join conditions.

Note: As seen in Example 1-3 on page 18, you can use custom attributes in

queries. Unfortunately at the moment you can only specify at most one custom attribute per query.

Table 1-11 list the available API methods used for queries.

Table 1-11 API methods for queries

Method Description query getAllActivities

Retrieves selected object properties persistently stored in the database

Queries predefined activity instance properties of activities directly contained in the specified process instance

The getAllActivities() method queries predefined activity instance properties of activities directly contained in the specified process instance. The returned

QueryResultSet instance contains the following columns:

1. AIID

2. Name

3. Execution state

4. Kind

5. Activation time

The caller of getAllActivities() must have reader authority for the process instance, be the process administrator, or be the business process administrator.

Chapter 1. Business Process Engine programming 19

Table 1-12, Table 1-13 on page 21, Table 1-14 on page 21, Table 1-15 on

page 22, Table 1-16 on page 23, Table 1-17 on page 24, and Table 1-18 on page 24 list the columns of the predefined views:

Note: You can access the database views directly, for example using SQLJ.

This Redpaper only describes queries using the query() API method.

Table 1-12 PROCESS_TEMPLATE view

Column name Type

PTID ID

NAME

APPLICATION_NAME

String

String

VALID_FROM

VERSION

CREATED

STATE

DESCRIPTION

CATEGORY

CAN_RUN_SYNC

String

Time stamp

String

String

CAN_RUN_INTERRUP Boolean

EXECUTION_MODE

Time stamp

Integer

Boolean

Integer

Comments

The process template ID

The name of the process template

The name of the enterprise application to which the process template belongs

The time from when the process template is instantiated

User-defined version.

The time the process template is created in the database

Specifies whether the process template is available to create process instances.

Possible values: STATE_STARTED

STATE_STOPPED

Description of the process template

The category to which the process template belongs

Specifies if the process can be invoked by call()

Specifies if the process can be invoked by initiate()

Specifies how process instances derived from this process template can be run.

Possible values are:

EXECUTION_MODE_MICROFLOW

EXECUTION_MODE_LONG_RUNNIN

G

20 Using the WebSphere Business Integration Server Foundation Programming APIs

Column name

COMP_SPHERE

Type

Integer

Comments

Specifies the compensation behavior of process instances derived from this process template; either an existing compensation sphere is joined or a compensation sphere is created.

Possible values for top-level processes are:

COMP_SPHERE_NOT_SUPPORTED

COMP_SPHERE_REQUIRES_NEW

Possible values for subprocesses are:

COMP_SPHERE_REQUIRED

COMP_SPHERE_SUPPORTS

Table 1-13 PROCESS_ATTRIBUTE view f

Column name Type

PIID ID

NAME

VALUE

String

String

Comments

The ID of the process instance that has a client property

The name of the client property

The value of the client property

Table 1-14 PROCESS_INSTANCE view

Column name Type

PTID ID

PIID

NAME

STATE

ID

String

Integer

CREATED

STARTED

Time stamp

Time stamp

Comments

The process template ID

The process instance ID

The name of the process instance.

The state of the process instance.

Possible values: STATE_READY

STATE_RUNNING STATE_FINISHED

STATE_COMPENSATING

STATE_INDOUBT STATE_FAILED

STATE_TERMINATED

STATE_COMPENSATED

STATE_TERMINATING

STATE_FAILING

The time the process instance is created

The time the process instance is started

Chapter 1. Business Process Engine programming 21

Column name

COMPLETED

PARENT_NAME

TOP_LEVEL_NAME

STARTER

TEMPLATE_NAME

String

String

TEMPLATE_DESCR String

TEMPLATE_CATEGO

RY

DESCRIPTION

String

String

Type

Time stamp

String

String

Comments

The time the process instance is completed

The name of the parent process instance

The name of the top-level process instance. This name is the current process instance if there is no top level.

The principal ID of the starter of the process instance

The name of the associated process template

Description of the associated process template

The category to which the associated process template belongs

If the description of the process template contains placeholders, this column contains the description of the process instance with the placeholders resolved.

Table 1-15 ACTIVITY view

Column name Type

PIID ID

AIID

PTID

ATID

KIND

ID

ID

ID

Integer

Comments

The process instance ID

The activity instance ID

The process template ID

The activity template ID

The kind of activity. Possible values:

KIND_INVOKE KIND_RECEIVE

KIND_REPLY KIND_THROW

KIND_TERMINATE KIND_WAIT

KIND_COMPENSATE

KIND_SEQUENCE KIND_EMPTY

KIND_SWITCH KIND_WHILE

KIND_PICK KIND_FLOW

KIND_SCOPE KIND_SCRIPT

KIND_STAFF KIND_ASSIGN

22 Using the WebSphere Business Integration Server Foundation Programming APIs

Column name

RUN_MODE

ACTIVATED

STARTED

COMPLETED

STATE

OWNER

TEMPLATE_NAME

TEMPLATE_DESCR

DESCRIPTION

BUSINESS_RELEVAN

CE

Type

Integer

Time stamp

Time stamp

Time stamp

String

String

String

String

String

Boolean

Comments

Possible values: Zero for BPEL-based processes

The time the activity is activated

The time the activity is started

The time the activity is completed

The state of the activity. Possible values:

STATE_INACTIVE STATE_READY

STATE_RUNNING STATE_SKIPPED

STATE_FINISHED STATE_FAILED

STATE_TERMINATED

STATE_CLAIMED

STATE_TERMINATING

STATE_FAILING STATE_WAITING

STATE_EXPIRED STATE_STOPPED

Principal ID of the owner

Name of the associated activity template

Description of the associated activity template

If the activity template description contains placeholders, this column contains the description of the activity instance with the placeholders resolved.

Specifies whether activities are audited.

Possible values are:

TRUE The activity is business relevant and it is audited.

FALSE Auxiliary step.

Table 1-16 ACTIVITY_ATTRIBUTE view

Column name Type

AIID ID

NAME

VALUE

String

String

Comments

The ID of the activity instance that has a client property

The name of the client property

The value of the client property

Chapter 1. Business Process Engine programming 23

Table 1-17 ACTIVITY_SERVICE view

Column name Type

EIID

AIID

PIID

ID

ID

ID

VTID ID

PORT_TYPE

NAME_SPACE_URI

OPERATION

String

String

String

Table 1-18 WORK_ITEM view

Column name Type

WIID ID

OWNER_ID

EVERYBODY

String

Boolean

OBJECT_TYPE Integer

OBJECT_ID

ASSOC_OBJECT_TYPE

ID

Integer

Comments

The ID of the event instance

The ID of the activity waiting for the event

The ID of the process instance that contains the event

The ID of the service template that describes the event

The name of the port type

The URI of the name space

The operation name of the service

Comments

The work item ID

The principal ID of the owner

Specifies whether everybody owns this work item

The type of the associated object. Possible values:

OBJECT_TYPE_ACTIVITY

OBJECT_TYPE_PROCESS_INSTANCE

OBJECT_TYPE_EVENT

The ID of the associated object, for example, the associated process or activity

The type of object associated with, or containing, the associated object of the work item. Possible values:

OBJECT_TYPE_ACTIVITY

OBJECT_TYPE_PROCESS_INSTANCE

OBJECT_TYPE_EVENT

24 Using the WebSphere Business Integration Server Foundation Programming APIs

Column name

ASSOC_OID

REASON

Type

ID

Integer

Comments

The ID of the object associated with, or containing, the associated object of the work item-For example, the process instance ID (PIID) of the process instance containing the activity instance for which this work item was created.

The reason for the assignment of the work item. Possible values:

REASON_POTENTIAL_OWNER

REASON_EDITOR REASON_READER

REASON_OWNER REASON_STARTER

REASON_ADMINISTRATOR

Worklists

You can store commonly used queries in the BPE database under a name by using the newWorkList API method. The method takes the same arguments as

the query() method described in “Queries” on page 17 and stores the query

under the specified name.

To actually execute the stored query, the executeWorkList method is called, passing the name of the worklist. It returns the results in a QueryResultSet instance as though you executed the query with the query() method directly.

In case a stored worklist is no longer needed, you can delete it using the deleteWorkList method. The methods newWorkList and deleteWorkList require that the logged-on user is the business process administrator.

The getWorkList method provides the capability to retrieve details about the stored query. It returns an instance of the WorkListData class, providing get methods to retrieve, for example, the select and where clause of the associated query.

The getWorkListNames method returns the names of all available worklists in a

String array. getWorkListActions returns an array of the worklist actions, create worklists, delete worklists, execute worklists, and so on, that the currently logged-on user can perform. For example if the logged-on user is not the business process administrator the returned array does not contain the right to create or delete worklists.

Table 1-19 on page 26 shows the API methods used for handling worklists.

Chapter 1. Business Process Engine programming 25

Table 1-19 API methods worklists

Method Description newWorkList deleteWorkList

Creates a worklist and persistently stores it in the database

Deletes the specified worklist executeWorkList getWorkList getWorkListActions getWorkListNames

Executes the query defined by the worklist and returns the qualifying object properties

Retrieves the specified worklist definition

Returns the actions that the logged-on user can call related to worklists

Retrieves the names of worklists persistently stored in the database

The code snippet in Example 1-4 shows the creation of a very simple worklist.

The query returns the process instance IDs of processes where the process instance name starts with ‘A’:

Example 1-4 Creating a worklist process.newWorklist("PIIDsForProcessesStartingWithA",

"DISTINCT PROCESS_INSTANCE.PIID",

"PROCESS_INSTANCE.NAME LIKE ’A%’",

"PROCESS_INSTANCE.NAME", null, null);

Other API methods

Table 1-20 on page 27 lists the remaining API methods that do not fit in any of

the categories previously discussed.

The BPEL editor allows you to set client user interface (UI) settings wherever staff assignments are possible. These settings can be retrieved via API methods and used to render the user interface appropriately.

The isBusinessProcessAdministrator method returns true in case the logged-on user is a business process administrator; otherwise, false is returned.

The getFaultNames method retrieves the fault names defined for the specified activity instance.

26 Using the WebSphere Business Integration Server Foundation Programming APIs

Table 1-20 Other API methods

Method getClientUISettings

Description

Retrieves client interface settings for the specified process template, activity, or process instance getInputClientUISettings getOutputClientUISettings getFaultNames isBusinessProcessAdministr ator

Retrieves client interface settings for the input message of the specified process instance

Retrieves client interface settings for the output message of the specified process instance

Retrieves the fault names defined for the specified activity instance

Indicates whether the logged-on user is a business process administrator

1.2 Developing applications for BPEL based processes

This section provides code samples for common tasks that occur when developing applications for BPEL based processes.

1.2.1 Accessing the session API bean

Use the following steps to access the stateless session API bean:

1. Add a reference in the application deployment descriptor as shown in

Example 1-5 or Example 1-6.

Example 1-5 Remote Interface - BusinessProcess interface

<ejb-ref>

<ejb-ref-name>ejb/BusinessProcessHome</ejb-ref-name>

<ejb-ref-type>Session</ejb-ref-type>

<home>com.ibm.bpe.api.BusinessProcessHome</home>

<remote>com.ibm.bpe.api.BusinessProcess</remote>

</ejb-ref>

Example 1-6 Local Interface - LocalBusinessProcess interface

<ejb-local-ref>

<ejb-ref-name>ejb/LocalBusinessProcessHome</ejb-ref-name>

<ejb-ref-type>Session</ejb-ref-type>

Chapter 1. Business Process Engine programming 27

<local-home>com.ibm.bpe.api.LocalBusinessProcessHome</local-home>

<local>com.ibm.bpe.api.LocalBusinessProcess</local>

</ejb-local-ref>

2. If you are running the Business Process Container in a different Java Virtual

Machine (JVM), package the files located in the

WebSphere/AppServer/ProcessChoreographer/client/bpe137650.jar file with the enterprise archive (EAR) file of your application.

3. Set the Class-Path parameter in the manifest file of the application module to include the bpe137650.jar file. The application module can be a J2EE application, a Web application, or an EJB application.

4. Make the home interface of the BusinessProcess session bean available to the application using Java Naming and Directory Interface (JNDI) lookup

mechanisms as shown in Example 1-7 and Example 1-8.

Example 1-7 Remote Interface

// Obtain the default initial JNDI context

Context initialContext = new InitialContext();

// Lookup the remote home interface of the BusinessProcess bean

Object result = initialContext.lookup("java:comp/env/ejb/BusinessProcessHome");

// Convert the lookup result to the proper type

BusinessProcessHome processHome =

(BusinessProcessHome)javax.rmi.PortableRemoteObject.narrow

(result,BusinessProcessHome.class);

The home interface of the BusinessProcess session bean contains a create() method for EJB objects. The method returns the remote interface of the session bean.

Example 1-8 Local Interface

// Obtain the default initial JNDI context

Context initialContext = new InitialContext();

// Lookup the local home interface of the LocalBusinessProcess bean

LocalBusinessProcessHome processHome =

(LocalBusinessProcessHome)initialContext.lookup

("java:comp/env/ejb/LocalBusinessProcessHome");

The home interface of the LocalBusinessProcess session bean contains a create() method for EJB objects. The method returns the local interface of the session bean.

28 Using the WebSphere Business Integration Server Foundation Programming APIs

5. Access the interface of the session bean.

– Remote Interface:

BusinessProcess process = processHome.create();

– Local Interface:

LocalBusinessProcess process = processHome.create();

6. Call the business functions exposed by the BusinessProcessService interface, for example: process.initiate("MyProcessModel",input);

Calls from applications are run as transactions. A transaction is established and ended in one of the following ways:

– Automatically by WebSphere Application Server (the deployment descriptor specifies TX_REQUIRED).

– Explicitly by the application. You can bundle application calls into one

transaction as shown in Example 1-9.

Example 1-9 Establish a transaction

// Obtain user transaction interface

UserTransaction transaction=

(UserTransaction)initialContext.lookup("jta/usertransaction");

// Begin a transaction transaction.begin();

// Applications calls ...

// On successful return, commit the transaction transaction.commit();

1.2.2 Accessing the Business Process Choreographer JMS interface

Important: The WebSphere Infocenter and the WebSphere Studio

Application Developer Integration Edition online help state that Business

Process Choreographer version 5.1.x supports JMS TextMessage and

ObjectMessage. This is wrong! Only ObjectMessage is supported.

An application that sends or receives JMS messages must:

1. Create a connection to Business Process Choreographer. Use Java Naming and Directory Interface (JNDI) lookup to retrieve the connection factory. The

JNDI-lookup name must be the same as the name specified when the

Chapter 1. Business Process Engine programming 29

Business Process Choreographer external request queue is configured.

Example 1-10 shows an example of creating this connection.

Example 1-10 Creating a connection to Business Process Choreographer

// Obtain the default initial JNDI context

Context initialContext = new InitialContext();

// Look up the connection factory

QueueConnectionFactory queueConnectionFactory =

(QueueConnectionFactory) initialContext.lookup("jms/BPECF");

// Create connection

QueueConnection queueConnection = queueConnectionFactory.createQueueConnection();

2. Create a session so that message producers and consumers can be created

as shown in Example 1-11.

Example 1-11 Creating a session

//Create a nontransacted session using autoacknowledgement

QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

3. Create a message producer to send messages. The JNDI-lookup name must be the same as the name specified when the Business Process

Choreographer external request queue is configured as shown in

Example 1-12.

Example 1-12 Message producer

// Look up the destination of the process choreographer queue

// to send messages to

Queue bpeQueue = (Queue) initialContext.lookup("jms/BPEApiQueue");

// Create message producer

QueueSender queueSender = queueSession.createSender(bpeQueue);

4. Create a message consumer to receive replies. The JNDI-lookup name must specify a user-defined destination to which replies are sent as shown in

Example 1-13.

Example 1-13 Message consumer

// Look up the destination of the reply to queue

Queue replyToQueue = (Queue) initialContext.lookup("MyReplyToQueue");

// Create message consumer

QueueReceiver queueReceiver = queueSession.createReceiver(replyToQueue);

5. Send requests and receive replies as shown in Example 1-14 on page 31.

30 Using the WebSphere Business Integration Server Foundation Programming APIs

Example 1-14 Sending and receiving replies

// Create message and send

ObjectMessage message = queueSession.createObjectMessage();

//message.SetStringProperty(..);

//message.setObject(...); queueSender.send(message);

// Receive message and analyze reply

// See the detailed task descriptions for examples

Message reply = queueReceiver.receive();

// Start sending and receiving messages queueConnection.start();

6. Close the connection to the free resources as shown in Example 1-15.

Example 1-15 Closing the connection

// Final housekeeping: free resources queueConnection.close();

A number of JMS message properties are available that you can set on the message by the caller before it is written to the queue. You can set these properties by executing the following: message.setStringProperty(name, value) where name

is one of the types listed in Table 1-21.

Table 1-21 JMS message properties

Name Description wf$verb wf$processTemplateName

The type of request being asked to be performed on the Process Server

This can be one of:

• initiate – Invoke a process but do not expect a response.

• call – Invoke a process and expect a response.

• forceTerminate

• sendEvent

The name of the Process Template to be invoked wf$piid This is the process instance identifier associated with this instance of the process

Chapter 1. Business Process Engine programming 31

Name wf$processInstanceName wf$eventName wf$processState wf$exceptionText

Description

The name of the process instance. You can use this name with the forceTerminate and the sendEvent functions to identify the process instance to process. You can use it with the call and the initiate functions to specify the process instance name of the process instance to create.

The name of the event to send. You must set this value for the sendEvent function.

The state of the process instance. Set this value in reply message.

This is a property that can be returned and indicates an exception occurred.

The body of the message is a ClientObjectWrapper contained in a JMS

ObjectMessage.

1.2.3 Starting a process

This section describes how to start a Business Process using the API.

You can start a new instance of a business process by knowing the name of the process template and creating an instance of an input message to be passed to the process as a initial input when it is started. The input message must be contained within a ClientObjectWrapper.

You can start either an interruptible or a non-interruptible process via API. There are two methods that can start a new instance of a business process:

򐂰 call()

򐂰 initiate()

The call() method is used when you are running a non-interruptible process that blocks the caller until a response is available. Use the initiate() method when you run either an interruptible or a non-interruptible process. This allows a process to run asynchronously with the caller.

Non-interruptible process

You can develop the following applications for non-interruptible processes based on the Business Process Execution Language (BPEL):

32 Using the WebSphere Business Integration Server Foundation Programming APIs

– Run a non-interruptible process using the Enterprise JavaBean (EJB) interface. The application depends on whether the process contains a unique starting service or a non-unique starting service.

– Run a non-interruptible process using the Java Message Service (JMS) interface.

Running a process that contains a unique starting service

If the starting service is unique, you can use the call method and pass the process template name as a parameter. The starting service is unique if the non-interruptible process starts with a receive activity or when the pick activity has only one onMessage definition.

Use the following steps to start the process:

1. This step is optional if you already know the name of the process.

List the process templates to find the name of the non-interruptible process

you want to run. See Example 1-16.

Example 1-16 Listing process templates

ProcessTemplateData[] processTemplates = process.queryProcessTemplates

("PROCESS_TEMPLATE.CAN_RUN_SYNC=TRUE",

"PROCESS_TEMPLATE_NAME",

newInteger(50),

null);

The results are sorted by name. The query returns an array containing the first 50 sorted templates that the call method can start.

2. Start the process with an input message of the appropriate type. When you create the message, you must specify its message type name so that the

message definition is contained. See Example 1-17.

Example 1-17 Starting the process with an input message.

ProcessTemplateData template = processTemplates[0];

//create a message for the single starting receive activity

ClientObjectWrapper input = process.createMessage

(template.getID(),

template.getInputMessageTypeName());

WSIFMessage myMessage = (WSIFMessage)input.getObject();

//set the parts in the message, for example, a customer name myMessage.setObjectPart("CustomerName", "Smith");

//run the process

ClientObjectWrapper output = process.call(template.getName(), input);

WSIFMessage myOutput = (WSIFMessage)output.getObject();

Chapter 1. Business Process Engine programming 33

int order = myOutput.getIntPart("OrderNo");

This action creates an instance of the process template, CustomerTemplate, and passes some client data. The operation returns only when the process is complete. The result of the process, OrderNo, is returned to the caller.

Running a process that contains a non-unique starting service

If the starting service is not unique, meaning that the non-interruptible process starts with a pick activity that has multiple onMessage definitions, then you must identify the service to be called.

Use the following steps to start the process:

1. This step is optional if you already know the name of the process.

List the process templates to find the name of the non-interruptible process

you want to run. See Example 1-18.

Example 1-18 Listing the process templates

ProcessTemplateData[] processTemplates = process.queryProcessTemplates

("PROCESS_TEMPLATE.EXECUTION_MODE.EXCECUTION_MODE_MICROFLOW",

"PROCESS_TEMPLATE_NAME",

newInteger(50), null);

The results are sorted by name. The query returns an array containing the first 50 sorted templates that can be started as non-interruptible processes.

2. Determine the starting service to be called. See Example 1-19.

Example 1-19 Starting service to be called

ProcessTemplateData template = processTemplates[0];

ActivityServiceTemplateData startActivities =

process.getStartActivities(template.getID());

3. Start the process with an input message of the appropriate type. When you create the message, you must specify its message type name so that the

message definition is contained. See Example 1-20.

Example 1-20 Starting the process

ActivityServiceTemplateData activity = startActivities[0];

//create a message for the service to be called

ClientObjectWrapper input =

process.createMessage(activity.getServiceTemplateID(),

activity.getActivityTemplateID(),

activity.getInputMessageTypeName());

WSIFMessage myMessage = (WSIFMessage)input.getObject();

34 Using the WebSphere Business Integration Server Foundation Programming APIs

//set the parts in the message, for example, a customer name myMessage.setObjectPart("CustomerName", "Smith");

//run the process

ClientObjectWrapper output = process.call(activity.getServiceTemplateID(),

activity.getActivityTemplateID(),

input);

//check the output of the process, for example, an order number

WSIFMessage myOutput = (WSIFMessage)output.getObject(); int order = myOutput.getIntPart("OrderNo");

This action creates an instance of the process template, CustomerTemplate, and passes some client data. The operation returns only when the process is complete. The result of the process, OrderNo, is returned to the caller.

Running a process using the JMS interface

You can use the Java Message Service (JMS) interface to run BPEL-based non-interruptible processes.

Use the following steps to start the process:

1. Create a message, for example, an ObjectMessage message. See

Example 1-21.

Example 1-21 Creating a message

ObjectMessage message = queueSession.createObjectMessage();

2. This step is optional if you do not want to receive a reply.

Set the JMSReplyToQueue. See Example 1-22.

Example 1-22 Setting JMSReplyToQueue

//Specify the destination object replies are to be sent to message.SetJMSReplyTo(replyToQueue);

3. This step is optional.

Specify the JMS properties. If you do not specify any properties, the process template name Dispatch is assumed. You must set the JMSReplyToQueue

value. See Example 1-23.

Example 1-23 JMS properties message.SetStringProperty("wf$verb", "call"); message.SetStringProperty("wf$processTemplateName", "CustomerTemplate");

4. Start the process with an input message of the appropriate type.

Chapter 1. Business Process Engine programming 35

Specify the input message as the payload of the message. When you have an array containing basic types, it is recommended that you use the

Enterprise JavaBean(EJB) interface to specify the message. This technique guarantees that the message definition is contained in the input message and that Business Process Choreographer can analyze the message. See

Example 1-24.

Example 1-24 Starting the process

//Create Customer input message

WSIFDefaultMessage input = new WSIFDefaultMessage(); input.setObjecPart("CustomerName", "Smith"); message.setObject(new ClientObjectWrapper(input));

//Send message queueSender.send(message);

This action creates an instance of the process template, CustomerTemplate, and passes some client data. The operation returns only when the flow is complete and when a JMSReplyToQueue is specified. The result of the process, OrderNo, is returned as the payload of the reply message. Because an ObjectMessage message was passed, an object message is returned.

5. This step is optional.

Get the result of the process. You can get the results of the process only if

you specified a queue in step 2 on page 35. In our example, the result of the

process, OrderNo, is returned as shown in Example 1-25.

Example 1-25 Getting the result of the process

Message m = queueReceiver.receive(); if (m instanceof ObjectMessage)

{

ClientObjectWrapper wrapper = (ClientObjectWrapper)m.getObject();

WSIFMessage output = (WSIFMessage)wrapper.getObject();

int order = output.getIntPart("OrderNo");

}

Interruptible process

You can use the Enterprise JavaBeans (EJB) interface to develop the following services for interruptible processes based on the Business Process

Execution Language (BPEL):

– Start an interruptible process that contains a unique starting service

– Start an interruptible process that contains a non-unique starting service

36 Using the WebSphere Business Integration Server Foundation Programming APIs

Starting an interruptible process that contains a unique starting service

If the starting service is unique, you can use the initiate method and pass the process template name as a parameter. This is the case when the long-running process starts with either a single receive or pick activity and when the single pick activity has only one onMessage definition.

Use the following steps to start the process:

1. This step is optional if you already know the name of the process.

List the process templates to find the name of the interruptible process you

want to start. See Example 1-26.

Example 1-26 Listing the process templates

ProcessTemplateData[] processTemplates = process.queryProcessTemplates

("PROCESS_TEMPLATE.CAN_RUN_INTERRUP=TRUE"

"PROCESS_TEMPLATE.NAME",

newInteger(50), null);

The results are sorted by name. The query returns an array containing the first 50 sorted templates that the initiate method can start.

2. Start the process with an input message of the appropriate type.

When you create the message, you must specify its message type name so that the message definition is contained. If you specify a process-instance name, it cannot start with an underscore. If a process-instance name is not specified, the process instance ID (PIID) in String format is used as the name.

See Example 1-27.

Example 1-27 Starting the process

ProcessTemplateData template = processTemplates[0];

//create a message for the single starting receive activity

ClientObjectWrapper input = process.createMessage

(template.getID(),

template.getInputMessageTypeName());

WSIFMessage myMessage = (WSIFMessage)input.getObject();

//set the message parts, for example, the customer name myMessage.setObjectPart("CustomerName", "Smith");

//start the process

PIID piid = process.initiate(template.getName(), "CustomerOrder", input);

This action creates an instance, CustomerOrder, and passes some client data. When the process starts, the operation returns the object ID of the new process instance to the caller.

Chapter 1. Business Process Engine programming 37

The starter of the process instance is set to the caller of the request and receives a work item for the process instance. The process administrators, readers, and editors of the process instance are determined and receive work items for the process instance. The follow-on activity instances are determined. These are started automatically or, if they are staff, receive, or pick activities, work items are created for the potential owners.

Starting a process that contains a non-unique starting service

If the starting service is not unique, for example, the process starts with multiple receive activities or a pick activity that has multiple onMessage definitions, then you must identify the service to be called.

Starting the process:

1. This step is optional if you already know the name of the process.

List the process templates to find the name of the interruptible process you

want to start. See Example 1-28.

Example 1-28 Listing the process templates

ProcessTemplateData[] processTemplates = process.queryProcessTemplates

("PROCESS_TEMPLATE.EXECUTION_MODE.EXCECUTION_MODE_LONG_RUNNING"

"PROCESS_TEMPLATE.NAME",

newInteger(50),

null);

The results are sorted by name. The query returns an array containing the first 50 sorted templates that can be started as interruptible processes.

2. Determine the starting service to be called. See Example 1-29.

Example 1-29 Starting service to e called

ProcessTemplateData template = processTemplates[0];

ActivityServiceTemplateData startActivities =

process.getStartActivities(template.getID());

3. Start the process with an input message of the appropriate type.

When you create the message, you must specify its message type name so that the message definition is contained. If you specify a process-instance name, it must not start with an underscore. If a process-instance name is not specified, the process instance ID (PIID) in String format is used as the name.

See Example 1-30.

Example 1-30 Starting the process

ActivityServiceTemplateData activity = startActivities[0];

38 Using the WebSphere Business Integration Server Foundation Programming APIs

//create a message for the service to be called

ClientObjectWrapper input = process.createMessage

(activity.getServiceTemplateID(),

activity.getActivityTemplateID(),

activity.getInputMessageTypeName());

WSIFMessage myMessage = (WSIFMessage)input.getObject();

//set the message parts, for example, the customer name myMessage.setObjectPart("CustomerName", "Smith");

//start the process

PIID piid = process.initiate(activity.getServiceTemplateID(),

activity.getActivityTemplateID(),

"CustomerOrder",

input);

This action creates an instance, CustomerOrder, and passes some client data. When the process starts, the operation returns the object ID of the new process instance to the caller.

The starter of the process instance is set to the caller of the request and receives a work item for the process instance. The process administrators, readers, and editors of the process instance are determined and receive work items for the process instance. The follow-on activity instances are determined. These are started automatically or, if they are staff, receive, or pick activities, work items are created for the potential owners.

1.2.4 Claiming work items

To work with a work item, you must claim the work item and then perform the actions needed to complete it. You can claim a work item that is in the ready state if you are a potential owner or the administrator of that work item. If you claim a work item, you become the owner of that work item and are responsible for completing it.

Claiming:

1. List the activities belonging to a logged-on person that are ready to be worked

on as shown in Example 1-31.

Example 1-31 Listing activities

QueryResultSet result =

process.query("ACTIVITY.AIID",

"ACTIVITY.STATE = ACTIVITY.STATE.STATE_READY AND

ACTIVITY.KIND = ACTIVITY.KIND.KIND_STAFF AND

WORK_ITEM.REASON =

WORK_ITEM.REASON.REASON_POTENTIAL_OWNER",

Chapter 1. Business Process Engine programming 39

null, null, null);

This action returns a query result set that contains the activities that the logged-on person can work on.

2. Claim the activity to be worked on, as shown in Example 1-32.

Example 1-32 Claiming an activity if (result.size() > 0)

{ result.first();

AIID aiid = (AIID) result.getOID(1);

// read the values from WSIFMessage

...

}

ClientObjectWrapper input = process.claim(aiid);

WSIFMessage activityInput = (WSIFMessage)input.getObject();

When the activity is claimed, the input message of the activity is returned.

1.2.5 Canceling work items

Sometimes it is necessary for someone with process administrator rights to cancel an activity that someone else claims. This situation might occur, for example, when an activity must be completed but the owner of the activity is absent.

The cancelClaim() method returns the Staff activity from the claimed state to the ready state.

1. List the claimed activities owned by a specific person to find the ID of the

activity in question. See Example 1-33.

Example 1-33 Listing claimed activities

QueryResultSet result = process.query("DISTINCT ACTIVITY.AIID",

"ACTIVITY.STATE = ACTIVITY.STATE.STATE_CLAIMED AND ACTIVITY.OWNER = ’Smith’

AND ACTIVITY.TEMPLATE_NAME = ’CustomerTemplate’", null, null, null);

This action returns a query result set that lists the activities claimed by the specified person, Smith.

2. Cancel the claimed activity. See Example 1-34.

Example 1-34 Cancel a claimed activity if (result.size() > 0)

{ result.first();

40 Using the WebSphere Business Integration Server Foundation Programming APIs

AIID aiid = (AIID) result.getOID(1); process.cancelClaim(aiid);

}

This action returns the activity to the ready state so that one of the other potential owners can claim it.

1.2.6 Completing work items

After you claim a work item, you can perform the actions needed to complete it.

The activity is completed either successfully or with a fault message. If the activity is successful, an output message is passed. If the activity is unsuccessful, the activity is put into the failed or stopped state and a fault message is passed. You must create the appropriate messages to do this. When you create the message, you must specify the message type name so that the message definition is contained.

1. To complete the activity successfully, create an output message as shown in

Example 1-35.

Example 1-35 Creating an output message and completing the activity

ActivityInstanceData activity = process.getActivityInstance(aiid);

ClientObjectWrapper output =

process.createMessage(aiid, activity.getOutputMessageTypeName());

WSIFMessage myMessage = (WSIFMessage)output.getObject();

//set the parts in your message, for example, an order number myMessage.setIntPart("OrderNo", 4711);

//complete the activity process.complete(aiid, output);

This action sets an output message that contains the order number.

2. To complete the activity when a fault occurs, create a fault message as

shown in Example 1-36.

Example 1-36 Completing the activity when a fault occurs

//retrieve the faults modeled for the staff activity

List faultNames = process.getFaultNames(aiid);

//create a message of the appropriate type

ClientObjectWrapper myFault =

process.createMessage(aiid, faultNames.get(0));

// set the parts in your fault message, for example, an error number

WSIFMessage myMessage = (WSIFMessage)myFault.getObject();

Chapter 1. Business Process Engine programming 41

myMessage.setIntPart("error",1304); process.complete(aiid,myFault,faultNames.get(0));

This action sets the activity in either the failed or the stopped state. If the continue-on-error parameter for the activity in the process model is set to true, the activity is put into the failed state and the navigation continues. If the continue-on-error parameter is set to false, the activity is put into the stopped state. In this state you can repair the activity using force terminate or force retry.

1.3 Authorization and security using the API

When a business process is modeled, the developer can indicate what kind of person can perform tasks such as starting a process, sending an event, or claiming an activity by assigning different individuals to different roles or by specifying permissions to the process or Staff activity. This is done in an abstract manner by formulating various queries. At runtime, Business Process

Choreographer uses the work item manager and staff plug-ins to resolve staff queries from a user registry and to authorize activity. If you specify a staff query for any of the roles for a process or staff activity, enable WebSphere Application

Server security. This is because the user needs to be authenticated to determine the appropriate work items.

When requests come in for starting a business process, sending an event message, or working with work items, the application server authenticates the request and a security token is created for the request. The security identity stored in the token is then available to the Business Process Container to control and authorize who starts a business process, or sends an event. It is also used for work items, so the items displayed are only those for which the individual was assigned a role. The user ID that is part of the security information is compared to the work item stored in the business process database and those administrative roles are also evaluated in respect to the user ID. All of the work items that the Business Process Container determined as matching the current user ID are then available to the current user. Different permissions on these work items dictate the actions the user may perform on these work items. The

Business Process Container only performs a type of authorization and leaves the authentication to the application server.

1.3.1 Process authorization authorities

The following reasons for a work-item assignment are used:

򐂰 For processes: reader, starter, administrator

42 Using the WebSphere Business Integration Server Foundation Programming APIs

򐂰 For activities: reader, editor, potential owner, owner

If a potential owner of a starting activity starts a process, this person becomes the starter of the process. If a potential owner claims a work item, the potential owner becomes the owner of the work item.

Chapter 1. Business Process Engine programming 43

These assignment reasons are mapped to authorization authorities. Table 1-22

contains the authorization authorities.

Table 1-22 Authorization authorities

Authorization authority Description

Activity reader authority Can see properties of the associated activity instance, and its input and output messages

Activity editor authority 򐂰 Has the authority of the activity reader

򐂰 Has write access to messages and other data associated with the activity

Potential activity owner authority 򐂰 Has the authority of the activity editor

򐂰 Has the right to claim the activity or to send a message to the activity

Activity owner authority

Process starter authority

򐂰 Has the authority of the potential activity owner

򐂰 has the right to complete the activity

򐂰 has the authority to transfer owned work items to an administrator or potential owner

Can see properties of the associated process instance, its input and output messages, and write other data associated with the process

Process reader authority

Process administrator authority

Can see properties of the associated process instance, its input and output messages, and everything that the activity reader supports for all contained activities but not those of the independent subprocesses

򐂰 Has the authority of the process reader and the process starter

򐂰 Has the right to intervene in a process that has started

򐂰 Has the authority to create, delete, and transfer work items

Special authority is granted to a person with the role of business process administrator. This role is different from the process administrator of a process instance. A business process administrator has all privileges. This is the role that is defined in the Business Process Container application deployment descriptor as BPE SystemAdministrator. The security role mapping for this role occurs during the configuration of the Business Process Container. A process administrator is the one defined for a process template when modeling the process.

44 Using the WebSphere Business Integration Server Foundation Programming APIs

1.3.2 Authorization for the EJB API

When an instance of the LocalBusinessProcess or the BusinessProcess session bean is created, WebSphere Application Server associates a session context with the instance. The session context contains the caller's principal. Both the

Business Process Container and the Business Process Engine use this

information to check the caller's authorization for each call. Table 1-23 shows the

authorizations associated with process requests.

Table 1-23 Minimum authorization authorities are needed for process requests:

Request Required Authorization createMessage process reader createWorkItem getAllActivities getAllWorkItems getClientUISettings process administrator process reader process reader process reader getCustomProperty getFaultMessage getInputClientUISettings getInputMessage getOutputClientUISettings getOutputMessage getProcessInstance getVariable process reader process reader process reader process reader process reader process reader process reader process reader getWorkItems setCustomProperty setVariable delete deleteWorkItem transferWorkItem forceTerminate process reader process starter process administrator process administrator process administrator process administrator process administrator

Chapter 1. Business Process Engine programming 45

Request forceTerminateAndCompensate

Required Authorization process administrator

Table 1-24 shows the authorizations associated with activity requests.

Table 1-24 Minimum authorization authorities are needed for activity requests:

Request Required Authorization createMessage createWorkItem activity reader or process reader process administrator getActivityInstance getCustomerProperty getFaultMessage getFaultNames activity reader or process reader activity reader or process reader activity reader or process reader activity reader or process reader getInputMessage getOutputMessage getClientUISettings getWorkItems getAllWorkItems setCustomProperty setOutputMessage setFaultMessage activity reader or process reader activity reader or process reader activity reader or process reader activity reader or process administrator process reader activity editor or process administrator activity editor or process administrator activity editor or process administrator call initiate claim cancelClaim complete forceRetry forceComplete deleteWorkItem transferWorkItem potential activity owner or process administrator potential activity owner or process administrator potential activity owner or process administrator activity owner or process administrator activity owner or process administrator process administrator process administrator process administrator activity owner or process administrator

46 Using the WebSphere Business Integration Server Foundation Programming APIs

Request sendMessage

Required Authorization potential activity owner or process administrator

1.3.3 Authorization for the JMS API

When a Business Process Container is installed, a JMS API user ID needs to be specified. This is the ID that the Business Process Container uses when processing JMS API calls. So when using the JMS API, this user ID must either be given the appropriate authorities when the process is modeled, or more commonly, it must be a member of a group that has the necessary authorizations.

If you want to support all actions on processes through the JMS API, you can specify a user ID that is a member of the business process administrator role.

However, in a production system, the more fine-grained security approach is recommended.

1.3.4 Authentication

The Business Process Container only performs a type of authorization and leaves the authentication to the application server. When an application using the BPE API is authenticated to the WebSphere Application Server, the security context propagates to the Business Process Container for authorization. Use standard J2EE authentication mechanisms for authentication, such as configuring form-based login for a Web application or using the Java

Authentication and Authorization Service (JAAS) to perform programmatic login.

Please refer to the relative WebSphere InfoCenter section for more information.

One example is the BPE Web Client, which is configured to use form-based login.

1.4 Exception and fault handling using the API

Faults can occur when a process instance is created or when operations that are invoked as part of the navigation of a process instance fail. Mechanisms exist to handle these faults and they include:

򐂰 Passing control to the corresponding fault handlers

򐂰 Stopping the process and letting someone repair the situation (force-retry, force-complete)

򐂰 Compensating the process

򐂰 Passing the fault to the client application as an API exception

Chapter 1. Business Process Engine programming 47

The next two sections discuss handling the BPE API exception and using the API to handle faults.

1.4.1 Handling API exceptions

The API provides exceptions that we can handle.

Exceptions and Enterprise JavaBeans interface

For the Enterprise JavaBean (EJB) interface, if a method in the interface does not complete successfully, an exception is thrown that denotes the cause of the error. You can handle this exception specifically to provide guidance to the caller.

However, it is common practice to handle only a subset of the exceptions specifically and to provide general guidance for the other potential exceptions. All specific exceptions inherit from a generic ProcessException

(com.ibm.bpe.api.ProcessException). It is a best practice to catch generic exceptions with a final catch(ProcessException) statement. This statement helps to ensure the upward compatibility of your application program because it takes account of all other exceptions that can occur.

Example 1-37 shows caching the EngineNotAuthorizedException when calling

the EJB API to claim a work item.

Example 1-37 Exception handling try {

... find the work item to claim

ClientObjectWrapper input = process.claim(aiid);

WSIFMessage activityInput = (WSIFMessage)input.getObject();

// read the values from WSIFMessage

...

} catch (EngineNotAuthorizedException enae) {

// notify client needs proper authorization to perform this task

} catch (ProcessException pe) {

// notify client a generic exception occurs.

}

A ProcessException can contain nested exceptions. Applications can use the

ProcessException.getRootCause() method to get the root cause of the exception, or use ProcessException.getCause() to get the nested exception.

48 Using the WebSphere Business Integration Server Foundation Programming APIs

JMS interface

From the application development point of view, using the JMS interface is standard JMS API programming. To get business process exceptions, set the

JMSReplyTo queue when sending the JMS request. You can check the reply message payload or the wf$exceptionText property for BPE exceptions.

If an ObjectMessage message is returned, it contains an object of the type

ClientObjectWrapper. This object contains the output message, the message of the fault terminal, or an exception. If the reply message contains an exception as the result of a port type or operation call, the exception is:

– A ProcessException if the operation cannot be invoked

– A FaultReplyException if the operation sends an application-defined fault

– An EngineMissingReceiveException if there is no activity waiting for the request and the process ends before an outstanding receive or pick activity processes this request

– An EngineMissingReplyException if the operation corresponds to a receive or pick activity that implements a two-way operation and the process ends without sending a reply

Example 1-38 shows how to handle exceptions returned by the JMS API.

Example 1-38 Handling exceptions using the JMS API

Queue replyToQueue = (Queue) initialContext.lookup(“MyReplyQueue”);

QueueReceiver queueReceiver = queueSession.createReceiver(replyToQueue);

Message m = queueReceiver.receive(); if (m instanceof ObjectMessage) {

ClientObjectWrapper wrapper = (ClientObjectWrapper)m.getObject();

Exception exception = (Exception)wrapper.getObject();

// check the type of the exception

}

If an exception occurs during the processing of a request or if an exception occurs during the execution of a process instance and the fault is not connected to a fault terminal of the process, the reply message does not contain a payload.

The wf$processInstanceName, the wf$processState, and the wf$exceptionText properties are set. The wf$exceptionText property contains the message text of the exception that ended the process. Nested exceptions follow the message

text. These exceptions are separated by new-line characters. Example 1-39 on page 50 shows how to retrieve the exception details from the JMS properties.

Chapter 1. Business Process Engine programming 49

Example 1-39 Exceptions properties

Queue replyToQueue = (Queue) initialContext.lookup(“MyReplyQueue”);

QueueReceiver queueReceiver = queueSession.createReceiver(replyToQueue);

Message reply = queueReceiver.receive();

String exceptionText = reply.getStringProperty(“wf$exceptionText”);

1.4.2 Handling faults using the BPE API

When a fault occurs, the client application can use the BPE API to perform the following tasks to get details of the fault or to repair the process or activity:

򐂰 Find failed or stopped process or activity using a query

򐂰 Get fault message of a process or activity, get fault names for an activity

򐂰 Force complete an activity

򐂰 Force retry for an activity

򐂰 Force terminate a process

Faults Enterprise JavaBean API

Some examples of using the EJB version of the BPE API to process faults are:

1. List stopped activity instances:

QueryResultSet result =

process.query("ACTIVITY.AIID",

"ACTIVITY.STATE = ACTIVITY.STATE.STATE_STOPPED",

null, null, null);

2. Get unhandled exceptions for the activity:

ActivityInstanceData adata = process.getActivityInstance(aiid);

ProcessException pe = adata.getUnhandledException();

// getting root cause of the unhandled exception pe.getRootCause();

// get cause of the unhandled exception pe.getCause();

3. Get fault names and fault messages of the activity:

// get fault message

ClientObjectWrapper wrapper = process.getFaultMessage(aiid);

WSIFMessage faultMessage = (WSIFMessage)wrapper.getObject();

// get fault names java.util.List aFaultNameList = process.getFaultNames(aiid);

// iterate through the list to get each fault names

50 Using the WebSphere Business Integration Server Foundation Programming APIs

4. Force retry an activity. The activity instance must be in the stopped execution state and the associated process instance must be in the running execution state. process.forceRetry(aiid, false);

Optionally, you can set an input message when force retrying an activity:

ActivityInstanceData adata = process.getActivityInstance(aiid);

ClientObjectWrapper aInputMessage = process.createMessage(aiid, adata.getInputMessageTypeName());

WSIFMessage myMessage = (WSIFMessage)aInputMessage.getObject();

// set parts to the message

...

process.forceRetry(aiid, aInputMessage, false);

The above statement is equivalent to following two statements: process.setVariable(processInstanceID, activityInputVariableName, aInputMessage); process.forceRetry(aiid, false);

The last boolean parameter of the forceRetry method is the continueOnError flag that indicates what happens in case of an error, that is, when a system exception or an unhandled fault occurs.

– True states that navigation should continue, that is, the activity instance is set into execution state failed and the error is propagated to the associated process instance.

– False states that the activity instance should stay in execution state stopped.

5. Force complete an activity. The activity instance must be in the stopped execution state, and the associated process instance must be in the running execution state. The caller must be an administrator of the associated process instance. Forcing the completion of an activity instance states that navigation of the process instance can continue. Before force completing an activity, user can optionally set output message or fault message to the activity.

ActivityInstanceData adata = process.getActivityInstance(aiid);

ClientObjectWrapper aOutputMessage = process.createMessage(aiid, adata.getOutputMessageTypeName());

WSIFMessage myMessage = (WSIFMessage)aOutputMessage.getObject();

// set parts to the message

...

process.forceComplete(aiid, aInputMessage, false)

The previous statement is equivalent to the following two statements: process.setVariable(processInstanceID, activityOutputVariableName, aOutputMessage);

Chapter 1. Business Process Engine programming 51

process.forceComplete(aiid, false);

Or process.setOutputMessage(aiid, aOutputMessage); process.forceComplete(aiid, false);

The last boolean parameter of the forceComplete method is also the continueOnError flag same as forceRetry.

6. Force terminate a process: process.forceTerminate(piid, compensateFlag);

Handling faults using the JMS API

There is limited functionality when using JMS API to handle faults. forceTerminate is the only functional available using JMS API.

1.5 API reference

This section gives a detailed description of each API method. The methods covered in this section have different arguments that are passed in the moment that it is called. We included these reference details for your convenience.

Please be aware that the authoritative reference source for the API remains the

WebSphere Business Integration Server Foundation product documentation.

Note: Most methods, in order to be executed, require as a parameter either a string or an object ID to identify the process template, activity instance, activity service template, and so on.

1.5.1 Process templates

This group provides a description of using process templates methods.

򐂰 getProcessTemplate

Description: Retrieves the specified process template. When a process template name is provided and there exists more than one template with this name, then the currently valid template is returned. The caller must be authorized for the process template.

Parameters:

– identifier - The string representation of the process template object ID or the process template name. This is used to identify the process template to be retrieved.

52 Using the WebSphere Business Integration Server Foundation Programming APIs

– piid - The object ID of the process instance to be retrieved.

Signature: getProcessTemplate(String identifier) getProcessInstance(PIID piid)

Returns: ProcessTemplateData

The process template. If the specified process template is not found, null is returned

򐂰 queryProcessTemplates

Description: Retrieves process templates persistently stored in the database. You can specify a threshold or a filter to reduce the number of process templates returned. Process templates are sorted on the server according to the specified sort criteria.

Parameters:

– whereClause - The search condition to be applied to the set of available templates. Its syntax is a SQL where-clause. The following rules apply:

• Specify object ID constants as ID('string-rep-of-ptid').

• Specify time stamp constants as TS('yyyy-mm-ddThh:mm:ss') or as

• Specify binary constants as BIN('UTF-8 string').

• Use constants instead of integer enumerations. For example, instead of specifying a process template state expression

"PROCESS_TEMPLATE.STATE=2" specify

"PROCESS_TEMPLATE.STATE=PROCESS_TEMPLATE.STATE.ST

ATE_STOPPED".

If a filter is not to be applied, specify null.

– orderByClause - Sorts the qualifying process templates by the values of the columns specified. Its syntax is a SQL order-by-clause. Each comma separated part of the order-by-clause must specify a property from the

PROCESS_TEMPLATE view. If you specify more than one column, the process templates are ordered by the values of the first column specified, then by the values of the second column, and so on. If the process templates are not to be sorted, specify null.

– threshold - Specifies the maximum number of process templates to be returned. If a threshold is not to be applied, specify null.

– time zone - The time zone of the time stamp constants in the whereClause. If a time zone is not specified, UTC is assumed.

Signature: queryProcessTemplates( java.lang.String whereClause,

Chapter 1. Business Process Engine programming 53

java.lang.String orderByClause, java.lang.Integer threshold, java.util.TimeZone timeZone)

Returns: ProcessTemplateData[]

An array of qualifying process templates. If no templates qualify, an empty array is returned.

1.5.2 Starting and terminating processes

This group provides a description of starting and terminating processes.

򐂰 call

Description: This method creates and executes a process instance that is derived from the specified process template. An input message is passed to specify initial values for the process instance.

This method returns only when the execution of the process instance finishes with the result of execution. If a fault occurs, an exception is thrown.

The process template must specify that derived process instances can run synchronously, that is, as a microflow and must return a reply.

Use this method if you have a BPEL process that contains a unique or non-unique starting service. For that, there are different parameters in its signature.

A process instance is only created when the currently valid version of the specified process template is started and when it belongs to a started application.

Parameters:

– processTemplateName - The name of the process template for which an instance is to be created and executed.

– inputMessage - The input message that specifies the initial values of the process instance. If input is not to be provided, specify null. Serialize the object that the ClientObjectWrapper wraps.

– vtid - The string representation of the activity service template object ID or the object ID of the activity service template. This is used to identify the starting service to be called.

– atid - A string representation of the activity template ID or the object ID of the activity template. This is used to identify the activity to which the service belongs.

Signature:

– Unique starting service

54 Using the WebSphere Business Integration Server Foundation Programming APIs

call(String processTemplateName, ClientObjectWrapper inputMessage)

– Non-unique starting service call(String vtid, String atid, ClientObjectWrapper inputMessage) call(VTID vtid, ATID atid, ClientObjectWrapper inputMessage)

Returns: ClientObjectWrapper

The output message that denotes the result of execution

򐂰 callWithReplyContext

Description: Creates and executes a process instance from the specified process template and asynchronously waits for the result. An input message can be passed to specify initial values for the process instance.

A process instance is only created when the currently valid version of the specified process template is started and when it belongs to a started application.

Parameters:

– processTemplateName - The name of the process template for which an instance is to be created and executed.

– inputMessage - The input message that specifies the initial values of the process instance. If input is not to be provided, null must be specified. The object wrapped by the ClientObjectWrapper must be serializable.

– processInstanceName - The name of the process instance to be created; must not be greater than 220 bytes in UTF-8 format. The name must be unique.

– replyContext - The reply context to use to send the result back to the caller.

– invocationCount - The invocation count that specifies the number of invocation attempts. The first attempt should be 1, the second 2, and so on. The caller must maintain this count and increment after each unsuccessful invocation attempt, that is, when the request ended with an exception. If the caller is an MDB that works on behalf of a received JMS message, the JMSXDeliveryCount property of the message can be used to count the invocation attempts. A value of 0 indicates that the invocation count is not known to the caller.

– requestId - An ID to identify the request uniquely. If the caller is an MDB that works on behalf of a received JMS message, the JMSMessageId can be used as the requestId. A value of null implies that a unique requestId is not known to the caller.

Chapter 1. Business Process Engine programming 55

Signature:

– Creates and executes a process instance from the specified process template and asynchronously waits for the result.

callWithReplyContext(java.lang.String processTemplateName,

ClientObjectWrapper inputMessage, ReplyContextWrapper replyContext)

– Creates and executes a process instance from the specified process template and asynchronously waits for the result of the uniquely identified request.

callWithReplyContext(java.lang.String processTemplateName,

ClientObjectWrapper inputMessage, ReplyContextWrapper replyContext, int invocationCount, java.lang.String requestId)

– Creates and executes a named process instance from the specified process template and asynchronously waits for the result.

callWithReplyContext(java.lang.String processTemplateName, java.lang.String processInstanceName, ClientObjectWrapper inputMessage,

ReplyContextWrapper replyContext)

– Creates and executes a named process instance from the specified process template and asynchronously waits for the result of the uniquely identified request.

callWithReplyContext(java.lang.String processTemplateName, java.lang.String processInstanceName, ClientObjectWrapper inputMessage,

ReplyContextWrapper replyContext, int invocationCount, java.lang.String requestId)

Returns: void

򐂰 callWithUISettings

Description: Creates and executes a process instance that is derived from the specified BPEL process template and returns the output message as well as its client UI settings. An input message can be passed to specify initial values for the process instance. This method returns only when the execution of the process instance finishes with the result of execution. If a fault occurs, an exception is thrown.

The process template must specify that derived process instances can run as a microflow and must return a reply.

This method can be used either if you have a BPEL process that contains either unique or a non-unique starting service. This method has different parameters in its signature depending upon whether the process starting service is unique or non-unique.

56 Using the WebSphere Business Integration Server Foundation Programming APIs

Parameters:

– processTemplateName - The name of the process template for which an instance is to be created and executed.

– inputMessage - The input message that specifies the initial values of the process instance. If input is not to be provided, null must be specified. The object wrapped by the ClientObjectWrapper must be serializable.

– vtid - The string representation of the activity service template object ID or the object ID of the activity service template. This is used to identify the starting service to be called.

– atid - A string representation of the activity template ID or the object ID of the activity template. This identifies the activity to which the service belongs.

Signature:

– Unique starting service callWithUISettings(String processTemplateName, ClientObjectWrapper inputMessage)

– Non-unique starting service callWithUISettings(String vtid, String atid, ClientObjectWrapper inputMessage) callWithUISettings(VTID vtid, ATID atid, ClientObjectWrapper inputMessage)

Returns: ProcessResponseWrapper

The output message that denotes the result of execution and its client UI settings

򐂰 initiate

Description: This method creates a process instance or a named process instance from the specified process template, passes the specified input message, and initiates processing of the process instance.

The BPEL process can be either a long or a short running process with a unique or non-unique starting service. This method has different parameters in its signature depending on whether the process starting service is unique or non-unique.

Parameters:

– processTemplateName - The name of the process template from which an instance is to be created.

Chapter 1. Business Process Engine programming 57

– inputMessage - The input message that specifies the initial values of the process instance. If input is not to be provided, null must be specified. The object wrapped by the ClientObjectWrapper must be serializable.

– processInstanceName - The name of the process instance to be created.

It must not be greater than 220 bytes in UTF-8 format. The name must be unique. This parameter is ignored for microflows.

– vtid - The string representation of the activity service template object ID or the object ID of the activity service template. This is used to identify the starting service.

– atid - A string representation of the activity template ID or the object ID of the activity template. This is used to identify the activity to which the service belongs.

Signature:

– Creates a process instance from the specified process template, passes the specified input message, and initiates processing of the process instance. You can use the long or short business process: initiate(String processTemplateName, ClientObjectWrapper inputMessage)

– Creates a named process instance from the specified process template with a unique starting service, passes the specified input message, and initiates processing of the process instance. You can use the long or short business process: initiate(String processTemplateName, String processInstanceName,

ClientObjectWrapper inputMessage)

– Creates a named process instance identifying the starting service, passes the specified input message, and initiates processing of the process instance. The process must be a long running process: initiate(String vtid, String atid, String processInstanceName,

ClientObjectWrapper inputMessage) initiate(VTID vtid, ATID atid, java.lang.String processInstanceName,

ClientObjectWrapper inputMessage)

Returns: PIID

The ID of the process instance created

򐂰 delete

Description: Deletes the specified top-level process instance and its subprocesses. The process instance must be in the finished, terminated,

58 Using the WebSphere Business Integration Server Foundation Programming APIs

compensated, or failed execution state. The caller must be an administrator of the process instance.

Parameters:

– piid - A string representation of the process instance object ID or the object ID of the process instance that identifies the process instance to be deleted.

Signature: delete(String piid) delete(PIID piid)

Returns: void

򐂰 forceTerminate

Description: Terminates the specified top-level process instance, its subprocesses, and its running, claimed, or waiting activities.

Use the process termination capabilities as a last resort only. The process instance is immediately terminated without waiting for outstanding activities to complete.

Process instances that are terminated are not compensated.

There is a parameter in its signature that, depending on the invokeCompensation flag, the process instance is compensated or not. If compensation is to be ignored, the process instance is immediately terminated. If compensation is to be invoked, the process instance is compensated before it is terminated provided that compensation is defined at all. Otherwise, the process instance is terminated without compensation.

The process instance must be in the running or failing execution state. Only an administrator of the process instance can terminate the process instance.

The process instance is put into the terminated execution state.

If the "auto delete" option is not set or set to 'true', the process instance is automatically deleted.

Parameters:

– identifier - The string representation of the process instance object ID or the name of the process instance. This identifies the process instance to be terminated.

– invokeCompensation - Indicates whether compensation is to be executed or not. If compensation is to be ignored, compensation is not invoked even if defined. If compensation is to be invoked, compensation is executed if defined.

– piid - The object ID of the process instance to be terminated.

Chapter 1. Business Process Engine programming 59

Signature:

– Terminates the specified top-level process instance, its subprocesses, and its running, claimed, or waiting activities without invoking compensation: forceTerminate(String identifier) forceTerminate(PIID piid)

– Terminates the specified top-level process instance, its subprocesses, and its running, claimed, or waiting activities invoking compensation before terminating: forceTerminate(String identifier, int invokeCompensation) forceTerminate(PIID piid, int invokeCompensation)

Returns: void

򐂰 sendMessage

Description: Sends the specified message to the specified activity service and process instance (if the process instance is already created).

The caller must be a potential owner of the associated activity or a process administrator.

Parameters:

– vtid - The string representation of the activity service template object ID or the object ID of the activity service template. This identifies the starting service.

– atid - A string representation of the activity template ID or the object ID of the activity template. This identifies the activity to which the service belongs.

– message - The message. The object wrapped by the ClientObjectWrapper must be serializable.

– piid - A string representation of the process instance object ID or the object ID of the process instance.

Signature:

– Sends the specified message to the specified activity service and process instance (when the process instance is already created): sendMessage(PIID piid, VTID vtid, ATID atid, ClientObjectWrapper message) sendMessage(String piid, String vtid, String atid, ClientObjectWrapper message)

Returns: void

60 Using the WebSphere Business Integration Server Foundation Programming APIs

– Sends the specified message to the specified activity service (when the process instance is not created): sendMessage(VTID vtid, ATID atid, ClientObjectWrapper message) sendMessage(String vtid, String atid, ClientObjectWrapper message)

Returns: PIID

򐂰 getStartActivities (for processes with non-unique starting service)

Description: Returns information about activities that can start a BPEL process instance.The caller must be authorized for the process template.

Parameters:

– ptid - The string representation of the process template object ID or the object ID of the process template. This identifies the process template.

Signature: getStartActivities(String ptid) getStartActivities(PTID ptid)

Returns: ActivityServiceTemplateData[]

An array of activity service templates. If no information is available for the logged-on user, an empty array is returned.

򐂰 getActivityServiceTemplate (for processes with non-unique starting service)

Description: Retrieves the specified activity service template. The caller must have at least reader authority for the associated activity or be a process administrator.

Parameters:

– vtid - The string representation of the activity service template object ID or the object ID of the activity service template. This identifies the starting service.

– atid - A string representation of the activity template ID or the object ID of the activity template. This is identifies the activity to which the service belongs.

Signature: getActivityServiceTemplate(String vtid, String atid) getActivityServiceTemplate(VTID vtid, ATID atid)

Returns: ActivityServiceTemplateData

The activity service template information. If not found, null is returned.

1.5.3 Details for process instances and activities

This group provides a description of process instances and activities.

Chapter 1. Business Process Engine programming 61

򐂰 getProcessInstance

Description: Retrieves the specified process instance. The process instance can be in any execution state. The caller must have at least reader authority for the process instance.

Parameters:

– identifier - The string representation of the process instance object ID or the process instance name. This identifies the process instance to be retrieved.

– piid - The object ID of the process instance to be retrieved.

Signature: getProcessInstance(String identifier) getProcessInstance(PIID piid)

Returns: ProcessInstanceData

The process instance. If the specified process instance is not found, null is returned.

򐂰 getActivityInstance

Description: Retrieves the specified activity instance.

The activity instance and the associated process instance can be in any execution state. The caller must have at least reader authority for the activity instance or for the associated process instance.

Parameters:

– aiid - A string representation of the activity instance object ID or the object

ID of the activity instance. This identifies the activity instance to be retrieved.

Signature: getActivityInstance(String aiid) getActivityInstance(AIID aiid)

Returns:

ActivityInstanceData

The activity instance. If the specified activity instance is not found, null is returned.

1.5.4 Variables and custom properties

This group provides a description of handling with variables and custom properties.

62 Using the WebSphere Business Integration Server Foundation Programming APIs

򐂰 getVariable

Description: Retrieves the specified variable of the specified process instance.

Variables are allowed to store business data for the process, across activity invocations. They can be retrieved in any execution state of the process instance. The caller must have at least reader authority for the process instance.

Parameters:

– piid - A string representation of the process instance object ID or the object ID of the process.

– variableName - The name of the variable to be retrieved.

Signature: getVariable(String piid, String variableName) getVariable(PIID piid, String variableName)

Returns: ClientObjectWrapper

The variable. If the specified variable is not found, an empty client object wrapper is returned.

򐂰 setVariable

Description: For a BPEL process, sets the specified variable.

Variables are allowed to store business data for the process, across activity invocations. This function supports process repair scenarios.

The process instance must be in the running, failing, or terminating execution state. The caller must be an administrator of the process instance.

Parameters:

– piid - A string representation of the process instance object ID or the object ID of the process instance. This identifies the process instance for which the specified variable is to be set.

– variableName - The name of the variable to be set.

– message - The message. The object wrapped by the ClientObjectWrapper must be serializable.

Signature: setVariable(String piid,String variableName,ClientObjectWrapper message) setVariable(PIID piid, String variableName, ClientObjectWrapper message)

Returns:void

Chapter 1. Business Process Engine programming 63

򐂰 getCustomProperty

Description: For BPEL processes, retrieves the named custom property of the specified process template, process instance, or activity instance.

Custom properties allow a user to add additional properties to processes and activities, beyond those provided and managed by the Business Process

Engine. Custom properties are an extension to the BPEL notion of properties.

While the value of BPEL properties can only be derived from messages, the value of custom properties can also be set in the process model during deployment or at runtime for process instances and activities.

A custom property can be retrieved in any execution state of the process or activity instance. The caller must have at least reader authority for the process or activity instance.

Parameters:

– aiid - The activity instance object ID whose named custom property is to be retrieved.

– piid - The process instance object ID for which the named custom property is to be retrieved.

– ptid - The process template object ID whose named custom property is to be retrieved.

– propertyName - The name of the custom property for which the value is to be read.

– identifier - A string representation of the process template, process instance, or activity instance object ID. This string identifies the object for which the custom property is to be retrieved.

Signature:

– Invoke method using the activity instance ID: getCustomProperty(AIID aiid, String propertyName)

– Invoke method using the process instance ID: getCustomProperty(PIID piid, String propertyName)

– Invoke method using the process template ID: getCustomProperty(PTID ptid, String propertyName)

– Invoke method using string representation of the process template, process instance, or activity instance object ID: getCustomProperty(String identifier, String propertyName)

Returns: String

The value of the specified custom property. Returns null when the specified property cannot be found.

64 Using the WebSphere Business Integration Server Foundation Programming APIs

򐂰 setCustomProperty

Description: For BPEL processes, stores custom-specific values for the specified process or activity instance.

Custom properties allow a user to add additional properties to processes and activities, beyond those provided and managed by the Business Process

Engine. Custom properties are an extension to the BPEL notion of properties.

While the value of BPEL properties can only be derived from messages, the value of custom properties can also be set in the process model during deployment or at runtime for process instances and activities.

A custom property has a name and a value of type string. Custom properties can be provided in any execution state of the process instance. The caller must be the starter or an administrator of the process instance.

Custom properties can be provided in any execution state of the activity instance. The caller must have editor authority for the activity instance, be the owner of the activity instance, or be the administrator of the associated process instance.

Parameters:

– identifier - A string representation of the process or activity instance object

ID that is used to identify the process or activity instance.

– piid - The object ID of the process instance that identifies the process instance.

– aiid - The object ID of the activity instance that identifies the activity instance.

– propertyName - The name of the custom property to be set. The name must not be greater than 220 bytes in UTF-8 format.

– propertyValue - The custom value to be set. The value must not be greater than 254 bytes in UTF-8 format.

Signature:

– Invoke method using the activity instance ID: setCustomProperty(AIID aiid, String propertyName, String propertyValue)

– Invoke method using the process instance ID: setCustomProperty(PIID piid, String propertyName, String propertyValue)

– Invoke method using string representation of the process or activity instance object ID: setCustomProperty(String identifier, String propertyName, String propertyValue)

Returns: void

Chapter 1. Business Process Engine programming 65

1.5.5 Message handling

This group provides a description of message handling.

򐂰 createMessage

Description: Creates a message defined by the specified process template, process instance, or activity instance using the process template ID, the process instance ID, or the activity instance ID.

Parameters:

– aiid - The object ID of the activity instance for which a message is to be created.

– piid - The object ID of the process instance for which a message is to be created.

– ptid - The object ID of the process template for which a message is to be created.

– vtid - The string representation of the activity service template object ID or the object ID of the activity service template. This identifies the service for which a message is to be created.

– atid - A string representation of the activity template ID or the object ID of the activity template. This identifies the activity to which the service belongs.

– identifier - String representation of the object ID that identifies the process template, process instance, or activity instance for which a message is to be created.

– messageTypeName - The name of the message type for which a message is to be created.

Signature:

– Creates a message defined by the specified activity instance using the activity instance ID. For example, create a message that can be used to complete a staff activity: createMessage(AIID aiid, String messageTypeName)

– Creates a message defined by the specified process instance using the process instance ID: createMessage(PIID piid, String messageTypeName)

– Creates a message defined by the specified process template using the process template ID. For example, create an initial input message to use when the specified process template is initiated:

66 Using the WebSphere Business Integration Server Foundation Programming APIs

createMessage(PTID ptid, String messageTypeName)

– Creates a message defined by the specified process template, process instance, or activity instance using a string representation of the process template ID, the process instance ID, or the activity instance ID: createMessage(String identifier, String messageTypeName)

– Creates a message defined by the specified activity service using string representations or the object IDs, or using the object IDs.

createMessage(String vtid, String atid, String messageTypeName) createMessage(VTID vtid, ATID atid, String messageTypeName)

Returns: ClientObjectWrapper

The message created. An empty client object wrapper is returned when the specified message type cannot be found.

򐂰 getFaultMessage

Description: For a BPEL process, retrieves the fault message of the specified process or activity instance.

The fault message can be retrieved in any execution state of the process instance. The activity instance must be in the claimed, expired, failed, finished, terminated, ready, or stopped execution state. The activity can be an invoke, script, or staff activity.

The caller must have at least reader authority for the process or activity instance.

Parameters:

– identifier - A string representation of the process or activity instance object

ID. This string identifies the process instance or activity instance for which the fault message is to be retrieved.

– aiid - The object ID of the activity instance for which the fault message is to be retrieved.

– piid - The object ID of the process instance for which the fault message is to be retrieved.

Signature:

– Invoke method using the activity instance ID: getFaultMessage(AIID aiid)

– Invoke method using the process instance ID: getFaultMessage(PIID piid)

Chapter 1. Business Process Engine programming 67

– Invoke method using string representation of the process or activity instance object ID: getFaultMessage(String identifier)

Returns: ClientObjectWrapper

The fault message. If there is no fault message, an empty client object wrapper is returned.

򐂰 getInputMessage

Description: Retrieves the input message of the specified process or activity instance.

The input message can be retrieved in any execution state of the process instance. For a schema 5.0 process, the input message can be retrieved in any execution state of the activity instance. For a BPEL process, the input message can be retrieved in the claimed, expired, failed, finished, terminated, ready, or stopped execution states of the activity instance. The activity can be an invoke or staff activity.

The caller must have at least reader authority for the process or activity instance.

Parameters:

– identifier - A string representation of the process or activity instance object

ID. The string identifies the process instance or activity instance for which the input message is to be retrieved.

– aiid - The object ID of the activity instance whose input message is to be retrieved.

– piid - The object ID of the process instance whose input message is to be retrieved.

Signature:

– Invoke method using the activity instance ID: getInputMessage(AIID aiid)

– Invoke method using the process instance ID: getInputMessage(PIID piid)

– Invoke method using string representation of the process or activity instance object ID: getInputMessage(String identifier)

Returns: ClientObjectWrapper

The input message.

68 Using the WebSphere Business Integration Server Foundation Programming APIs

򐂰 getOutputMessage

Description: Retrieves the output message of the specified process or activity instance.

An output message can be retrieved in any execution state of the process instance. For a schema 5.0 process, the output message can be retrieved in any execution state of the activity instance. For a BPEL process, the output message can be retrieved in the claimed, expired, failed, finished, terminated, ready, or stopped execution states of the activity instance. The activity can be an invoke or staff activity.

The caller must have at least reader authority for the process or activity instance.

Signature:

– Invoke method using the activity instance ID: getOutputMessage(AIID aiid)

– Invoke method using the process instance ID: getOutputMessage(PIID piid)

– Invoke method using string representation of the process or activity instance object ID: getOutputMessage(String identifier)

Returns: ClientObjectWrapper

The output message. If the output message has not yet been created, a empty client object wrapper is returned.

1.5.6 Work items, staff activities, and administration methods

This group deals with work items, staff activities, and administration methods

򐂰 createWorkItem

Description: Creates a work item for BPEL processes or activities. The work item is created with the specified assignment reason for the specified process or activity instance and the specified user.

Work items with assignment reasons "starter" or "owner" cannot be explicitly created. Work items with assignment reasons "administrator" can only be created on the process instance.

Work items with assignment reasons "administrator" or "reader" for the process instance are automatically propagated to all enclosed activity instances.

The process instance must be in the running, failing, or terminating execution state. When a work item for an activity instance is to be created, the activity

Chapter 1. Business Process Engine programming 69

instance must be in the claimed, waiting, ready, or stopped execution state.

The activity must be an invoke, script, or staff activity.

The caller must be an administrator of the process instance.

Parameters:

– identifier - A string representation of the process or activity instance ID that identifies the object to which the new work item belongs.

– assignmentReason - The reason why the work item is assigned.

– userID - The user to which the work item should belong. It does not check whether the user exists.

– aiid - The object ID of the activity instance to which the new work item should belong.

– piid - The object ID of the activity instance to which the new work item should belong.

Signature:

– Creates a work item for BPEL activities with the specified assignment reason for the specified activity instance and user: createWorkItem(AIID aiid, int assignmentReason, String userID)

– Creates a work item for BPEL processes with the specified assignment reason for the specified process instance and user: createWorkItem(PIID piid, int assignmentReason, String userID)

– Creates a work item for BPEL processes or activities using a string representation of either the process or activity instance ID: createWorkItem(java.lang.String identifier, int assignmentReason, String userID)

Returns: void

򐂰 deleteWorkItem

Description: Deletes the specified work item of either the BPEL process or the activity instance ID.

The following restrictions apply:

– A work item with an assignment reason "owner" or "starter" cannot be deleted.

– A work item with an assignment reason "administrator" can only be deleted as long as it is not the last work item with this assignment reason for the associated process instance.

70 Using the WebSphere Business Integration Server Foundation Programming APIs

– A "reader" or "administrator" work item that was propagated from the process instance to the activity instance can only be deleted on the process instance.

– A work item for a specific user cannot be deleted when the work item is assigned to everybody.

The process instance must be in the running, failing, or terminating execution state. When a work item for an activity instance is to be deleted, the activity instance must be in the claimed, waiting, ready, or stopped execution state.

The activity must be an invoke, script, or staff activity.

The caller must be an administrator of the process instance.

Parameters:

– identifier - A string representation of the process or activity instance ID that identifies the object to which the work item belongs.

– assignmentReason - The reason why the work item was assigned.

– userID - The user to which the work item belongs.

– aiid - The object ID of the activity instance to which the work item belongs.

– piid - The object ID of the activity instance to which the work item belongs.

Signature:

– Deletes the specified work item for the specified BPEL activity instance: deleteWorkItem(AIID aiid, int assignmentReason, java.lang.String userID)

– Deletes the specified work item for the specified BPEL process instance: deleteWorkItem(PIID piid, int assignmentReason, java.lang.String userID)

– Deletes the specified work item using a string representation of either the

BPEL process or the activity instance ID: deleteWorkItem(String identifier, int assignmentReason, String userID)

Returns: void

򐂰 transferWorkItem

Description: Transfers the specified work item of a BPEL process to the specified user of either the process or the activity instance ID.

Following restrictions apply:

– A work item with an assignment reason "starter" cannot be transferred.

– When a work item with assignment reason "owner" is transferred and the caller is not an administrator, then the user the work item is transferred to must be an administrator or must own the same work item with an assignment reason "potential owner".

Chapter 1. Business Process Engine programming 71

– Work items with assignment reason "administrator" can only be transferred on the process instance.

– Work items with assignment reason "reader" can only be transferred on the activity instance, when the work item was not propagated from the process instance, meaning, when the work item denotes an activity reader but no process reader.

When work items with assignment reasons "administrator" or "reader" for the process instance are transferred, the transfer is automatically propagated to all enclosed activity instances.

The process instance must be in the running, failing, or terminating execution state. When a work item for an activity instance is to be transferred, the activity instance must be in the claimed, waiting, ready, or stopped execution state. The activity must be an invoke, script, or staff activity.

The caller must own the work item with an assignment reason "owner" or be an administrator of the associated process instance.

Parameters:

– identifier - A string representation of the process or activity instance ID that identifies the work item to be transferred.

– assignmentReason - The reason why the work item was assigned.

– fromUserID - The user to which the work item belongs.

– toUserID - The user to which the work item is to be transferred. It does not check whether the user exists.

– aiid - The object ID of the activity instance to which the work item belongs.

– piid - The object ID of the process instance to which the work item belongs.

Signature:

– Transfers a work item for the specified BPEL activity instance to the specified user using the activity instance ID: transferWorkItem(AIID aiid, int assignmentReason, String fromUserID,

String toUserID)

– Transfers a work item for the specified BPEL process instance to the specified user using the process instance ID: transferWorkItem(PIID piid, int assignmentReason, String fromUserID,

String toUserID)

– Transfers the specified work item of a BPEL process to the specified user using a string representation of either the process or activity instance ID: transferWorkItem(String identifier, int assignmentReason, String fromUserID, String toUserID)

72 Using the WebSphere Business Integration Server Foundation Programming APIs

Returns: void

򐂰 getWorkItems

Description: Retrieves work item assignments for the logged-on user and a process or activity instance. Note that the business process administrator has special rights and can access all objects, even those of other users.

Parameters:

– identifier - A string representation of the process or activity instance object

ID. The string identifies the process instance or activity instance for which work item assignments are to be retrieved.

– aiid - The object ID of the activity instance for which work item assignments are to be retrieved.

– piid - The object ID of the process instance for which work item assignments are to be retrieved.

Signature:

– Retrieves work item assignments using the activity instance ID: getWorkItems(AIID aiid)

– Retrieves work item assignments using the process instance ID: getWorkItems(PIID piid)

– Retrieves work item assignments using a string representation of the process or activity instance ID: getWorkItems(String identifier)

Returns: WorkItemData[]

An array of work items. If no work items are found, an empty array is returned.

򐂰 getAllWorkItems

Description: Retrieves all work item assignments associated to the specified process or activity instance.

The activity or process instance can be in any execution state. The caller must have reader authority for the process instance, be the process administrator, or be the business process administrator.

Parameters:

– identifier - A string representation of the process or activity instance object

ID. The string identifies the process instance or the activity instance.

– aiid - The object ID of the activity instance.

– piid - The object ID of the process instance.

Chapter 1. Business Process Engine programming 73

Signature:

– Retrieves all work item assignments using the activity instance ID: getAllWorkItems(AIID aiid)

– Retrieves all work item assignments using the process instance ID: getAllWorkItems(PIID piid)

– Retrieves all work item assignments using a string representation of the process or activity instance ID: getAllWorkItems(java.lang.String identifier)

Returns: WorkItemData[]

An array of work items. If no work items are found, an empty array is returned.

򐂰 claim

Description: Claims a ready activity instance for user processing. You can claim an activity instance using the activity instance ID or specify where-and order-by-clauses as a parameter.

The activity instance must be a staff activity instance and be in the ready execution state. The associated process instance must be in the running execution state.

The caller must be a potential owner of the activity instance or an administrator of the associated process instance.

The execution state of the activity instance is changed to claimed.

If you are specifying where- and order-by-clauses as a parameter, the first activity that qualifies under these conditions is claimed.

Parameters:

– aiid - A string representation of the activity instance object ID or the object

ID of the activity instance that identifies the activity instance to be claimed.

– whereClause - The search condition to be applied to the query domain.

The search condition filters the set of ready staff activities that can be claimed by the logged-on user. Its syntax is a SQL where-clause. The following rules apply:

• Specify object ID constants as ID('string-rep-of-oid').

• Specify time stamp constants as TS('yyyy-mm-ddThh:mm:ss') or as

CURRENT_DATE for comparisons with the current date. The date and time parts of a TS definition are optional. Specify either the date or the time. If no date part of a TS definition is specified, the current date is taken. Optional time values that are not specified are set to zero. The time stamp is 24 hours based. For example, TS('16:04') is the same as

TS('2002-12-24T16:04:00') provided that the current date is December

74 Using the WebSphere Business Integration Server Foundation Programming APIs

24th, 2002. If a date part of a TS definition is specified, the year must consist of 4 letters. The month and day specifications are optional.

Missing month and day specifications are set to 01. For example, specifying TS('2003') is the same as specifying

TS('2003-01-01T00:00:00').

• Specify binary constants as BIN('UTF-8 string').

• Use constants instead of integer enumerations. For example, instead of specifying an activity state expression "ACTIVITY.STATE=2" , specify "ACTIVITY.STATE=ACTIVITY.STATE.STATE_READY".

If a filter is not to be applied, null must be specified.

– orderByClause - Sorts the query result set by the values of the columns you identify. The orderby-clause sorts the set of qualifying ready activities.

The first activity of the sorted result is claimed. Its syntax is a SQL order-by-clause. Each comma separated part of the order-by-clause must specify a property from the published process views—see the InfoCenter for details. If you identify more than one property, the query result set is ordered by the values of the first property you identify, then by the values of the second property, and so on. If sort criteria are not to be applied, null must be specified.

– time zone - Specifies the time zone of the time stamp constants in the whereClause. If a time zone is not specified, UTC is assumed.

Signature:

– Claims a ready activity instance using the activity instance ID or using a string representation of the activity instance ID: claim(AIID aiid) claim(java.lang.String aiid)

Returns: ClientObjectWrapper

The input message of the claimed activity instance.

– Claims a ready activity instance specifying where- and order-by-clauses: claim(String whereClause, String orderByClause, timeZone)

Returns: ActivityInstanceData

The activity instance that is claimed. If there is no ready activity instance within a BPEL process that qualifies, null is returned.

򐂰 cancelClaim

Description: Cancels the claim of an activity instance.

The activity instance must have been claimed. It is returned to the ready execution state. Any previously stored output or fault message is deleted.

Chapter 1. Business Process Engine programming 75

The associated process instance must be in the running, failing, or terminating execution state. The caller must be the owner of the activity instance or an administrator of the associated process instance.

Signature: cancelClaim(AIID aiid) cancelClaim(String aiid)

Returns: void

򐂰 complete

Description: Completes a claimed activity instance.

The activity instance must be in the claimed execution state and the associated process instance must be in the running, failing, or terminating execution state.

The caller must be the owner of the activity instance or an administrator of the associated process instance.

For schema 5.0 processes, the required user input must be set.

Completion of an activity instance means that user processing finished and that navigation of the process instance can continue. If user processing completed successfully, the activity instance is put into the finished execution state. For schema 5.0 processes, the following exceptions apply:

– If the exit condition is not met, the activity instance stays in the claimed execution state, and an exception is thrown.

– If the loop condition indicates that the loop is to be continued, the activity instance is put into the ready execution state.

If user processing did not complete successfully, or if a fault message is set, the activity instance is put into the failed or stopped execution state depending on the process instance "continue on error" flag. If set into the failed execution state and if the fault is not handled, the associated process instance is placed into the finished execution state or the failed execution state if the fault is also not handled there.

Output or fault message values can continue navigation.

Note: an output or fault message does not need to be set; navigation can continue with an empty message.

Parameters:

– aiid - A string representation of the activity instance object ID or the object

ID that identifies the activity instance to be completed.

– output - The output message that denotes the result of processing. An object wrapped by the ClientObjectWrapper must be serializable.

76 Using the WebSphere Business Integration Server Foundation Programming APIs

– faultMessage - The fault message. The object wrapped by the

ClientObjectWrapper must be serializable. Any previously set output or fault message is ignored.

– faultName - A fault to denote unsuccessful processing. Must be a fault defined for the activity. Note that the structure of a BPEL fault name is a

QName.

Signature:

– Completes a claimed activity instance using a string representation of the activity instance ID or using the activity instance ID: complete(AIID aiid) complete(String aiid)

– Completes a claimed activity instance and passes the result of user processing: complete(AIID aiid, ClientObjectWrapper output) complete(String aiid, ClientObjectWrapper output)

– Completes a claimed activity instance and denotes failing user processing: complete(AIID aiid, ClientObjectWrapper faultMessage, java.lang.String faultName) complete(java.lang.String aiid, ClientObjectWrapper faultMessage, java.lang.String faultName)

Returns: void

򐂰 forceComplete (invoke)

Description: Forces the completion of a stopped activity instance.

The activity instance must be in the stopped execution state and the associated process instance must be in the running execution state. The caller must be an administrator of the associated process instance.

Forcing the completion of an activity instance states that navigation of the process instance can continue. Depending on the stored result of user processing, output or fault message values are used to continue navigation.

If user processing did not complete successfully, or if a fault message was set, the activity instance is placed into the failed execution state when the fault is handled or when the continueOnError flag is set to true. It remains in the stopped execution state when the fault is not handled and the continueOnError flag is set to false.

Note: an output or fault message does not need to be set. Navigation can continue with an empty output message.

Chapter 1. Business Process Engine programming 77

Parameters:

– aiid - A string representation of the activity instance object ID or the object that identifies the activity instance to be completed.

– continueOnError - A flag that indicates what should happen in case of an error, that is, when a system exception or an unhandled fault occurs. True states that navigation should continue, that is, the activity instance is set into execution state failed, and the error is propagated to the associated process instance. False states that the activity instance stays in execution state stopped.

– output - The output message that denotes the successful result of processing. If output is not to be provided, null must be specified. The

Business Process Engine then uses the output available to the system.

The object wrapped by the ClientObjectWrapper must be serializable.

– message - The output or fault message. If an output or fault is not to be provided, null must be specified. The Business Process Engine then uses the output or fault available to the system. The object wrapped by the

ClientObjectWrapper must be serializable.

– faultName - The name of the fault, if any. Can also specify an output terminal for version 5.0 activities. If a fault name is specified, the fault must have been defined for the activity. Note that the structure of a BPEL fault name is a QName.

Signature:

– Forces the completion of a stopped activity instance: forceComplete(AIID aiid, boolean continueOnError) forceComplete(String aiid, boolean continueOnError)

– Forces the completion of a stopped activity instance using an output messsage: forceComplete(AIID aiid, ClientObjectWrapper output, boolean continueOnError) forceComplete(String aiid, ClientObjectWrapper output, boolean continueOnError)

– Forces the completion of a stopped activity instance and states the actual result of user processing: forceComplete(AIID aiid, ClientObjectWrapper message, String faultName, boolean continueOnError) forceComplete(String aiid, ClientObjectWrapper message, String faultName, boolean continueOnError)

Returns: void

78 Using the WebSphere Business Integration Server Foundation Programming APIs

򐂰 forceRetry

Description: Forces the repetition of a stopped activity instance.

The activity instance must be in the stopped execution state and the associated process instance must be in the running execution state. The caller must be an administrator of the associated process instance.

Optionally, an input message may be provided. The Business Process

Engine then uses the input message provided.

Parameters:

– aiid - A string representation of the activity instance object ID or the object

ID that identifies the activity instance to be retried.

– continueOnError - A flag that indicates what should happen in case of an error, that is, when a system exception or an unhandled fault occurs. True states that navigation should continue, that is, the activity instance is set into execution state failed and the error is propagated to the associated process instance. False states that the activity instance should stay in execution state stopped.

– inputMessage - The input message that specifies the values to be used by the activity instance. If input is not to be provided, null must be specified; the Business Process Engine then uses the input available to the system.

An empty ClientObjectWrapper causes the input message to be set to null. The object wrapped by the ClientObjectWrapper must be serializable.

Signature:

– Forces the repetition of a stopped activity instance: forceRetry(AIID aiid, boolean continueOnError) forceRetry(java.lang.String aiid, boolean continueOnError)

– Forces the repetition of a stopped activity instance using an input message: forceRetry(AIID aiid, ClientObjectWrapper inputMessage, boolean continueOnError) forceRetry(java.lang.String aiid, ClientObjectWrapper inputMessage, boolean continueOnError)

Returns: void

򐂰 setFaultMessage

complete/forceComplete

Description: Stores the specified fault message for the specified activity instance into the database. The fault message is saved only, that is, navigation does not continue. Refer to complete or forceComplete for information about how to complete an activity instance.

Any previously stored fault or output message is deleted.

Chapter 1. Business Process Engine programming 79

The activity instance must be in the claimed or stopped execution state and the associated process instance must be in the running, failing, or terminating execution state. The caller must have editor authority for the activity instance, be the owner of the activity instance, or be the administrator of the associated process instance.

For a BPEL process, the activity must be a staff activity.

Parameters:

– aiid - A string representation of the activity instance object ID or object ID.

This identifies the activity instance whose fault message is to be set.

– faultName - The name of the fault message to be set. Must be a fault defined for the activity. Note that the structure of a BPEL fault name is a

QName.

– faultMessage - The fault message. The object wrapped by the

ClientObjectWrapper must be serializable.

Signature: setFaultMessage(AIID aiid, String faultName, ClientObjectWrapper faultMessage) setFaultMessage(String aiid, java.lang.String faultName,

ClientObjectWrapper faultMessage)

Returns: void

򐂰 setOutputMessage

complete/forceComplete

Description: Stores the output message of the specified activity instance into the database. The output message is saved only, that is, navigation does not continue. Refer to complete or to forceComplete for information about how to complete an activity instance.

Any previously stored output or fault message is deleted. If a schema 5.0 activity has more than one output terminal, specify the output terminal name; otherwise, the first output terminal that the engine reads is set.

The activity instance must be in the claimed or stopped execution state and the associated process instance must be in the running, failing, or terminating execution state. The caller must have editor authority for the activity instance, be the owner of the activity instance, or be the administrator of the associated process instance.

For a BPEL process, the activity must be a staff activity. To repair variables used by a stopped invoke or script activity, refer to setVariable.

Parameters:

– aiid - A string representation of the activity instance object ID or the object

ID. This identifies the activity instance whose output message is to be set.

80 Using the WebSphere Business Integration Server Foundation Programming APIs

– outputMessage - The output message. The object wrapped by the

ClientObjectWrapper must be serializable.

Signature: setOutputMessage(AIID aiid, ClientObjectWrapper outputMessage) setOutputMessage(String aiid, ClientObjectWrapper outputMessage)

Returns: void

1.5.7 Queries and worklists

This group discusses queries and worklists.

򐂰 deleteWorkList

Description: Deletes the specified worklist. Only a business process administrator can delete a worklist. No error is signalled when the specified worklist no longer exists.

Parameters:

– workListName - The name of the worklist to be deleted.

Signature: deleteWorkList(String workListName)

Returns: void

򐂰 executeWorkList

Description: Executes the query defined by the worklist and returns the qualifying object properties. Only properties of objects are returned for which the logged-on user has a work item. Note that the business process administrator has special rights and can access all objects.

Parameters:

– workListName - The name of the worklist to be executed.

Signature: executeWorkList(String workListName)

Returns: QueryResultSet

The qualifying object properties. If qualifying objects are not found, an empty query result set is returned.

򐂰 getWorkList

Description: Retrieves the specified worklist definition.

Parameters:

– workListName - The name of the worklist to be retrieved

Chapter 1. Business Process Engine programming 81

Signature: getWorkList(java.lang.String workListName)

Returns: WorkListData

The definition of the worklist retrieved

򐂰 getWorkListActions

Description: Returns the actions that can be called by the logged-on user related to worklists.

Signature: getWorkListActions()

Returns: int[]

An array of worklist actions

򐂰 getWorkListNames

Description: Retrieves the names of worklists persistently stored in the database.

Signature: getWorkListNames()

Returns: String[]

An array of worklist names

򐂰 newWorkList

Description: Creates a worklist and persistently stores it in the database.

Only a business process administrator can create a worklist.

A worklist represents a set of selected object properties. The number of tuples in the set can be restricted by a filter or threshold. Additionally, sort criteria can be defined that are applied on the server.

The domain of the query, the SQL from-clause, is determined automatically.

In principle, all properties of objects are selectable for which you own a work item (which can be transitively reached via a user's work item). As a rule of thumb, all objects except process templates can be reached via work items.

The business process administrator has special rights and can access all objects and included process templates. The business process administrator is the only user who can use properties of the PROCESS_TEMPLATE view only. All other users must specify a non process template property in the select- or the where-clause.

Although worklist definitions are stored persistently, object properties contained in the worklist are assembled dynamically when they are queried.

All worklists are publicly accessible.

82 Using the WebSphere Business Integration Server Foundation Programming APIs

When a worklist definition needs to be updated, it must be deleted and recreated.

Parameters:

– workListName - The name of the worklist to be created. Cannot not be greater than 64 bytes in UTF-8 format. The name must be unique.

– selectClause - Describes the query result produced when the worklist is executed. It represents a list of names that identify the object properties

(columns of the result) to be returned. Its syntax is a SQL select-clause.

However, aggregation functions like AVG(), SUM(), COUNT(), MIN(), and

MAX() are not supported. Each part of the select-clause separated by a comma must specify a property from the published views.

A selectClause must not be greater than 512 bytes in UTF-8 format.

The QueryResultSet contains columns in the same order as specified in the selectClause.

– whereClause - Specifies the search condition that is applied when the worklist is executed. Its syntax is a SQL where-clause.

If a filter is not to be applied, null must be specified.

A whereClause must not be greater than 2048 bytes in UTF-8 format. orderByClause - Orders the result of the worklist execution by the values of the columns you identify. Its syntax is a SQL order-by-clause. Each part of the order-by-clause separated by a comma must specify a property from the published views. If you identify more than one property, the worklist execution result is ordered by the values of the first property you identify, and then by the values of the second property, and so on.

If sort criteria are not to be applied, null must be specified.

An orderByClause must not be greater than 254 bytes in UTF-8 format.

– threshold - The maximum number of worklist execution result tuples to be returned. If a threshold is not to be applied, null must be specified.

– time zone - Specifies the time zone of the time stamp constants in the whereClause. If a time zone is not specified, UTC is assumed.

Signature: newWorkList(String workListName, String selectClause, String whereClause,

String orderByClause, Integer threshold, TimeZone)

Returns: void

򐂰 query

Description: Retrieves selected object properties persistently stored in the database.

Chapter 1. Business Process Engine programming 83

You can specify a filter or a threshold to restrict the number of tuples returned.

The tuples are sorted on the server according to the specified sort criteria.

Specify the parameters of the query, the select-, where-, and order-by-clause, using SQL based on the published process views. Execution of the query can be shifted to SQL and becomes portable and optimizable.

The domain of the query, or the SQL from-clause, is determined automatically. In principle, all properties of objects are selectable for which you own a work item, which can be transitively reached via a user's work item.

As a rule of thumb, all objects except process templates can be reached via work items.

The business process administrator has special rights and can access all objects, included process templates. The business process administrator is the only user who can use properties of the PROCESS_TEMPLATE view only. All other users must specify a non process template property in the select- or where-clause.

Parameters:

– selectClause - Describes the query result. Represents a list of names that identify the object properties (columns of the result) to be returned. Its syntax is a SQL select-clause. However, aggregation functions like AVG(),

SUM(), COUNT(), MIN(), and MAX() are not supported. Each comma separated part of the select-clause must specify a property from the published process views—see the InfoCenter for details.

The QueryResultSet produced by selecting the specified properties only contains columns in the same order as specified in the selectClause.

– whereClause - The search condition to be applied to the query domain. Its syntax is a SQL where-clause. The following rules apply:

• Specify object ID constants as ID('string-rep-of-oid').

• Specify time stamp constants as TS('yyyy-mm-ddThh:mm:ss') or as

CURRENT_DATE for comparisons with the current date.

The date and time parts of a TS definition are optional; either the date or the time must be specified. If no date part of a TS definition is specified, the current date is taken. Optional time values that are not specified are set to zero. The time stamp is 24 hours based. For example, TS('16:04') is the same as TS('2002-12-24T16:04:00') provided that the current date is December 24th, 2002.

If a date part of a TS definition is specified, the year must consist of four letters. The month and day specifications are optional. Missing month and day specifications are set to 01. For example, specifying

TS('2003') is the same as specifying TS('2003-01-01T00:00:00').

• Specify binary constants as BIN('UTF-8 string').

84 Using the WebSphere Business Integration Server Foundation Programming APIs

• Use constants instead of integer enumerations. For example, instead of specifying an activity state expression "ACTIVITY.STATE=2" , specify "ACTIVITY.STATE=ACTIVITY.STATE.STATE_READY".

If a filter is not to be applied, null must be specified.

– orderByClause - Sorts the query result set by the values of the columns you identify. Its syntax is a SQL order-by-clause. Each comma separated part of the order-by-clause must specify a property from the published process views—see the InfoCenter for details.

If you identify more than one property, the query result set is ordered by the values of the first property you identify, then by the values of the second property, and so on.

If sort criteria are not to be applied, null must be specified.

– threshold - The maximum number of query result set tuples to be returned.

If a threshold is not to be applied, null must be specified.

– time zone - The time zone of the time stamp constants in the whereClause. If a time zone is not specified, UTC is assumed.

Signature: query(String selectClause,

String whereClause,

String orderByClause,

Integer threshold, timeZone)

Returns: QueryResultSet

An object containing the query result. If qualifying tuples are not found, an empty query result set is returned.

򐂰 getAllActivities (no join)

Description: Queries predefined activity instance properties of activities directly contained in the specified process instance or block instance or block instance ID. Following properties of an activity instance (columns of the query result set) are returned in the stated sequence: a. ID b. Name c. Execution state d. Kind e. Activation time

Note: For a BPEL process, only business-relevant activities are returned.

Chapter 1. Business Process Engine programming 85

The process instance can be in any execution state. The caller must have reader authority for the process instance, be the process administrator, or be the business process administrator.

Parameters:

– piid - The String representation of the object ID or the object ID of the process or schema 5.0 block instance.

– time zone - The time zone of all time stamp properties returned. If a time zone is not specified, timestamps are returned in UTC.

Signature: getAllActivities(String piid, timezone)

Returns: QueryResultSet

An object containing the query result. If qualifying tuples are not found, an empty query result set is returned.

1.5.8 Other API methods

This section describes miscellaneous API methods.

򐂰 getFaultNames

Description: For a BPEL process, retrieves the fault names defined for the specified activity instance.

Fault names can be retrieved in any execution state of the associated process instance. The activity instance must be in the claimed, expired, failed, finished, terminated, ready, or stopped execution state. The activity can be a staff or invoke activity.

The caller must have at least reader authority for the activity instance or the associated process instance.

Parameters: aiid - A string representation of the activity instance object ID or the object ID that identifies the activity instance for which fault names are to be retrieved.

Signature: getFaultNames(AIID aiid) getFaultNames(String aiid)

Returns:

򐂰 isBusinessProcessAdministrator

Description: Indicates whether the logged-on user is a business process administrator.

86 Using the WebSphere Business Integration Server Foundation Programming APIs

In general, authorization is granted to persons explicitly when a process model is defined or implicitly, for example, by starting a process instance.

Above that, special authority is granted to a person playing the role of a business process administrator. A business process administrator has all privileges.

Signature: isBusinessProcessAdministrator()

Returns: boolean

– True states that the logged-on user is a business process administrator.

– False states that the logged-on user is no business process administrator.

1.6 Sample scenario

This section describes a very simple JSP client for the process shown in

Figure 1-7. It is a process for assessing incidents. When the process is started a

message containing information about the submitter (name, street, city) and the incident (incident number, description and abstract) is passed to the process. In a first step the incident has to be assessed by a person. In case the input data is insufficient the submitter has to provide additional data (see the While loop). At some point in time the data is sufficient and the incident can be assessed, which will end the process. The process instance will not be deleted, so it is possible to retrieve the assessment of finished incident processes.

Figure 1-7 IncidentReport process

Chapter 1. Business Process Engine programming 87

Running the sample

If you have not already, install the SAW424* projects. Create and configure a test

server as described in Appendix B, “Configuration and setup” on page 199.

To run the sample, perform the following steps:

1. Switch to the Servers view.

2. Select and start the test server.

3. When the server is ready for business, expand the SAW424Web project.

4. Browse to the WebContent/jsp/bpe/incident folder.

5. In the context menu of Incident.jsp, select Run on Server...

6. Select the desired test server, accept the defaults, and click Finish.

A Web browser window displaying a page similar to Figure 1-8 on page 89

should open.

Note: You can also run the sample in a Web browser using the following Web address: http://localhost:9080/SAW424Web/jsp/bpe/incident/Incident.jsp

88 Using the WebSphere Business Integration Server Foundation Programming APIs

Figure 1-8 Incident sample JSP

Figure 1-9 on page 90 shows how to use the sample to create a new Incident.

Chapter 1. Business Process Engine programming 89

Figure 1-9 Submitting the input data will start the process

Figure 1-10 shows that two incidents must be assessed.

Figure 1-10 Currently two incidents have to be assessed

7. Select an incident ID to assess.

A page similar Figure 1-11 on page 91 appears.

90 Using the WebSphere Business Integration Server Foundation Programming APIs

Figure 1-11 The page to asses incidents is reached by clicking an incident number

8. Test the client by performing the various possible actions.

Code analysis

The sample consists only of two files, the Incident.jsp that you already saw, and the Java class containing the logic to access the Business Process Engine API.

The Java class is named IncidentReportController and can be found in the com.ibm.ral.itso.bpe.incident package of the SAW424Web project. Please explore the Java class for yourself. It contains code to access the session API bean, start processes, query the BPE database, perform message handling, and for claiming and completing Staff activities.

Chapter 1. Business Process Engine programming 91

92 Using the WebSphere Business Integration Server Foundation Programming APIs

2

Chapter 2.

Common Event

Infrastructure programming

© Copyright IBM Corp. 2004. All rights reserved.

93

2.1 CEI introduction

The Common Event Infrastructure (CEI) is an embeddable technology intended to provide basic event management services to applications that require those services. This event infrastructure serves as an integration point for consolidation and persistence of raw events from multiple, heterogeneous sources, and distribution of those events to event consumers. Events are represented using the Common Base Event (CBE) model, a standard XML-based format defining the structure of an event.

By using this common infrastructure, diverse products that are not tightly coupled with one another can integrate their management of events, providing an end-to-end view of enterprise resources and correlating events across domain boundaries. For example, you can correlate events generated by a network monitoring application with events generated by a security application. Such correlation can be difficult to achieve when each product uses its own approach to event management.

The Common Event Infrastructure provides facilities for the generation, propagation, persistence, and consumption of events, but it does not define the events themselves. Instead, application developers and administrators define event types, event groups, filtering, and correlation.

The Common Base Event, within the CEI, provides a means of capturing information about significant system or business occurrences. For example:

򐂰 A significant system event may be when a particular server’s performance drops below a critical threshold.

򐂰 A significant business event encapsulates information that is specific to a particular business; for example, when an important client places an order, you might want to store extra information or alert individuals that this event occurred.

2.1.1 Business level event

CEI is a technology for logging and retrieving business level events. Business level events are those events that capture an event or activity occurrence that can later be observed and monitored by consumers wishing to analyze the effectiveness of the business. Business level events can also trigger related and additional business level processing. Each is valuable to an organization looking to understand their business processes better and capitalize on the knowledge that is inherent in the execution of the business. The more automation that we apply to our business process, the more opportunity we have to gather and analyze data about these processes. This is a positive side effect of automating business processes. CEI is a technology that helps us leverage this eventuality.

94 Using the WebSphere Business Integration Server Foundation Programming APIs

The basic idea behind using CEI for business level logging is to enable business process improvement in a more systematic and automated fashion. The basic concept is that events are created with relevant information for later use and then sent, via an emitter, to the event infrastructure. The sender of the event can be new J2EE application code, or it could be specially outfitted infrastructures such as adaptors and process engines. These pieces of infrastructure are written to automatically emit events that are business relevant. Event producer is the term applied to the software that emits or sends events to the event infrastructure.

2.1.2 Common Base Event model

The Common Base Event model is a standard defining a common representation of events intended for use by enterprise management and business applications.

This standard, developed by the IBM Autonomic Computing Architecture Board, supports encoding of logging, tracing, management, and business events using a common XML-based format, which makes it possible to correlate different types of events that originate from different applications. The Common Base

Event model is part of the IBM Autonomic Computing Toolkit. For more information, visit the following Web address: http://www.ibm.com/autonomic

The Common Event Infrastructure currently supports version 1.0.1 of the specification.

The basic concept behind the Common Base Event model is the

situation

. A situation is anything that happens anywhere in the computing infrastructure, such as a server shutdown, a disk-drive failure, or a failed user login. The Common

Base Event model defines a set of standard situation types that accommodate most of the situations that might arise (for example, StartSituation and

CreateSituation).

An

event

is a structured notification that reports information related to a situation.

An event reports three kinds of information:

򐂰 The situation itself (what has happened)

򐂰 The identity of the affected component (for example, the server that has shut down)

򐂰 The identity of the component that is reporting the situation (which might be the same as the affected component)

The Common Base Event specification defines an event as an XML element containing properties that provide all three kinds of information. These properties are encoded as attributes and sub-elements of the root element,

CommonBaseEvent.

Chapter 2. Common Event Infrastructure programming 95

The Common Base Event format is extensible. In addition to the standard event properties, an event can also contain extended data elements, which are application-specific elements that can contain any kind of information relevant to the situation. The

extensionName

attribute labels an event with an optional classification name (an event class), which indicates to applications what sort of extended data elements to expect. The event catalog stores event definitions that describe these event classes and their allowed content.

For complete details on the Common Base Event format, see the specification document and XSD schema included in the IBM Autonomic Computing Toolkit.

CBE structure

A Common Base Event contains several structural elements:

򐂰 Common header information

򐂰 Component Identification

򐂰 Situation Information

򐂰 Extended data

򐂰 Context data

򐂰 Associated events and association engine

򐂰 Message data

Each of these structural elements has its own embedded elements, or fields. The

logical structure of CBE is illustrated in Figure 2-1 on page 97.

96 Using the WebSphere Business Integration Server Foundation Programming APIs

Figure 2-1 Common Base Event structure

Some of these elements are required and some are not. If a required field is not filled in, then the emitter throws a MissingPropertyException. Any event that is incomplete or missing a required property, can automatically be filled in by calling the complete() method on the CBE. It is recommended to call the complete() method right before all events are sent. The required fields are global_id, version, creationTime, ComponentIdentification, and Situation. The important optional properties are priority, severity, msg, extension_name,

ContextDataElement and ExtendedDataElement. Please note that this is not a complete list of CBE properties, they are just the properties that best apply to business events.

Note: The behavior of complete() method applies only to ECSEmitter implementation for an emitter. The complete() method in emitter implementation will not fill in all required values automatically. The emitters

are discussed in more details in “Event emitter” on page 107

Chapter 2. Common Event Infrastructure programming 97

The following sections contain further descriptions of the CBE elements.

Required Fields

Table 2-1 provides the required fields of CBE.

Table 2-1 CBE required fields

Required CBE field

Global_id

Version

CreationTime

SourceComponentId

Description

A global_id is an unique value that identifies an event. It is important that all global_ids be unique because they are used as keys for many of the

CEI database tables.

The version property is used to describe the version of an event. The default value is 1.0.1 to indicate the version of the Common Base Event specification defined by hyades.

The creationTime property describes when an event is created.

The sourceComponentId is set using a

ComponentIdentification object. The source component is the component in which the event happens. The ComponentIdentification class provides a collection of attributes that are required to uniquely define a component. A

ComponentIdentification class is used to specify both the sourceComponentId and the reporterComponentId. In many cases, they are the same and therefore, only the source is set.

Table 2-2 on page 98 describes the component

data and the values that are filled in by default for the source component using the ECSEmitter.

Table 2-2 contains the default sourceComponentID values.

Table 2-2 Default sourceComponentId values. Refer :WBI SF5.1.1 Information Center

Attribute Description Value filled in ECSEmitter complete() method application OPTIONAL

The name of the application

(for example myWebApp). null

98 Using the WebSphere Business Integration Server Foundation Programming APIs

Attribute component componentIdType executionEnvironment instanceId location locationType processId subComponent threadId

Description

REQUIRED

Specifies the logical identity of a component (for example IBM

DB2#7.1)

REQUIRED

Specifies the format and the meaning of the ComponentIdentity

OPTIONAL

Specifies the immediate environment that an application is running on

OPTIONAL

Specifies a handle or identifier for the instance of the component that is specified for the component property

REQUIRED

Specifies the physical address that corresponds to the location of the component

REQUIRED

Specifies the format and meaning of the location value

OPTIONAL

Specifies the process ID of the running component or subcomponent that generated the event

REQUIRED

Specifies a further distinction for the logical component property of the event. It should contain the identity of the subcomponent.

OPTIONAL

Defines the thread ID of the component that generated the event

Value filled in ECSEmitter complete() method

Set to WBI-SF followed by the version information of the WebSphere components

Set to ProductName

A string that describes the operating system in which the application server is running

The identifier of the application server

This ID has the format: <cell name>/<node name>/<server name>

The host name of the server (or server region for z/OS)

Default is "Hostname"

The identifier of the operating system process

The default is J2EE_Application.

The identifier of the current thread

Chapter 2. Common Event Infrastructure programming 99

Attribute componentType

Description

REQUIRED

A name that characterizes all instances of a given kind of component.

Value filled in ECSEmitter complete() method http://www.ibm.com/namespaces/auto nomic/WebSphereApplicationServer

򐂰 Situation

The situation property of a CBE describes the type of situation that caused the event to be emitted. Every event must have only one situation category

associated with it. Table 2-3 describes the situation categories and the

properties associated with those categories. You cannot change the structure of these categories, nor can you add new categories.

Table 2-3 Situation categories and their associated properties

Category name

StartSituation

StopSituation

ConnectSituation

ConfigureSituation

RequestSituation

FeatureSituation

DependencySituation

CreateSituation

Description

Messages indicate that a component began startup, finished startup, or aborted startup.

Messages indicate that a component began to stop, stopped, or failed to stop.

Messages indicate that a connection was created, ended, or failed to connect.

Properties

ReasoningScope,

SuccessDisposition,

SituationQualifier reasoningScope, successDisposition, situationQualifier reasoningScope, successDisposition, situationDisposition reasoningScope, successDisposition

Messages indicate any component configuration. They might include port numbers, addresses, process ids, and so on.

Messages indicate that a component identifies the completion status of a request

Messages indicate that a component feature, like a service, is available/not available.

Messages indicate that a dependency was met/not met. Messages usually include 'could not find' or 'no such component'

Messages that indicate when a component created something reasoningScope, successDisposition, situationQualifier reasoningScope, featureDisposition reasoningScope, dependencyDisposition reasoningScope, successDisposition

100 Using the WebSphere Business Integration Server Foundation Programming APIs

Category name

DestroySituation

ReportSituation

AvailableSituation

OtherSituation

Description

Messages indicate that an entity or component was destroyed or removed

Messages that indicate information reported from a component

Messages that indicate an operational state or the availability of a component

Messages that do not fit into any of the categories

Properties reasoningScope, successDisposition reasoningScope, reportCatagory reasoningScope, operationDisposition, availabilityDisposition, processingDisposition reasoningScope, any

Every category has properties associated to them. These properties are defined by having certain values in the Canonical Situation Data Format: The Common

Base Event V1.0.1 specification. Table 2-4 illustrates these values. Although the

properties are defined in this way, the API allows for any string up to 64 characters.

Table 2-4 Static situation property values

Property Values

ReasoningScope INTERNAL, EXTERNAL

SuccessDisposition

SituationQualifier

SUCESSFUL, UNSUCESSFUL

START INITIATED, RESTART INITIATED, START COMPLETED, STOP

INITIATED, ABORT INITIATED, PAUSE INITIATED, STOP

COMPLETED, REQUEST INITIATED, REQUEST COMPLETED

SituationDisposition

FeatureDisposition

DependencyDisposition

ReportCatagory

OperationDisposition

AvailabilityDisposition

ProcessingDisposition

Any

INUSE, FREED, CLOSED, AVAILABLE

AVAILABLE, NOT AVAILABLE

MET, NOT MET

PERFORMANCE, SECURITY, HEARTBEAT, STATUS

STARTABLE, NONSTARTABLE

AVAILABLE, NOT AVAILABLE

FUNCTION_PROCESS, FUNCTION_BLOCK, MGMTTASK_PROCESS,

MGMTTASK_BLOCKED

No set values exist

Chapter 2. Common Event Infrastructure programming 101

Optional fields

Following are the optional fields of CBE.

򐂰 Priority

The priority field describes how important the event is or the relative order in which this event is to be processed. The values are from 0-100, where 0 is a

low priority and 100 is high. The predefined priorities are shown in Table 2-5.

90

70

50

10

1

Table 2-5 Event Priority

Priority value

(short)

Description

100 This event must be processed first and is the highest priority available.

This is an urgent event. Process as soon as possible.

This is an important event.

This is an average event.

This is a low priority event.

Process this event last.

򐂰 Severity

The severity field focuses on how bad or serious an event is. The values are

from 0-70, where 0 is unknown and 70 is fatal. Table 2-6 shows some

predefined severity values.

Table 2-6 Event Severity

Severity value (short) Description

70

60

Fatal - Indicates that an error occurred and remedial action is not possible

Critical - Indicates an error that requires immediate remedial action

50

40

30

20

Major - Indicates an error that needs attention

Minor - Indicates that action is needed but the situation is not critical

Warning - Signals a warning to the user. The user can then decide if any action is needed.

Harmless - An error occurred but will cause no harm to the application or the system.

102 Using the WebSphere Business Integration Server Foundation Programming APIs

Severity value (short) Description

10 Information - Signals that the event is only for information and no error occurred

0 Unknown

򐂰 Msg

The msg field is a string describing the event.

򐂰 Extension_name

The extension_name property is the name for the event. Although this property is optional, the code examples shown later require an extension_name for the creation of an event. The examples also use ':' to separate the domain and the event description. This is a common practice to convey multiple kinds of data in the same name. Events that inherit from other events also tend to use a separator to show the whole event type, for instance, parent.child.

Extension_name is required when using the event catalog. Each event type must have a unique extension_name. Multiple events with the same extension_name may be emitted to the CEI server. In such a case they are all thought of as having the same type. It is recommended to use this property because it can be useful in distinguishing between two events.

򐂰 ContextDataElement

The ContextDataElement property is a complex property that holds any contextual information. WebSphere Business Integration Server

Foundationhas added Emitter Correlation Sphere (ECS) values as context data elements. Emitter correlation spheres are used for event correlation.

These values are the current sphere id (ECSCurrentID) and the parent sphere id (ECSParentID). Conceptually events are thought of as existing inside of spheres. ECSCurrentID represents the first sphere. Events that contain the same ECSCurrentID are thought of as being highly correlated.

Events that have the same ECSParentID are still related, but not as strongly

related as those within the same ECSCurrentID. Figure 2-2 on page 104

illustrates these spheres.

Chapter 2. Common Event Infrastructure programming 103

Event A

ECS Current ID: X

ECS Parent ID: null

X

Event B

ECS Current ID: Y

ECS Parent ID: X

Y

Event C

ECS Current ID: Z

ECS Parent ID: Y

Z

Figure 2-2 Sample scenario for emitter spheres

Event A belongs to sphere X and does not have a parent sphere. Event B belongs to sphere Y and has the parent sphere X. Event C belongs to sphere

Z and has the parent sphere Y. Although event C has the parent sphere Y, you can trace it back to X by looking at the parents of the events within Y.

򐂰 ExtendedDataElement

An ExtendedDataElement is a complex CBE property. These properties are essential to business events because they store most of the business relevant information. ExtendedDataElements are name and value pairings of

104 Using the WebSphere Business Integration Server Foundation Programming APIs

information related to an event. Most business data is easily represented with an ExtendedDataElement property.

The fields described above apply to or could apply to business relevant events. For a complete list of CBE properties please refer to the specification

Canonical Situation Data Format: The Common Base Event V1.0.1.

2.1.3 CEI architecture

CEI is designed as a technology that you can integrate into larger solutions.

WebSphere Business Integration Monitor and WebSphere Business Integration

Server Foundation are the first generation of applications that build on CEI technology. In the next release of CEI, update and delete capabilities are available.

From an application integrator point of view, there are three key aspects of CEI:

򐂰 CEI Software Development Kit (SDK). A combination of client libraries, runtime components, and descriptive API documentation. Developers use the

CEI SDK and associated API documentation to initially write their applications and, later on, package the runtime components within their own installation modules to produce the final installation image of their products.

򐂰 CEI runtime. CEI components that actually service the requests initiated at event consumers and event sources, such as creation and purging of events.

Applications interact with the CEI runtime through the CEI APIs.

򐂰 CEI administration. Installation, configuration, and management aspects associated with CEI components.

As part of the overall IBM push for WebSphere-centric products, CEI is modeled as a J2EE application.

Additionally, certain product packages include a Web-based interface that allows

CEI operators to visualize and act on events routed through CEI server-side components. The interface is based on IBM Integrated Solutions Console (ISC).

The system administration follows the Common Configuration Model (WCCM).

The ISC-based event management console is not part of the default CEI technology distribution.

The CEI architecture overview shown in Figure 2-3 on page 106 illustrates the

main building blocks of the CEI and the main interaction points with external applications. The figure also delineates the separation between the components of the first CEI phase and the components planned for the next phase. For instance, phase 2 addresses the evolution of the current servlet-based Web console into a portlet-based console exploiting the IBM Integrated Solution

Console.

Chapter 2. Common Event Infrastructure programming 105

Figure 2-3 CEI architecture overview

The building blocks of the figure are explained in detail in the following sections.

Event bus

The event bus is the entry point for event creation requests into the CEI runtime.

The event bus acts as the conduit for event streams between event sources and event consumers. It ensures that events are routed to the event data store component for persistence (when configured to do so), and to the event distribution component for subsequent publication to consumers.

The event server (event bus, event distribution, event access, event data store) implementation and configuration are part of the CEI runtime and administration, respectively.

106 Using the WebSphere Business Integration Server Foundation Programming APIs

Event distribution

The event distribution component delivers subscribed events to event consumers distributed throughout the network. The distribution component also informs event consumers about changes to events for which they are interested, including event purges, updates, and deletes.

Event access

Event consumers interact with the Event access component whenever they need to query event data from the event database or effect changes on the events already persisted into the event database.

The component is also responsible to coordinate the interaction between the event data store and the event distribution components. The event access services provide an architected, pluggable interface between the bus and event data store persistence mechanism(s).

Event data store

The event data store component implements the event data store plug-in model that the event access component supports. Its sole responsibility in the system is to adapt requests from the event access component to an actual persistent event repository.

The event access component deals with the event data at the event management level while the event data store deals with the event data according to some native schema, for example an relational database management system

(RDBMS) implementation.

You can configure some installations not to use an event database. In these cases event consumers receive error messages upon requests for event queries and event purge operations.

Event database

An event database is the repository for event data managed by an event data store. The default event data store packaged with the CEI uses a relational database (RDBMS) to host the Event database. Providers for different event datastore plug-ins may choose to adopt a different technology, such as simple text files, object-relational databases, or even a connector to some other kind of

Enterprise Information System (EIS).

Event emitter

The event emitter component allows event sources to submit event creation requests to CEI. Its architectural function is four-fold:

Chapter 2. Common Event Infrastructure programming 107

1. Ensure that the event creation request conforms to the CBE event model.

This verification checks for mandatory fields and allowed value ranges for event properties. For instance, the event emitter refuses an event creation request where the value of the "severity" attribute is negative (the CBE specifies a valid range of 0-100).

2. Fill in mandatory fields that have default values. For instance, the

"creationTime" property may be filled-in by the event emitter component with the current system time stamp.

3. Filter out any event that does not match a filtering policy defined from an event management point-of-view. For instance, a CEI administrator may push a filtering policy to the emitters stating that events from a certain business application should not be sent to the event management infrastructure during maintenance periods.

4. Adapt the CBE event format to the transport mechanism of choice between the event emitter and the event bus. The transport mechanisms for the first release of CEI are JMS messages and direct EJB calls. Later releases should also support Web services and other methods of communication.

The event emitter exposes three interfaces:

1. The event submission interface: based on CBE event model and allows client applications to submit event creation requests.

2. An event-filtering interface: the mechanism for plugging in different event filtering mechanisms. The CEI event emitterEvent Emitter uses a modified version of the TEC State Correlation Engine as the default implementation for an event-filtering plug-in. Other providers may write an event-filtering component and use it as a replacement to the default event filter.

3. A configuration management interface: allows dynamic changes in the event emitterEvent Emitter configuration.

An implementation of all the CEI components is included in the CEI SDK.

The event emitter interfaces are part of the CEI SDK. The event emitter implementation and configuration are part of the CEI runtime and CEI administration, respectively.

Event catalog

The event catalog is a repository of event metadata in the system. It allows other applications to understand an event's content based on the event's extension name. The rationale behind the event catalog component is that the CBE model specifies the semantics for all event properties in the base event, but the base model cannot specify the semantics for

108 Using the WebSphere Business Integration Server Foundation Programming APIs

application-specific data in extended data elements or context data elements.

The event catalog allows the definition of those semantics.

The CEI event catalog hosts the event definitions from the external applications that flow their events through CEI. The main consumers of the event catalog data are planning and configuration tools, which operators can use to assist them to configure the system based on the expectation of certain extended data elements.

For instance, a graphical editor for correlation rules may use definitions in the event catalog to allow the rule writer to browse the fields available within an event type and point only to the fields relevant to the rule execution. Going a step further, the event definition information may be used on such a graphical rule editor to provide an auto-completion feature similar to the one available in

WebSphere Studio.

Another potential use of the event catalog is during runtime. For instance, an application subscribed to the event bus may use the information about the event catalog to determine the integrity of an event notification. A correlation engine is a good example of an application that may follow this pattern.

A third usage pattern is the bi-directional mapping between event sources and CBE extension names for the events produced by these sources. An application can consult the event catalog to determine all CBE extension names (types of events) associated with an application-type, and vice-versa.

Event source

From the CEI perspective, event sources are applications or components that submit event creation requests through the event emitter component.

Examples of such event sources are log file adapters, monitors for workflow containers, monitors for J2EE containers, applications explicitly instrumented to emit CEI events, SNMP trap emitters, and others.

Event consumer

Event consumers are applications that subscribe to the event bus in order to receive event notifications or that use the CEI APIs to query or update event data persisted in event data stores.

An example of event consumers are correlation engines that subscribe to the event bus to receive notifications about events with certain characteristics and then produce new events upon detection of a pattern in the received events. An event correlation engine may also simply update one or more event attributes on an event.

Another example of an event consumer is an event console, which initially queries a CEI server for a list of events according to certain characteristics, and then subscribes to a real-time input stream of events. It allows an

Chapter 2. Common Event Infrastructure programming 109

operator to browse the list of events. The operator may also use the event console to update event properties, for instance to change the priority of an event from medium to high.

Notification helper

The notification helper component maps CEI-related concepts to messaging-related concepts so that event consumers can interact with the messaging infrastructure using the messaging programming model rather than a CEI interface wrapped around it.

Preserving the messaging programming model allows application developers for the event consumers to rely on better-established tools, concepts, and infrastructure support. As one of many concrete examples, CEI 1.0 supports a JMS messaging mechanism between the back end (event distribution component) and the event consumers. Preserving the programming model also enables event consumers to write J2EE Message Driven Beans to process event notifications.

The notification helper exposes three main functions in CEI architecture: a. Mapping of an event group definition to a target topic for actual subscription b. Mapping of event selector expressions to actual subscription message selector c. Mapping of notifications to CBE event format

Event groups

CEI is designed to handle events in the order of thousands, and even millions. This magnitude of data requires a grouping model that allows efficient processing.

An event group is represented through event selector expressions. Whenever an event matches the event selector expression for that event group, the event is said to be part of that event group. An event may fit into more than one filter constraint, which means an event may be part of more than one event group.

An event group has three main roles within the CEI architecture:

– Determination of target queues and topics for event notifications at the event distribution subsystem

– Anchor for authorization control lists (ACL's) throughout the system

– Basic parameters for event queries

The attributes of an event group are:

– Name: Symbolic name for the event group, such as "NT_events" or

"Insurance_claims".

110 Using the WebSphere Business Integration Server Foundation Programming APIs

– Selector expression: A logical expression written in terms of event attributes. Events that match the expression are considered part of the event group, for instance ((severity=HIGH) and

(sourceComponentId.location="hostname")).

2.2 Working with events

The Common Event Infrastructure represents events as Java objects.

Specifically, each event is an instance of a class implementing the org.eclipse.hyades.logging.events.cbe.CommonBaseEvent interface, which is a

Java representation of the Common Base Event specification. For more

information about this specification, see 2.1.2, “Common Base Event model” on page 95. The org.eclipse.hyades.logging.events.cbe package is part of the

Eclipse-based Hyades environment, which is a set of standards and open-source tools for testing, tracing, and monitoring. For more information, visit the following

Web address: http://www.eclipse.org/hyades/

The typical life cycle of an event is as follows:

1. To send an event, an event source creates a new instance of Common Base

Event, populates it with property data, and then submits it to an emitter.

2. The emitter optionally uses the content completion mechanism (if implemented) to populate the event with required property data automatically.

The emitter then validates the event against the Common Base Event specification and checks it against the currently configured filter criteria. If the event is valid and passes the filter criteria, the emitter sends the event to the event server. For more information about event processing by the emitter,

see “Creating an event” on page 112.

3. If persistence is enabled, the event server stores the event in a persistent data store.

4. If publishing is enabled, the event server publishes the event to one or more

Java Message Service (JMS) destinations. Event consumers subscribing to these destinations then receive notifications of the new event. The event consumers then use the notification helper to convert the received JMS messages back into a Common Base Event instance.

An event consumer might also submit a query to retrieve the event from the data store. Typically, a consumer uses the query interface to retrieve historical events, especially during startup processing.

After receiving the event, an event consumer reads the event property data and processes the event. For more information about event consumers, see

“Event consumer” on page 134.

Chapter 2. Common Event Infrastructure programming 111

5. When it is no longer needed, the event can be purged from the data store.

The Common Base Event specification, which is based on the XML Schema definition language, defines two kinds of event property data:

򐂰 Properties represented by simple data types, encoded in XML as attributes of the CommonBaseEvent element. These include properties such as

globalInstanceId

,

severity

, and

msg

. The CommonBaseEvent Java class represents these values as strings or integers, as appropriate.

򐂰 Properties represented by complex data types and encoded in XML as subelements of the CommonBaseEvent element. These include properties such as

situation

,

sourceComponentId

, and

extendedDataElements

, each of which has nested properties of its own. These complex types are represented by specialized Java classes defined in the org.eclipse.hyades.logging.events.cbe package. For example, the

sourceComponentId

property is represented by an instance of

ComponentIdentifier.

The CommonBaseEvent interface defines getter and setter methods for each property, as well as helper methods to simplify creation of complex properties.

An event source uses the setter methods (or the helper methods) to populate an event with property data before submitting it to an emitter. An event consumer uses the getter methods to retrieve the property data from a received event.

2.2.1 Creating an event

CEI provides a Java programing interface for creating an event. Figure 2-4 on page 113 shows an overview of the key features in the Common Event

Infrastructure. To create new events in your event source, use an

event factory

, which is an object that returns new instances of CommonBaseEvent or of the specialized classes representing complex property data types.

There are two ways you can access an event factory:

򐂰 You can create a new event factory using the

event factory

factory. Use this approach if no appropriate event factory is already available. When you create a new event factory, you can optionally specify a content handler to provide automatic content completion. For more information about content

completion, see “Completing event content automatically” on page 116.

򐂰 You can use an existing event factory that was bound into a JNDI namespace. Use this approach if an administrator provided an event factory for you to use. This ensures that any events you create conform to the appropriate business rules, because the event factory might be configured with a content handler.

112 Using the WebSphere Business Integration Server Foundation Programming APIs

Figure 2-4 Overview of CEI

Creating an event factory object

To create a new event factory, use the event factory factory, implemented as the class EventFactoryFactory. This class has no instances; instead, it provides two static methods used to create event factories. The decision of which method to use depends upon whether you want to use a content handler to implement

automatic content completion. For more information, see “Completing event content automatically” on page 116.

򐂰 To create a generic event factory with no content handler, use the createEventFactory() static method of EventFactoryFactory:

EventFactory eventFactory = (EventFactory)

EventFactoryFactory.createEventFactory();

Chapter 2. Common Event Infrastructure programming 113

򐂰 To create an event factory with a content handler, use the createEventFactory(ContentHandler) method, specifying the content handler you want to use:

EventFactory eventFactory = (EventFactory)

EventFactoryFactory.createEventFactory(contentHandler);

In either case, the returned object is an event factory you can use to create new events.

JNDI lookup

If an administrator binds an existing event factory into JNDI for event sources to use, perform a standard JNDI lookup to retrieve the event factory: import javax.naming.*; import org.eclipse.hyades.logging.events.cbe.*;

Context context = new InitialContext();

EventFactory eventFactory = (EventFactory) context.lookup("com/ibm/events/EventFactory");

The returned object is the provided event factory; if the event factory is configured with a content handler, an instance of the content handler is also created locally. For more information about content handlers and JNDI, see

“Completing event content automatically” on page 116.

Creating and populating an event

After obtaining an event factory, you can create event objects and populate them with property data. Most event properties are defined as optional by the Common

Base Event specification, but the following properties are required:

򐂰

version

(a string attribute)

򐂰

򐂰

򐂰

creationTime

(an XML Schema dateTime attribute; see http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/#dateTime )

sourceComponentId

(a complex ComponentIdentification element)

situation

(a complex Situation element)

Note: The version attribute is defined as optional by the Common Base Event specification, but if it is not specified, the default value 1.0 is assumed.

Because the Common Event Infrastructure supports only version 1.0.1 of the specification, this value must be specified.

If you try to send an event that is missing any of these properties, the emitter rejects the event and throws an EventsException exception.

114 Using the WebSphere Business Integration Server Foundation Programming APIs

The code snippet in Example 2-1 creates an event and populates it with the

minimal required property data:

Example 2-1 Creating and populating an event

CommonBaseEvent event = eventFactory.createCommonBaseEvent(); event.setVersion("1.0.1"); // set version long currentTime = System.currentTimeMillis(); // get current time event.setCreationTimeAsLong(currentTime); // and set creationTime

// set sourceComponentId (a complex type) event.setSourceComponentId("Windows",

"svchost.exe",

// application

// component

"tlntsvr.exe", // subcomponent

"http://www.ibm.com/namespaces/autonomic/Windows",

"win386_svc",

"9.45.72.138",

"IPV4"

// componentType

// componentIdType

// location

// locationType

);

// create situation object

Situation situation = eventFactory.createSituation();

// set situationType to AvailableSituation (a complex type) situation.setAvailableSituation("EXTERNAL", // reasoningScope

"NOT AVAILABLE", // availabilityDisposition

"STARTABLE", // operationDisposition

"FUNCTION_PROCESS"); // processingDisposition

// set situation event.setSituation(situation);

Example 2-1 first uses an event factory to create a new event instance,

event

.

First it sets the version property, and then it retrieves the current system time and uses the setCreationTimeAsLong(long) method to set the value of the

creationTime

property. An alternative is to use the setCreationTime(String) method, which sets the creation time using the XML dateTime format (for example, "2004-07-29T13:12:00-05:00").

The next required property,

sourceComponentId

, is a complex property represented by an instance of ComponentIdentification, which has properties of its own. However, it is not necessary to directly instantiate or interact with this object (although it is possible to do so). Instead, the next statement in the example uses a helper method, setSourceComponentId(), to specify the nested properties. The helper method uses these values to create an instance of

Chapter 2. Common Event Infrastructure programming 115

ComponentIdentification that it then uses to set the value of the

sourceComponentId

property of the event.

Similar helper methods exist for setting other complex properties (for example, setMsgDataElement(), addAssociatedEvent, and addExtendedDataElement()).

Many of these methods exist in multiple versions with different signatures, making it possible to specify property values in different ways. Refer to the

Hyades Javadoc API documentation for complete information about these methods on page 221.

The last required property in the example,

Situation

, is another complex property. In this case the situation object must be instantiated directly using an event factory. The example then uses a helper method to set the

situationType

property, which is itself a complex subelement.

In an actual application, a useful event needs to include more information than is shown here, but this is the minimum required by the Common Base Event specification and the Common Event Infrastructure. The event is now valid, and you can submit it to an emitter.

Completing event content automatically

In some situations, you might want some event property data to be automatically set for every event you create. This is a way to fill in certain standard values that do not change (such as the application name), or to set some properties based on information available from the run-time environment (such as creation time or thread information). You can also set policies that govern event content according to business rules; for example, you might require that any event with a particular extension name have its severity set to a certain value.

You can do this by creating a content handler. A content handler is an object that automatically sets the property values of each event based on any arbitrary policies you want to use. The Common Event Infrastructure does not restrict how a content handler can modify event data, as long as the event still conforms to the Common Base Event specification.

To ensure that all event sources comply with the same policies, you can create an event factory associated with a content handler (using EventFactoryFactory), and then bind the created event factory into a JNDI namespace. Instead of creating their own event factories, event sources can then perform JNDI lookups to access the event factory that already exists, without any knowledge of the content handler. If your business rules later change, you can modify the content handler in one place.

An event source does not need to do anything to enable content completion. If an event factory is associated with a content handler, each event it creates carries

116 Using the WebSphere Business Integration Server Foundation Programming APIs

with it a reference to that content handler. When the event is submitted to an emitter, the event calls the completeEvent() method of the content handler, passing a reference to itself. This ensures that the correct policies are applied to the event after the event source is finished setting event-specific properties, but before the event is validated and processed by the emitter.

Note: When an event is transmitted from one process to another, the reference to the content handler is not transmitted with it. This is because content completion relies upon the environment where the event originates, and the necessary information might not be available elsewhere. This restriction does not affect calls between applications that are local to one another (for example, a call to an enterprise bean using its local interface).

To create a content handler, follow these steps:

1. Create a new Java class implementing the org.eclipse.hyades.logging.events.cbe.ContentHandler interface. This interface defines a single method called completeEvent(CommonBaseEvent).

The parameter is the event whose content is to be completed. In your implementation of this method, use the getter and setter methods of

CommonBaseEvent to process the event property data in accordance with any policies that apply.

Note: When an event source uses JNDI to retrieve an event factory, the content handler is returned along with the event factory. For this reason, the content handler must be serializable.

Example 2-2 is a simple content handler that automatically sets the extension

name of each event:

Example 2-2 Using a content handler import java.io.Serializable; import org.eclipse.hyades.logging.events.cbe.*; public class BusinessContentHandler implements ContentHandler,Serializable { public void completeEvent(CommonBaseEvent event) throws CompletionException { event.setExtensionName("business");

}

}

2. Associate the content handler with an event factory. To do this, specify the content handler when creating the event factory:

EventFactory eventFactory = (EventFactory)

EventFactoryFactory.createEventFactory(contentHandler);

Chapter 2. Common Event Infrastructure programming 117

The returned event factory is permanently associated with the specified content handler.

3. Bind the event factory object into JNDI to make it accessible to other applications:

Contect newContext = new InitialContext(); newContext.bind(“eventFactory/newCustomEventFactory“);

// obtain the event factory from JNDI

EventFactory eventFact = (EventFactory) context.lookup(“eventFactory/newCustomEventFactory“);

2.3 Event source

An event source is any application that uses an emitter to send events to the event server. The following applications are examples of event sources:

򐂰 An adapter or monitor that generates events related to monitored resources

򐂰 An application that generates notification events

򐂰 An application that forwards events from other sources

2.3.1 Different ways of event generation

There are three ways to send events.

򐂰 The first way is to use the Java API. This option gives the most flexibility to decide what information is sent, but it requires more work on the coding side.

򐂰 The second way is to configure events to be sent using deployment descriptors. This option allows for events to be sent when a method of an EJB is called.

򐂰 The third way is to configure events to be sent within a BPEL process.

We discover more about event management using Java in the following sections.

2.3.2 Using Java code

Note: While developing CEI based applications in WebSphere Studio

Application Developer Integration Edition, you must configure the test environment server to be CEI enabled. The configuration steps can be found

in Appendix B, “Configuration and setup” on page 199.

118 Using the WebSphere Business Integration Server Foundation Programming APIs

An event source is implemented in the Java programming language, using either the Java 2 Platform, Standard Edition(J2SE) or Java 2 Platform, Enterprise

Edition(J2EE). An event source must submit valid events conforming to the

Common Base Event model (for more information, see 2.1.2, “Common Base

Event model” on page 95). Each event is represented as a Java object.

Emitters and emitter factories

An event source does not interact directly with the event server; instead, it interacts with an object called an emitter (an implementation of the com.ibm.events.emitter.Emitter interface). An emitter is a local object that provides methods for sending events.

In general, the emitter handles the details of event transmission. It is not necessary for the developer of an event source to be concerned about the event server location, the filter settings, or the underlying transmission mechanism.

Details such as these are governed by the emitter factory, an object configured by an administrator and bound in a Java Naming and Directory Interface (JNDI) namespace. An emitter factory is an an instance of com.ibm.events.emitter.EmitterFactory and creates emitter objects. It also defines the behavior of the emitters it creates. It includes settings for the following:

Emitter Object

The preferred

transaction mode

Description

This setting specifies whether the emitter attempts to send each event in a new transaction or within the current transaction. An event source can change this setting for a particular emitter or event submission, but the profile specifies the default value. (This setting is valid only in a J2EE container. The J2SE platform does not provide transaction controls.)

The preferred

synchronization mode

This setting specifies whether events are sent using synchronous or asynchronous transmission. Synchronous transmission means that the sendEvent() method does not return control to the caller until the event is processed. Asynchronous transmission means that the method returns immediately after the event is submitted, and the caller has no further information about event processing.

Again, an event source can change this setting for an emitter or for an event submission, but the default value is specified by the profile.

Chapter 2. Common Event Infrastructure programming 119

Emitter Object

The

transmission profiles

The

filter configuration

The Emitter and

ECSEmitter classes

Description

A transmission profile is a configuration object that defines a specific transmission mechanism for sending events to the event server. An emitter factory profile can specify two transmission profiles, one for synchronous transmission and one for asynchronous transmission. An event source cannot change the transmission profiles used by an emitter. Use the filter configuration for the emitter.

The filter configuration defines what filtering plug-in filters events submitted to the emitter. The Common Event Infrastructure includes a default filter plug-in, but you can also implement your own filter plug-in if you want to use a different filtering engine.

The Emitter and ECSEmitter classes are currently the only two implementations for an emitter. The ECSEmitter is new in

WebSphere Business Integration Server Foundation version 5.1.1 while the Emitter is available in both the technical preview and in

5.1.1.

Using an emitter

Before you can obtain an emitter, there must be at least one emitter factory profile configured. For each emitter factory profile, an emitter factory is automatically created and is accessible using the JNDI name of the emitter factory profile. To obtain an emitter, follow these steps:

1. Perform a JNDI lookup specifying the name of the emitter factory you want to use for your emitter. This is the JNDI name specified by an administrator when defining an emitter factory profile.

Tip: To create an emitter factory profile, follow these steps:

1. In the WebSphere administrative console, click Common Event

Infrastructure Provider

Emitter Factory Profile

New.

2. Specify the properties of the new profile. Refer to the online help for the

Emitter Factory Profile Settings page for detailed information about these properties.

3. Click OK to save your changes, and create the emitter factory profile.

4. Call the

getEmitter()

method of the emitter factory. The returned object is an emitter configured according to the options defined in the emitter factory profile you specified. If the emitter factory is unable to obtain an emitter, it throws an EmitterException exception.

5. The Example 2-3 code snippet obtains an emitter configured with the profile

Default

:

120 Using the WebSphere Business Integration Server Foundation Programming APIs

Example 2-3 Obtaining an emitter import javax.naming.*; import com.ibm.events.emitter.*;

Context context = new InitialContext();

EmitterFactory emitterFactory = (EmitterFactory) context.lookup("com/ibm/events/configuration/emitter/Default");

Emitter emitter = emitterFactory.getEmitter();

Using ECSEmitter

The Example 2-4 code snippet obtains ECSEmitter and sends an event. This is

the amount of code that sends an event.

Example 2-4 Sending simple event using ECSEmitter

24

25

26

27

28

29

30

31 }

32

20

21

22

23

16

17

18

19

12

13

14

15

8

9

10

11

1 import org.eclipse.hyades.logging.events.cbe.CommonBaseEvent;

2 import org.eclipse.hyades.logging.events.cbe.CompletionException;

3 import com.ibm.events.EventsException;

4 import com.ibm.websphere.cem.ECSEmitter;

5

6 public class EventGenerator {

7 public static void main(String[] args) {

EventGenerator t = new EventGenerator(); t.generateEvents();

} public void generateEvents() { try{

System.out.println("Before generating an event...........");

ECSEmitter myEmitter = new ECSEmitter(

"com/ibm/events/configuration/emitter/Default", null);

CommonBaseEvent event = myEmitter.createCommonBaseEvent("MySimpleEvent");

System.out.println("Event created..........."); event.complete();

System.out.println("Auto Completing an event..........."); myEmitter.sendEvent(event);

System.out.println("Event sent...........");

}catch (CompletionException e) { e.printStackTrace();

} catch (EventsException e) { e.printStackTrace();

}

}

Chapter 2. Common Event Infrastructure programming 121

The ECSEmitter constructor takes in two strings as parameters:

򐂰 The first string indicates the JNDI of a configured emitter factory. An emitter factory is bound into JNDI by an emitter factory profile. Although not shown in the example below, the emitter API allows the programmer to specify the

transaction mode

and

synchronization mode

. These settings, otherwise, correspond to the values set in the emitter factory profile. The value used for the emitter JNDI is the default emitter factory that is configured for CEI during installation.

򐂰 The second string parameter is the identifier of the correlation sphere in which this event belongs. When sending an event, decide if you want your event to be sent in the current Emitter Correlation Sphere (ECS), or if you want your event to start a new ECS. If you have not yet emitted any events or created an Emitter Correlation Sphere, then create a new sphere; otherwise, your events do not belong to a sphere. To create a new sphere, pass in any string value other than null for this parameter. If correlation is not a capability needed for your events, then pass in null for this value. Doing so sends an event with no values for the current sphere and the parent sphere.

The method used to create a new event takes in a string as a parameter. This string is the

extension_name

property for this CBE. This name is consistent with the event definition name that describes the event type.

The method

complete()

completes the event by filling in all required properties that we did not.

Method

send()

tells the emitter to then send the event on through CEI.

Note: To run these examples on WebSphere Studio Application Developer

Integration Edition, follow the instructions in “Event source sample code” on page 161

The code in Example 2-4 on page 121 produces an event with the properties and

values listed in Table 2-7. Notice the default values that were filled in for

version

,

sourceComponentId

, and

situation

.

Table 2-7 Properties and Values of simple event

Name Value version globalInstanceId extensionName

1.0.1

CECA36FA7F07A21625E30B8E50340011D9

MySimpleEvent

122 Using the WebSphere Business Integration Server Foundation Programming APIs

Name localInstanceId creationTime severity msg priority sequenceNumber repeatCount elapsedTime

ContextDataElement:

ECSCurrentID / contextValue

ContextDataElement:

ECSParentID / contextValue sourceComponentId / component

-

-

Value

2004-11-11T16:43:59.562Z

1

0

0

WBI-SF#Platform 5.1 [BASE 5.1.1 a0426.01]

[JDK 1.4.2 cn1420-20040626] [PME 5.1.1 o0429.02]

J2EE_Application sourceComponentId / subComponent sourceComponentId / componentIdType sourceComponentId / instanceId sourceComponentId / application sourceComponentId / executionEnvironment

ProductName localhost\localhost\server1

Windows® 2000[x86]#5.0

sourceComponentId / location 9.42.171.100

sourceComponentId / locationType Hostname sourceComponentId / processId sourceComponentId / threadId

1632

Servlet.Engine.Transports : 0 sourceComponentId / componentType msgDataElement http://www.ibm.com/namespaces/autonomic/W ebSphereApplicationServer

Chapter 2. Common Event Infrastructure programming 123

Name situation / categoryName situation / situationType / reasoningScope situation / OtherSituation / any

Value

OtherSituation

EXTERNAL

Application Event

Example 2-5 on page 124 shows how to manipulate the simple and the complex

properties of a Common Base Event.

We create a new ECSEmitter that emits events with a ECSCurrentID of

"myNewSphere" and ECSParentID of null. The value "myNewSphere" is interpreted as a new sphere, and in this case a new root sphere because the parent value is null. If we now create the new sphere, "myNewSphere2", then it has the ECSCurrentID of "myNewSphere2" and ECSParentID of

"myNewSphere", as long as myNewSphere is still active. The ECSCurrentID used below is somewhat misleading because these names should be generated by an algorithm. This algorithm should be constructed in such a way that the sphere name provides information about the events within the sphere. It is useful to have the ECSCurrentID based on time and also to have it include information that is specific to all events inside of the sphere. Correlation is further

discussed in section “Correlation” on page 154.

We first create a blank event and then populate it with top level properties such as

priority

and

msg

.

We create a EventFactory that creates Situation object, a

ComponentIdentification object and ExtendedDataElement objects.

Example 2-5 Creating a complex event

1 import java.net.InetAddress;

2 import java.net.UnknownHostException;

3 import javax.naming.InitialContext;

4 import javax.naming.NamingException;

5 import org.eclipse.hyades.logging.events.cbe.CommonBaseEvent;

6 import org.eclipse.hyades.logging.events.cbe.CompletionException;

7 import org.eclipse.hyades.logging.events.cbe.ComponentIdentification;

8 import org.eclipse.hyades.logging.events.cbe.EventFactory;

9 import org.eclipse.hyades.logging.events.cbe.ExtendedDataElement;

10 import org.eclipse.hyades.logging.events.cbe.Situation;

11 import com.ibm.events.EventsException;

12 import com.ibm.websphere.cem.ECSEmitter;

13

14 public class ComplexEventGenerator {

15

124 Using the WebSphere Business Integration Server Foundation Programming APIs

59

60

61

62

55

56

57

58

63

64

27

28

29

30

23

24

25

26

16

17

18

19

20

21

22 public static void main(String[] args) {

}

ComplexEventGenerator t = new ComplexEventGenerator(); t.generateEvents(); public void generateEvents() { try{

System.out.println("Before generating an event...........");

ECSEmitter myEmitter = new ECSEmitter(

"com/ibm/events/configuration/emitter/Default", "myNewSphere");

CommonBaseEvent event =

myEmitter.createCommonBaseEvent("MyComplexEvent");

System.out.println("Event created...........");

35

36

37

38

31

32

33

34 event.setPriority(new Integer(10).shortValue()); event.setMsg("MyMessage");

InitialContext ctx = new InitialContext();

EventFactory eventFactory =(EventFactory) ctx.lookup("com/ibm/websphere/events/factory");

43

44

45

46

39

40

41

42

//Add a Situation

Situation eventSituation = eventFactory.createSituation();

eventSituation.setCategoryName(Situation.REPORT_SITUATION_CATEGORY); eventSituation.setReportSituation("INTERNAL", "STATUS"); event.setSituation(eventSituation);

47

48

49

50

//Add SourceComponentId attribute

ComponentIdentification eventSourceComponentId = eventFactory.createComponentIdentification(); eventSourceComponentId.setComponentIdType(

ComponentIdentification.COMPONENT_ID_TYPE_PRODUCT_NAME); eventSourceComponentId.setApplication("EventTester"); eventSourceComponentId.setComponent("WBI-SF");

51 eventSourceComponentId.setComponentType(

52 "http://www.ibm.com/namespaces/autonomic/WebSphereApplicationServer");

53

54 eventSourceComponentId.setSubComponent("J2EE_Application"); eventSourceComponentId.setLocation(

InetAddress.getLocalHost().toString()); eventSourceComponentId.setLocationType(

ComponentIdentification.LOCATION_TYPE_HOSTNAME); event.setSourceComponentId(eventSourceComponentId);

// A regular ExtendedDataElement attribute

ExtendedDataElement data1=eventFactory.createExtendedDataElement(); data1.setName("MyRegularExtendedDataElement"); data1.setType(ExtendedDataElement.TYPE_STRING); data1.setValuesAsString("ExtendedDataValue");

Chapter 2. Common Event Infrastructure programming 125

88

89

90

91

92

93

94

95 }

96

84

85

86

87

80

81

82

83

76

77

78

79

72

73

74

75

65

66

67

68

69

70

71

} event.addExtendedDataElement(data1);

// Embedded ExtendedDataElement attribute

ExtendedDataElement data2=eventFactory.createExtendedDataElement(); data2.setName("MyEmbeddedExtendedDataElement"); data2.setType(ExtendedDataElement.TYPE_NO_VALUE); data2.addChild("Child1", "MyChild1"); data2.addChildWithIntValue("Child2", 2); data2.addChildWithDoubleValue("Child3", 3.33); event.addExtendedDataElement(data2);

System.out.println("Event populated..........."); event.complete(); myEmitter.sendEvent(event);

System.out.println("Event sent..........."); myEmitter.releaseAndEndECS(myEmitter.getCurrentEcsID()); myEmitter.close();

System.out.println("EventEmitter resource released...........");

}catch (CompletionException e) { e.printStackTrace();

} catch (EventsException e) { e.printStackTrace();

} catch (NamingException e) { e.printStackTrace();

} catch (UnknownHostException e) { e.printStackTrace();

}

Creating and populating a situation (lines 38 - 42)

As shown in Example 2-5 on page 124 we first create a situation from the event

factory. Set the category. Here we are setting it to be a REPORT category. Then we set the properties to the situation corresponding to the selected category

(Report category in this example). For the set of available categories and

corresponding properties refer to Table 2-3 on page 100. Here we set the

ReasoningScope

to 'INTERNAL' and the

ReportCatagory

to 'STATUS'. We then add the situation to the event.

Creating and populating a ComponentIdentification (lines 44 - 58)

As shown in Example 2-5 on page 124, we first create a blank

ComponentIdentification using the event factory. Then we set the component type that describes this ComponentIdentification property. The possible values

126 Using the WebSphere Business Integration Server Foundation Programming APIs

for this type are productName, deviceName, systemName, serviceName, process, application, and unknown. This property describes what this component id identifies. Next we set possible ComponentIdentification fields. Then we set the newly created ComponentIdentification to be the sourceComponentId of this event by using the setSourceComponentId(..) method. To set a reporterComponentId use the setReporterComponentId(…) method.

Creating and populating ExtendedDataElements (lines 60 - 74)

As shown in Example 2-5 on page 124, there are two different kinds of extended

data elements, regular and embedded. Extended data elements must have a name, value(s), and a type associated with them. The name must describe what the value represents. The value could either be a regular type or another extended data element, and the type must be one of the following values:

򐂰 TYPE_BOOLEAN_ARRAY_VALUE

򐂰 TYPE_HEX_BINARY_VALUE

򐂰 TYPE_BOOLEAN_VALUE

򐂰 TYPE_INT_ARRAY_VALUE

򐂰 TYPE_BYTE_ARRAY_VALUE

򐂰 TYPE_INT_VALUE

򐂰 TYPE_BYTE_ARRAY

򐂰 TYPE_LONG_ARRAY_VALUE

򐂰 TYPE_DATE_TIME_ARRAY_VALUE

򐂰 TYPE_LONG_VALUE

򐂰 TYPE_DATE_TIME_VALUE

򐂰 TYPE_NO_VALUE_VALUE

򐂰 TYPE_DOUBLE_ARRAY_VALUE

򐂰 TYPE_SHORT_ARRAY_VALUE

򐂰 TYPE_DOUBLE_VALUE

򐂰 TYPE_SHORT_VALUE

򐂰 TYPE_FLOAT_ARRAY_VALUE

򐂰 TYPE_STRING_ARRAY_VALUE

򐂰 TYPE_FLOAT_VALUE

򐂰 TYPE_STRING_VALUE

Regular extended data elements have a real type and one specific value associated to them. Embedded elements are of TYPE_NO_VALUE_VALUE type and contain one or many child extended data elements. This example has three embedded children elements.

Finally we complete and send the event. Then we end the correlation sphere

"myNewSphere" and close the emitter. Therefore, any new emitter created to start a new sphere has the parent sphere of null. If we do not close the sphere

"myNewSphere" and create a new emitter to send an event within a new sphere, then that event has the parent sphere of "myNewSphere".

Chapter 2. Common Event Infrastructure programming 127

The code shown in Example 2-5 on page 124 produces an event with the

properties and values listed in Table 2-8.

Table 2-8 Properties and values of complex event

Name Value version globalInstanceId

1.0.1

CEF29AB8FF0CB2B21625E3A0A0399711D

9

MyComplexEvent extensionName localInstanceId creationTime severity msg priority sequenceNumber repeatCount elapsedTime

ContextDataElement:

ECSCurrentID / contextValue

ContextDataElement:

ECSParentID / contextValue

ExtendedDataElement:

MyRegularExtendedDataEle ment

ExtendedDataElement:

MyEmbeddedExtendedData

Element / Child1

ExtendedDataElement:

MyEmbeddedExtendedData

Element / Child2

ExtendedDataElement:

MyEmbeddedExtendedData

Element / Child3

-

2004-11-18T19:22:12.266Z

MyMessage

10

1

0

0 myNewSphere

ExtendedDataValue

MyChild1

2

3.33

128 Using the WebSphere Business Integration Server Foundation Programming APIs

Name reporterComponentId sourceComponentId / component sourceComponentId / subComponent sourceComponentId / componentIdType sourceComponentId / instanceId sourceComponentId / application sourceComponentId / executionEnvironment sourceComponentId / location sourceComponentId / locationType sourceComponentId / processId sourceComponentId / threadId sourceComponentId / componentType msgDataElement situation / categoryName situation / situationType / reasoningScope situation / ReportSituation / reportCategory

Value

WBI-SF

J2EE_Application

ProductName localhost\localhost\server1

EventTester

Windows 2000[x86]#5.0

ka0lcxl/9.42.171.100

Hostname

1760

Servlet.Engine.Transports : 2 http://www.ibm.com/namespaces/autonomic/

WebSphereApplicationServer

ReportSituation

INTERNAL

STATUS

Emitter API

In this section we try to understand the methods of Emitter interface.

1.

synchronizationMode

- set and get methods of synchronization mode manage the mode of events. Valid values are:

Chapter 2. Common Event Infrastructure programming 129

2.

– SynchronizationMode.SYNCHRONOUS to send events to the event bus synchronously.

– SynchronizationMode.ASYNCHRONOUS to send events to the event bus asynchronously.

– SynchronizationMode.DEFAULT to use the default setting in the emitter for sending events.

isSynchronizationModeSupported(int ..)

checks if a desired synchronization mode is supported by this emitter.

transactionMode

- The transaction mode specifies whether to send an event to the event bus in the same transaction as the caller or in a new transaction.

There is a corresponding get method. Valid values are:

– TransactionMode.SAME to use the same transaction as the caller.

– TransactionMode.NEW to use a new transaction.

– TransactionMode.DEFAULT to use the default setting in the emitter.

Please refer to the Hyades javadocs for more information about CBE API: http://dev.eclipse.org/viewcvs/indextools.cgi/~checkout~/hyades-home/docs/c omponents/common_base_event/cbe101/overview-summary.html

2.4 Event monitoring

The events that we send to the event server are monitored in different ways. You can view events through some of the available tools, or we can write custom applications, called event consumers, to access complete event information.

2.4.1 Viewing events

The best way to view and test the events is to use the CBE event browser; however, the viewer is limited. If you cannot find all of the information that you are looking for in the CBE event browser, check the event tables. If you useCloudscape, cview is an easy way to view the tables. However, if you use

DB2, then view the event tables using the DB2 Command Center.

CBE event browser

The CBE event browser application comes with WebSphere Studio Application

Developer Integration Edition V5.1.1. It allows the user to view the events that are in the event database.

To run the application on the unit test environment:

1. Go to the server view.

2. Select the server that you configured for CEI.

130 Using the WebSphere Business Integration Server Foundation Programming APIs

3. Right-click the server.

4. Select Launch CBE Event Browser as shown in Figure 2-5 on page 131.

Figure 2-5 Starting the CBE event browser in WebSphere Studio Application Developer Integration Edition

You can also start the CBE event browser using the following Web address: http://<hostname>:9080/cbeviewer

The CBE event browser appears as shown in Figure 2-6 on page 132.

Chapter 2. Common Event Infrastructure programming 131

Figure 2-6 CBE event browser

In the CBE event browser you can select different filtering criteria such as:

򐂰 Data/Time range of event generation.

򐂰 Event group

򐂰 Event data source

򐂰 Server name

򐂰 Sub-component name

򐂰 Priority (range)

򐂰 Severity (range)

132 Using the WebSphere Business Integration Server Foundation Programming APIs

5. Once you set the criteria, click Get data . You can see the number of records matching your criteria.

6. To see the event records, select All. You can see the list of events. Selecting an event from the list displays the property and values of the selected event

as shown in Figure 2-7.

Figure 2-7 Event view on CBE event browser

Chapter 2. Common Event Infrastructure programming 133

Using CView and the DB2 Command Center

To view your database tables you can use CView or the DB2 Command Center depending on your database type (Cloudscape or DB2 respectively). The event database contains sixteen different tables.

򐂰 The CEI_T_CBE_MAP table contains a listing of all of the CBE properties and what tables in which they can be found.

򐂰 The CEI_T_EVENT table contains all of the simple or top-level property data of a CBE.

򐂰 The extended data element information is located in the

CEI_T_EXT_ELEMENT table.

The values of the extended data can be found in the following:

CEI_T_EXT_BLOB, CEI_T_EXDATETIME, CEI_T_EXT_FLOAT,

CEI_T_EXT_INTEGER, and CEI_T_EXT_STRING.

򐂰 Component Identification is found in the CEI_T_COMPID table.

򐂰 The CEI_T_CONTEXT table contains the Emitter Correlation Sphere (ECS) information.

򐂰 The situation data is located in the CEI_T_SITUATION table.

򐂰 The CEI_T_ASSOC_ENG table contains the association engine information.

򐂰 The associated events are located in the CEI_T_EVENT_RELN table.

In order to use CView, stop your server. On windows, to bring up CView, run:

<WAS_HOME>\cloudscape\bin\embedded\cview.bat.

To view the CEI tables load <WAS_HOME>\event\CloudScapeEventDB\event into CView.

On windows, to bring up the DB2 Command Center run the following batch file: <DB2_INSTALL_DIR>\SQLLIB\bin\db2cmdctr.bat.

2.4.2 Event consumer

An event consumer is any application that receives events from the event server.

This might be an application that receives asynchronous event notifications, or it might be an application that queries and processes historical event data from the persistent data store. The event consumer receives events in the form of Java objects. It can then use the CommonBaseEvent interface to retrieve event property data, or convert the event to another supported format (such as XML) for forwarding to another application.

134 Using the WebSphere Business Integration Server Foundation Programming APIs

An event consumer can receive events in either of two ways:

򐂰 It can use the Java Message Service(JMS) interface to subscribe to a queue or topic, receiving events asynchronously as JMS messages. This is the most efficient approach for an event consumer that needs to receive current events as they arrive at the event server.

򐂰 It can use the event access interface to query historical events from the persistent data store, retrieving the requested events synchronously. This is useful for startup processing. By querying the data store for historical events, an event consumer can determine current state information before beginning to receive new events through JMS.

In addition to receiving events, an event consumer can also purge old events from the data store.

Events from a Java Message Service (JMS) interface

Using the JMS interface, you can develop event consumers that receive events asynchronously from JMS queues or topics. An event consumer can be implemented as a standard Java class or as a Message Driven Bean(MDB).

By using the JMS interface, you can implement your event consumer using standard Java tools and programming models, and you can avoid the performance disadvantages of directly querying the event data store. Instead of interacting with the Common Event Infrastructure directly, your event consumer subscribes to JMS destinations (queues and topics) and receives events in the form of JMS messages.

The Common Event Infrastructure organizes events in event groups, which are logical collections of events defined in the Common Event Infrastructure configuration. A particular event consumer typically needs to receive only events from specific event groups.

The configuration profile for each event group associates that event group with one or more JMS destinations through which notifications related to that event group are distributed. The relationships between event groups and JMS destinations are as follows:

򐂰 An event group can be associated with multiple queues.

򐂰 An event group can be associated with only one topic. (Multiple event consumers can subscribe to the same topic, so publishing the same event group to more than one topic is redundant.)

򐂰 A JMS destination (queue or topic) should typically be associated with only one event group.

Chapter 2. Common Event Infrastructure programming 135

To receive messages from an event group, a JMS consumer subscribes to the appropriate destination. Each event is then delivered in the form of a JMS message containing an event notification. This notification is then converted into a CommonBaseEvent instance.

In addition to the standard JMS interfaces, a JMS event consumer interacts with a facility called the notification helper. The notification helper translates between

Common Event Infrastructure entities (events and event groups) and equivalent

JMS entities (messages and destinations). The notification helper provides the following functions:

򐂰 It can identify the JMS topic or queues associated with a specified event group. Your event consumer can then use the appropriate destination to create subscriptions.

򐂰 It can convert a JMS message notification into an instance of

CommonBaseEvent.

򐂰 It can provide filtering of events at the consumer. Each Notification Helper is associated with an event selector specifying which events are returned to consumers. When a consumer uses the Notification Helper to convert an event notification into an event instance, the event instance is returned only if it matches the specified event selector.

Message Driven Bean consumer

A J2EE event consumer is implemented as a Message Driven Bean, which is associated with a JMS destination and connection factory at deployment time. To receive events, follow these steps:

1. Obtain a notification helper. A JMS event consumer uses a notification helper to identify JMS destinations associated with an event group, to convert received JMS messages into CommonBaseEvent instances, and to perform filtering of received events. To obtain a notification helper, use a notification helper factory, which is an instance of NotificationHelperFactory that was

bound into a JNDI namespace. The Example 2-6 code snippet uses a

notification helper factory to obtain a notification helper.

Example 2-6 Obtain a notification helper

// Get notification helper factory from JNDI

InitialContext context = new InitialContext();

Object notificationHelperFactoryObject=context.lookup

("com/ibm/events/NotificationHelperFactory");

NotificationHelperFactory nhFactory = (NotificationHelperFactory)

PortableRemoteObject.narrow(notificationHelperFactoryObject,

NotificationHelperFactory.class);

// Create notification helper

NotificationHelper notificationHelper = nhFactory.getNotificationHelper();

136 Using the WebSphere Business Integration Server Foundation Programming APIs

2. Optional: Specify the event selector. If you want to filter received events, use the setEventSelector() method to set an event selector on the notification helper. Your event consumer can then use the notification helper to check received events against the event selector. The following code snippet sets an event selector specifying events with severity greater than 30 (warning).

notificationHelper.setEventSelector("CommonBaseEvent[@severity > 30]");

3. Convert received messages into CommonBaseEvent instances. In the onMessage() method of your listener, use the notification helper to convert each received JMS message into an event represented by an instance of

CommonBaseEvent. To do this, use the getCreatedEvent(Message) method of NotificationHelper. Each message received by an event consumer has a property called the notification type. This is an integer whose value is one of the notification type constants defined by the NotificationHelper interface.

Currently, the only supported notification type is

CREATE_EVENT_NOTIFICATION_TYPE, which indicates a notification of a new event. However, additional notification types might be added in future releases, so an event consumer should generally check this field using the

NotificationHelper.getNotificationType method before processing received notifications. public void onMessage(Message msg) { int msgType = notificationHelper.getNotificationType(msg); if(msgType == NotificationHelper.CREATE_EVENT_NOTIFICATION_TYPE) {

CommonBaseEvent event = notificationHelper.getCreatedEvent(msg);

...

}

If the received event does not match the event selector specified on the notification helper, the returned value is null.

4. Process the event. Your consumer can then process the event as appropriate. if (event != null) {

// Process the event

.....

}

In its deployment descriptor, associate a Message Driven Bean with a listener port that specifies a JMS destination and connection factory. You must create a listener port for your event consumer before deploying the MDB, which specifies the destination and connection factory associated with the event

Chapter 2. Common Event Infrastructure programming 137

group from which you want to receive events. See “Configuring for working with Message Driven Bean event consumer” on page 209.

Note: Do not use the CommonEventInfrastructure_ListenerPort listener port when deploying your MDB. The event server uses this listener port and is not intended for use by event consumers.

See “Using JMS interface” on page 162 for the example.

Non-MDB consumer

To write an event consumer that is not aMessage Driven Bean, follow these steps:

1. Obtain a notification helper. A JMS event consumer uses a notification helper to identify JMS destinations associated with an event group, to convert received JMS messages into CommonBaseEvent instances, and to perform filtering of received events.

To obtain a notification helper, use a notification helper factory, which is an instance of NotificationHelperFactory that was bound into a JNDI namespace.

The Example 2-7 code snippet uses a notification helper factory to obtain a

notification helper.

Example 2-7 Obtain a notification helper

// Get notification helper factory from JNDI

InitialContext context = new InitialContext();

Object notificationHelperFactoryObject =context.

lookup("com/ibm/events/NotificationHelperFactory");

NotificationHelperFactory nhFactory = (NotificationHelperFactory)

PortableRemoteObject.narrow(notificationHelperFactoryObject,

NotificationHelperFactory.class);

// Create notification helper

NotificationHelper notificationHelper = nhFactory.getNotificationHelper();

2. Optional: Specify the event selector. If you want to filter received events, use the setEventSelector() method to set an event selector on the notification helper. If you specify an event selector, the notification helper returns only events that match the event selector. The following code fragment sets an event selector specifying events with severity greater than 30 (warning).

notificationHelper.setEventSelector("CommonBaseEvent[@severity > 30]");

138 Using the WebSphere Business Integration Server Foundation Programming APIs

3. Use the notification helper to find the JMS destination to which to subscribe.

You can associate each event group with a single JMS topic and any number of JMS queues. Query the notification helper to obtain what destinations are associated with a particular event group.

To find the topic associated with an event group, use the getJmsTopic(String) method of NotificationHelper, which specifies the name of the event group:

MessagePort msgPort = notificationHelper.getJmsTopic("critical_events");

To find the queues associated with an event group, use the getJmsQueues(String) method:

MessagePort[] msgPorts =notificationHelper.

getJmsQueues("critical_events");

The returned object is either a single MessagePort object representing a JMS topic or an array of MessagePort objects representing JMS queues. A

MessagePort instance is a wrapper object containing the JNDI names of the destination and its connection factory.

4. Connect to the destination. Use the getter methods of MessagePort to retrieve the JNDI names of the destination and connection factory. You can then use the standard JMS interfaces to connect to the destination. The

Example 2-8 code snippet subscribes to a JMS topic:

Example 2-8 Connect to the destination

String connectionFactoryName = msgPort.getConnectionFactoryJndiName(); String destinationName = msgPort.getDestinationJndiName();

// create connection and session

ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryName);

Connection connection = connectionFactory.createConnection();

Session session = connection.createSesion(false, CLIENT_ACKNOWLEDGE);

// Create consumer and register listener

Topic topic = (Topic) context.lookup(destinationName);

MessageConsumer consumer = session.createConsumer(topic); consumer.setMessageListener(this); connection.start();

5. Convert received event notification messages into CommonBaseEvent instances. In the onMessage() method of your listener, you can use the notification helper to convert each received JMS message into an event represented by an instance of CommonBaseEvent. To do this, use the getCreatedEvent(Message) method of NotificationHelper.

Chapter 2. Common Event Infrastructure programming 139

Each message received by an event consumer has a property called the notification type. This is an integer whose value is one of the notification type constants defined by the NotificationHelper interface. Currently, the only supported notification type is CREATE_EVENT_NOTIFICATION_TYPE, which indicates a notification of a new event. However, additional notification types might be added in future releases, so an event consumer should generally check this field using the NotificationHelper.getNotification type

method before processing received notifications. See Example 2-9.

Example 2-9 Convert received event notification messages public void onMessage(Message msg) { int msgType = notificationHelper.getNotificationType(msg); if(msgType == NotificationHelper.CREATE_EVENT_NOTIFICATION_TYPE) {

CommonBaseEvent event = notificationHelper.getCreatedEvent(msg);

...

}

}

If the received event does not match the event selector specified on the notification helper, the returned value is null.

6. Process the event. Your consumer can then process the event as appropriate. if (event != null) {

// Process the event

.....

}

Retrieving events from an event data store

An event consumer can synchronously retrieve historical events from the persistent data store by querying the event server. You can query events in four ways:

򐂰 You can specify a global instance identifier to retrieve a specific single event.

򐂰 You can specify an event group and retrieve events associated with that event group. You can optionally refine the query further by specifying an additional event selector, retrieving only events that match both the event group and event selector.

򐂰 You can query the existence of events associated with a specified event group without retrieving the events.

򐂰 You can specify a known event and an association type, retrieving events that are associated with the known event.

140 Using the WebSphere Business Integration Server Foundation Programming APIs

To query the event server, use the event access interface. This is a J2EE stateless session bean whose interface provides methods for querying the event server. An event consumer uses an instance of the event access bean for all synchronous event queries.

The persistent data store is implemented as a separate component called a

data store plug-in

. The Common Event Infrastructure includes a default data store plug-in that supports event queries based on a subset of XPath syntax. If you want to use a different data store, you can implement your own data store plug-in.

Creating an event access bean

The event access interface is implemented as a stateless session bean using the

Enterprise JavaBeans architecture. To query the event server using the event access interface, an event source must first create an instance of the event access session bean. The event access bean can be either local or remote. To create an instance of the event access session bean, use the appropriate home interface (either EventAccessHome or EventAccessLocalHome). See

Example 2-10.

Example 2-10 Creating an event access bean

// use home interface to create remote event access bean

InitialContext context = new InitialContext();

Object eventAccessHomeObj = context.

lookup("ejb/com/ibm/events/access/EventAccess");

EventAccessHome eventAccessHome = (EventAccessHome)

PortableRemoteObject.narrow(eventAccessHomeObj, EventAccessHome.class); eventAccess = (EventAccess) eventAccessHome.create();

Using the global instance identifier

The Common Base Event specification defines an event property called globalInstanceId that you can use as a primary key for event identification. The content of this property is a globally unique identifier, generated either by the application or by the emitter. Although the Common Base Event specification defines the globalInstanceId property as optional, the event emitter automatically assigns an identifier to any event that does not already have one.

You can retrieve a specific single event from the event server by querying with the globalInstanceId property of the event you want to retrieve. This is useful for testing purposes (to confirm that events are being stored in the event database), or for retrieving an event associated with one that was received previously.

Chapter 2. Common Event Infrastructure programming 141

To query an event by global instance identifier, use the queryEventByGlobalInstanceId() method of the event access bean.

1. If necessary, create an event access bean.

2. Call the queryEventByGlobalInstanceId(String) method of the EventAccess bean, specifying the global instance identifier of the event you want to retrieve.

CommonBaseEvent event = eventAccess.queryEventByGlobalInstanceId(eventId);

The returned object is the event with the specified global instance identifier. If there is no matching event in the persistent data store, the returned object is null.

Using the event group

An event is associated with one or more event groups. An event group is a logical grouping of events that match a particular event selector. Event groups are defined in the event infrastructure configuration. For more information about

event groups, see “Event groups” on page 110.

Use the event access interface to retrieve events that belong to a specified event group. You can further restrict the query results by specifying an additional event selector.

The event access interface provides two methods for querying by event group.

The first method returns a limited number of events, while the other returns all events belonging to the specified event group (which might be a large number of events).

CommonBaseEvent[] events = eventAccess.queryEventsByEventGroup(eventGroup, eventSelector, ascendingOrder, maxEvents);

CommonBaseEvent[] events = eventAccess.queryEventsByEventGroup(eventGroup, eventSelector, ascendingOrder);

The parameters of these methods are as follows:

򐂰

eventGroup

򐂰

A string containing the name of the event group from which you want to query events. This must be the name of an existing event group defined in the event infrastructure configuration.

eventSelector

A string containing an optional event selector that further refines the query.

The query returns only events that match both the specified event group and the additional event selector. An event selector is specified in the form of an

XPath expression. For more information, see “Writing event selectors” on

142 Using the WebSphere Business Integration Server Foundation Programming APIs

򐂰

򐂰

page 145. If you do not want to specify an additional event selector, this

parameter can be null.

ascendingOrder

A boolean value specifying whether the returned events are to be sorted in ascending or descending order according to the value of the creationTime property. If this parameter is true, the events are sorted in ascending

(chronological) order. If it is false, they are sorted in descending (reverse chronological) order.

maxEvents

An integer specifying the maximum number of events you want returned.

The returned object is an array containing the events from the specified event group.

Note: If the number of matching events exceeds the query threshold defined in the data store profile, a QueryThresholdExceededException exception is thrown. The default query threshold is 100 000.

The Example 2-11 code fragment returns all events that belong to an event group

called critical_hosts and whose severity is greater than 30 (warning), but specifies that no more than 5000 matching events are returned:

Example 2-11 Events in an event group

CommonBaseEvent[] events = eventAccess.queryByEventGroup(

"critical_hosts",

"CommonBaseEvent[@severity > 30]", true,

5000);

Querying the existence of events in an event group

In some situations, you might want to find out whether any events exist in a particular event group without actually retrieving the events. To do this, use the eventExists() method of the event access bean.

boolean hasEvents = eventAccess.eventExists(eventGroup, eventSelector);

The parameters of this method are as described in “Using the event group” on page 142.

The returned boolean object equals true if any events exist that match the specified event group and event selector. It is false if none exist.

Chapter 2. Common Event Infrastructure programming 143

The Example 2-12 code snippet checks for the existence of any events in an

event group called critical_hosts and retrieves any that exist.

Example 2-12 Retrieving events in an event group if (eventAccess.eventExists("critical_hosts",null)) {

CommonBaseEvent[] events = eventAccess.queryByEventGroup(

"critical_hosts", null, true);

}

Querying events by association type

The Common Base Event specification defines properties that establish relationships between events. The associatedEvents property is a complex element containing one or more sub-elements of the AssociatedEvent type, each representing an associated event. Each AssociatedEvent element, in turn, contains subelements identifying the type of association and the application that established the association. Examples of association types might include

CausedBy or Correlated.

By specifying the global instance identifier of a known event and a type of association, you can retrieve events that satisfy the specified association. To query events by association type, use the

EventAccess.queryEventsByAssocation(String, String) method.

CommonBaseEvent[] events = eventAccess.queryEventsByAssocation

(associationType, eventId);

The parameters of this method are as follows:

򐂰

associationType

򐂰

The type of association. This is the name of an association type specified by the associationEngineInfo property.

eventId

The global instance identifier of a known event.

The returned object is an array containing the events that satisfy the specified type of association with the known event. Only events that are still in the event database at the time of the query are returned (an associated event might be purged from the database).

The Example 2-13 on page 145 code snippet returns all events from the event

database that have a CausedBy association with a known event:

144 Using the WebSphere Business Integration Server Foundation Programming APIs

Example 2-13 Querying events by association type

String eventId = causeEvent.getGlobalInstanceId();

CommonBaseEvent[] resultEvents = eventAccess.

queryEventsByAssociation("CausedBy", eventId);

See “Using the event access interface” on page 162 for example.

Purging events from the data store

An event consumer or administrative tool can purge events from the data store using the event access interface. You can purge all events from the data store, or you can limit the purge by specifying event groups, event selectors, or both. To purge events from the data store, use the purgeEvents() method of the event access bean. int purged = eventAccess.purgeEvents(eventGroup, eventSelector, transactionSize);

The parameters are as follows:

򐂰

򐂰

eventGroup

and

eventSelector

are explained in “Using the event group” on page 142.

transactionSize

A nonzero integer specifying the number of events you want purged in a single database transaction. In most cases, you can use the constant

DEFAULT_PURGE_TRANSACTION_SIZE that the EventAccess interface defines.

The purgeEvents() method purges all of the events that match all of the criteria you specify. If the eventGroup and eventSelector parameters are both null, all events in the data store are purged. Events that arrive after the purge operation starts are not purged. The returned value is an integer specifying

how many events were purged. See the example in appendix “Purging events sample code” on page 163.

Note: If the value of the transactionSize parameter exceeds the maximum purge transaction size defined in the data store profile, a

PurgeThresholdExceededException exception is thrown and no events are purged. The default maximum purge transaction size is 100 000.

Writing event selectors

An event selector is a regular expression that defines a set of events based on their property data (attributes or subelements). For example, an event selector might specify all events from a particular host whose severity is greater than 30

Chapter 2. Common Event Infrastructure programming 145

(warning). Event selectors define event groups, specify filter criteria, and query the event server.

Because the Common Base Event specification is based on XML, event selectors are written using a subset of the XPath syntax. The specific syntax you can use for an event selector depends on how the event selector is to be used,

as summarized by Table 2-9.

Table 2-9 Event selector

Event selector purpose

Event group definition

Event query and purge through event access interface

Emitter filter configuration

Subscription through Notification

Helper interface

Syntax

Limited to XPath subset supported by default data store plug-in

Limited to XPath subset supported by default data store plug-in

Any valid XPath

Any valid XPath

Note: The default data store plug-in uses a subset of XPath syntax. However, if you are using a different data store plug-in, it might support a different subset of XPath. The event selectors you write for event group definitions and for the event access interface must use the syntax that your data store plug-in supports.

Writing XPath event selectors

XPath is a standard language that identifies parts of an XML document. For more information, see the XPath specification at the following Web address: http://www.w3.org/TR/xpath .

A simple XPath event selector that specifies an attribute value takes the following form:

򐂰 CommonBaseEvent [@attribute = value]

The value can be either a numeric value or a string enclosed in single or double quotation marks.

You can also specify an attribute of a sub-element:

– CommonBaseEvent[/subelement/@attribute = value]

146 Using the WebSphere Business Integration Server Foundation Programming APIs

When using XPath operators, keep the following general rules in mind:

򐂰 When used to compare XML dateTime values, the comparison operators perform logical comparisons that recognize time zone differences.

򐂰 Logical operators and function names must be specified using all lowercase letters (for example, and rather than AND).

򐂰 Operators must be separated with white space from the surrounding attribute names and values (@severity > 30 rather than @severity>30).

򐂰 Parentheses can be used to change operator precedence.

The examples in Table 2-10 are valid XPath event selectors.

Table 2-10 Valid XPath event selectors

XPath event selector

CommonBaseEvent[@extensionName =

’ApplicationStarted’]

Description

All events with the extensionName attribute ApplicationStarted

CommonBaseEvent[sourceComponentId/

@location = "server1"]

All events containing a sourceComponentId element with the location attribute server1

CommonBaseEvent[@severity]

CommonBaseEvent[@creationTime <

’2003-12-10T12:00:00-05:00’ and

@severity > 30]

All events with a severity attribute, regardless of its value

All events created before noon EST on 10

December 2003 and with severity greater than 30 (warning)

CommonBaseEvent[contains(@msg,

’disk full’)]

CommonBaseEvent[(@severity = 30 or

@severity = 50) and @priority = 100]

All events with the phrase disk full occurring within the msg attribute

All events whose severity attribute is equal to 30 or 50, and whose priority is equal to

100.

You can write event selectors for the default data store plug-in. If your event selector might be used to define an event group or to query the persistent data store, it is subject to the restrictions of the default data store plug-in. These restrictions are as follows:

򐂰 An event property can be specified only on the left side of an operator or

XPath function. The value on the right side of an operator must be a literal value. The following example is not a valid event selector:

CommonBaseEvent[30 < @priority and contains(’this message’, @msg)]

Instead, this could be rewritten as follows:

CommonBaseEvent[@priority > 30 and contains(@msg, ’this message’)]

Chapter 2. Common Event Infrastructure programming 147

򐂰 Only the following XPath functions are supported:

– contains

– starts-with

– false

– true

– not

򐂰 The union operator (|) is not supported.

򐂰 An event selector must take the following form:

– CommonBaseEvent[predicate_expression]

Only a single predicate expression can be associated with the

CommonBaseEvent element. Stacked predicates are not supported. For example:

CommonBaseEvent[@extensionName = "server_down"][@severity = 10]).

򐂰 A predicate can be only be associated with the last step of a location path.

The following example is not a valid event selector:

CommonBaseEvent[contextDataElement[@contextValue = "myContextValue"]

/@contextId = "myContextId"]

Instead, this could be rewritten as follows:

CommonBaseEvent[contextDataElement[@contextValue = "myContextValue" and

@contextId = "myContextId"]]

򐂰 If an event selector refers to properties of extended data elements that are at different levels of the XML containment hierarchy, these elements must be grouped together by level. The following example is not a valid event selector, because the references to the

type

and

value

attributes (both top-level) of

extendedDataElements

are separated:

CommonBaseEvent[extendedDataElements[@type = ’int’ and children/@type =

’intArray’ and children/@name = ’myName’ and @value = 10]]

Instead, this could be rewritten as follows, grouping the top-level and second-level attributes together:

CommonBaseEvent[extendedDataElements[@type = ’int’ and @value = 10 and children/@type = ’intArray’ and children/@type = ’myName’]]

򐂰 Node indexes are not supported, for example,

CommonBaseEvent[extendedDataElements[1]]).

򐂰 Wildcard characters are not supported, for example,

CommonBaseEvent[extendedDataElements/*/children/values = "text"]).

148 Using the WebSphere Business Integration Server Foundation Programming APIs

򐂰 When referring to the values property of an extended data element, you must specify not only the value but also the type of the property:

CommonBaseEvent[extendedDataElements[values = "myVal" and @type =

"string"]]

You can specify the type for multiple comparisons within a compound expression by grouping them with parentheses:

CommonBaseEvent[extendedDataElements[(values = "myVal" or values =

"yourVal") and @type = "string"]]

In this example, the type expression applies to both parts of the compound expression in parentheses. You cannot override this by specifying a different type expression inside the parentheses. You can also group together multiple related types by using the starts-with or contains functions. The following expression, for example, matches a property with either the string or stringArray type:

CommonBaseEvent[extendedDataElements[values = "myVal" and startsWith(@type,

’string’)]]

Implementing a data store plug-in

To use your own data store for persistent storage of events, implement a custom data store plug-in by following these steps:

1. Develop your data store plug-in as an enterprise bean with the provided local interface. Your data store plug-in must implement the interface com.ibm.events.datastore.DataStoreLocal. The DataStoreLocal interface defines the following methods (refer to the Javadoc API documentation for complete information):

– createEvent(CommonBaseEvent)

Stores a new event in the data store

– eventExists(String)

Returns a boolean indicating whether any events currently in the data store match the specified event selector

– purgeEvents(String, long, int)

Deletes events matching an event selector

– queryEventByGlobalInstanceId(String)

Returns the event whose global instance identifier matches the specified value (or null if no matching event is found)

– queryEvents(String, boolean)

Returns an array of events that match the specified event selector

Chapter 2. Common Event Infrastructure programming 149

– queryEvents(String, boolean, int)

Returns an array of events that match the specified event selector, limiting the array to the specified size

– queryEventsByAssociation(String, String)

Returns an array of events that satisfy the specified relationship to a known event

– getMetaData()

Returns metadata describing the data store plug-in, including the version of the Common Base Event specification it supports

A data store plug-in must also satisfy the following requirements:

– It must use XPath syntax, or a subset of XPath syntax, for specifying event selectors.

– It must store all of the data associated with each received event.

– Its query methods must return event objects that are identical to those originally stored.

2. Deploy your data store plug-in in WebSphere Application Server. See the

WebSphere Application Server documentation for more information about how to deploy an application.

3. In the WebSphere Administrative Console, modify the default event server profile. In the Data Store JNDI Name field, specify the JNDI name of your data store plug-in. For more information about the event server profile, see the online help for the WebSphere Administrative Console.

When you start the Common Event Infrastructure server, the event server uses the specified JNDI name to access the local home interface of the data store enterprise bean. It then uses the local home interface to create an instance of the data store plug-in bean.

Retrieve data from received event

When an event source receives an event, it can then use the getter methods of

CommonBaseEvent to retrieve the event property data. For example, the following code fragment retrieves a single event and then reads the content of the msg property.

CommonBaseEvent event = eventAccess.queryEventByGlobalInstanceId(eventId);

String eventMessage = event.getMsg();

If the property you want to retrieve is a complex property (a sub-element of

CommonBaseEvent in the Common Base Event specification), the returned value is an instance of the specialized class representing the complex data type.

You can then use the getter methods of the returned object to retrieve the

150 Using the WebSphere Business Integration Server Foundation Programming APIs

property data from that object. For example, the following code fragment retrieves the value of componentId, which is a complex property. It then retrieves the content of the nested component property, which is a string, to read the name of the source component.

CommonBaseEvent event = eventAccess.queryEventByGlobalInstanceId(eventId);

ComponentIdentification componentId = event.getSourceComponentId();

String componentName = componentId.getComponent();

Converting XML events

In addition to creating new events, an event source might convert events received from other applications in XML format. Similarly, an event consumer might convert events to XML format for forwarding to another application. The org.eclipse.hyades.logging.events.cbe.util.EventFormatter class provides methods you can use to convert between CommonBaseEvent instances and

XML.

Using EventFormatter, you can convert an instance of CommonBaseEvent into a string containing either an XML document or an XML fragment. Similarly, you can convert from an XML document or fragment into an instance of

CommonBaseEvent.

Here are some useful methods of EventFormatter:

򐂰 Static CommonBaseEvent eventFromCanonicalXML(String xmlString)

򐂰 Static CommonBaseEvent[] eventsFromCanonicalXML(java.io.File file)

򐂰 Static CommonBaseEvent[] eventsFromCanonicalXML(java.xml.sax.InputStream inputStream)

򐂰 Static CommonBaseEvent[] eventsFromCanonicalXML(java.io.InputStream inputStream)

򐂰 Static CommonBaseEvent[] eventsFromCanonicalXML(String xmlDocString)

򐂰 Static String toCaninicalXMLDocString(CommonBaseEvent cbe)

򐂰 Static String toCaninicalXMLDocString(CommonBaseEvent[] cbe)

򐂰 Static String toCaninicalXMLDocString(CommonBaseEvent[] cbe, boolean format)

򐂰 Static String toCaninicalXMLString(CommonBaseEvent cbe)

򐂰 Static String toCaninicalXMLString(CommonBaseEvent cbe, boolean format)

For more information about EventFormatter, refer to the Ê on page 223 Javadoc

documentation in the org.eclipse.hyades.logging.events.cbe.util package.

Chapter 2. Common Event Infrastructure programming 151

Accessing event instance metadata

The org.eclipse.hyades.logging.events.cbe package that provides the classes and interfaces required for working with event objects, is based on the Eclipse

Modeling Framework (EMF). EMF is a Java framework that generates application code based on a structured data model. It also provides interfaces in the generated code used to access metadata describing the data model. (Refer to the Eclipse Modeling Framework documentation at http://www.eclipse.org/emf for more information about EMF.)

By using these interfaces, EMF-compatible tools can interact with Common Base

Event event data without any prior knowledge of the data model or access to the implementation. This makes it possible for development tools to generate code that transfers data from other data models into the Common Base Event model.

Application developers can then focus on writing code that uses the data rather than code that builds the data.

For example, consider an event source that monitors network events and describes its own data model in terms of EMF. With access to both data models, a development tool can display the fields of the event source data model alongside the fields of the Common Base Event data model. A developer can then use a graphical interface to indicate how the fields in the event source model are mapped to fields in the Common Base Event model, for example, a field called Workstation.name in the event source data model might correspond to the CommonBaseEvent.sourceComponentId.location field in the Common

Base Event data model. Because both data models are described using standard EMF interfaces, the tool can generate code that handles the transfer of data between the two models.

The Example 2-14 code snippet is a simple example of how a development tool

might use EMF interfaces to query information about the Common Base Event data model, and then use that information to interact with an event instance. This example is part of a simple event consumer. It iterates through all of the fields of an event instance and, for each one, prints the name and value of the field.

Example 2-14 EMF interfaces to query information about the Common Base Event

// event is a valid CommonBaseEvent instance

// Get list of event instance structural features (fields)

List features = event.eClass().getEAllStructuralFeatures();

// iterate through list; print names and values for (int i = 0 ; i < features.size() ; i++) {

EStructuralFeature feature = (EStructuralFeature)features.get(i);

Object value = eObj.eGet(feature);

152 Using the WebSphere Business Integration Server Foundation Programming APIs

}

System.out.println(feature.getName() + ":" + value);

The CommonBaseEvent data model is described in the EMF files cbe.ecore and cbe.genmodel. These files are included with the Common Event Infrastructure

SDK. You can import them into an Eclipse-based development environment, and then use EMF to generate code that interacts with CommonBaseEvent objects.

WebSphere Business Integration Monitor

WebSphere Business Integration Monitor focuses on enabling the ability to make event consumption easier and faster. Non-technical individuals for instance, sales managers, need the ability to consume event data in a reasonable amount of time. These people may not have the skills or the time to use the event viewer application. This is where WebSphere Business Integration Monitor closes the gap between CBE database entries and useful business information.

While emitting and persisting events through the Common Event Infrastructure is important, the value of the CEI becomes real when we can actually consume and process the events. WebSphere Business Integration Monitor is an example of a product that leverages CEI to receive events, and then provides added value to correlate and aggregate event information and enable business users to track, monitor, and take actions to ultimately improve the performance of the organization.

The user concepts in WebSphere Business Integration Monitor are simple:

1. What area of the business is being monitored (context)?

2. From my goals, what are the measurements of performance, with targets and thresholds (key performance indicators)?

3. What are conditions or anomalies that I want to detect, so I can respond when they occur (situations), and what are those responses (actions)?

4. What are the business milestones from my operational systems, processes and applications that I want to observe (events)?

5. How can I visualize and analyze key performance indicators and see trends with tables, charts and graphs in the portal in a manner specific to my role

(dashboards)?

WebSphere Business Integration Monitor interacts with the CEI in three ways:

1. First, in the role of an event subscriber, WebSphere Business Integration

Monitor uses the CEI notification helper to subscribe to a set of event groups

(as defined by the administrator). As events are published to the event bus,

WebSphere Business Integration Monitor receives them and then uses event correlation techniques to associate information from events coming from

Chapter 2. Common Event Infrastructure programming 153

multiple sources for the purpose of calculating key performance indicators and detecting business situations.

2. Second, as an event source, WebSphere Business Integration Monitor emits events when business situations are detected. WebSphere Business

Integration Monitor populates the CEI event catalog with the situation event definitions. Other event consumers can subscribe to these situation events via CEI and respond in appropriate ways. Note that WebSphere Business

Integration Monitor provides basic 'out of the box' actions including the ability to notify a person or start a workflow process.

3. Finally, when WebSphere Business Integration Monitor needs to access historical events, WebSphere Business Integration Monitor can query the CEI event data store for events that it has yet to process.

WebSphere Business Integration Monitor provides a tool that is used both by a business analyst to describe what should be monitored, and also by a solution architect to specify how the monitoring is done. The architect selects events from the event catalog and creates the maps and expression definitions that WebSphere Business Integration Monitor uses to correlate the events, calculate key performance indicators, and detect situations.

2.5 Correlation

The CEI infrastructure provides the opportunity to correlate a series of events that match to a particular business activity.

Correlation is achieved easily in a BPEL process. We discuss how to achieve correlation programatically.

Since there are no written rules for how events are correlated, correlation is left to the CBE architect. Architects must decide what series of events constitutes a business activity. Correlation is thought of as a series of events that all relate and make up one larger event. We use a simple example to help demonstrate.

A servlet calculates something. There are some private methods M1, M2, M3, and M4 within the servlet. These methods represent important activities and all together make up our one calculation. To use correlation for this example, we need to have a root parent sphere to house all of our events. Then for each method, we open a new sphere.

One successful run of this servlet is as follows. A servlet session starts and runs method M1. Method M1 runs, emits "M1_event1" and "M1_event2", and finishes.

Then method M2 runs, emits "M2_event", and calls method M3. Method M3 emits "M3_event" and finishes. Method M2 then calls M4. M4 emits events

154 Using the WebSphere Business Integration Server Foundation Programming APIs

"M4_event1" and "M4_event2" and finishes. A servlet session is stopped.

Figure 2-8 illustrates how the event spheres look for this execution example.

Figure 2-8 Event correlation spheres.

To code this example, we need to start by creating a new sphere. The doGet() method creates this sphere and it becomes the root parent sphere of all of the servlet events within a session; therefore, we create the new sphere whenever a new session is started.

Lines 8-15 in Example 2-15 on page 156 detect a new session and create a new

root emitter if needed. The root emitter is associated with the session value

Chapter 2. Common Event Infrastructure programming 155

emitter

. A

servlet_session_started

event is emitted to show our new sphere started. After the event is sent, methods M1 and M2 are called.

Example 2-15 Event correlation sample

39

40

41

42

43

44

7

8

5

6

1 public class CorrelationServlet extends HttpServlet {

2

3 public void doGet(HttpServletRequest req, HttpServletResponse resp)

4 throws ServletException, IOException {

HttpSession session = req.getSession();

9

10

11

12 if (session.getValue("emitter") == null) {

// start root sphere

ECSEmitter rootEmitter = new ECSEmitter(

"com/ibm/events/configuration/emitter/Default",

System.currentTimeMillis() + "calculate");

13

14

15

16

} session.putValue("emitter", rootEmitter);

17

18

19

20

ECSEmitter emitter = (ECSEmitter) session.getValue("emitter");

// create CBE

CommonBaseEvent startEvent =

21 emitter.createCommonBaseEvent("servlet_session_started");

22

35

36

37

38

31

32

33

34

27

28

29

30

23

24 try {

InitialContext ctx = new InitialContext();

25 EventFactory eventFactory = (EventFactory)

26 ctx.lookup("com/ibm/websphere/events/factory");

// add situation to the event

Situation startSituation = eventFactory.createSituation(); startSituation.setStartSituation(

"INTERNAL", "SUCCESSFUL", "START COMPLETED"); startEvent.setSituation(startSituation); startEvent.complete(); emitter.sendEvent(startEvent);

M1();

M2();

} catch (NamingException e) { e.printStackTrace();

} catch (CompletionException e) { e.printStackTrace();

} catch (EventsException e) {

156 Using the WebSphere Business Integration Server Foundation Programming APIs

45

46

47 }

} e.printStackTrace();

We do not close the rootEmitter in the doGet method because it needs to remain

open as long as the session is active. Lines 52-55 of Example 2-16 create a new

sphere. Lines 57-65 emit two events, and line 67 ends the M1 correlation sphere.

Example 2-16 Event correlation sample part 2

64

65

66

67

68

69

70

60

61

62

63

56

57

58

59

48

49

50

51 private void M1() throws CompletionException, EventsException {

String M1ECSCurrentID = System.currentTimeMillis() + ":M1";

52

53

// start new sphere

ECSEmitter m1Emitter = new ECSEmitter(

54 "com/ibm/events/configuration/emitter/Default",

55 M1ECSCurrentID);

// create M1_event1

CommonBaseEvent event1=m1Emitter.createCommonBaseEvent("M1_event1"); event1.complete(); m1Emitter.sendEvent(event1);

// create M1_event2

CommonBaseEvent event2=m1Emitter.createCommonBaseEvent("M1_event2"); event2.complete(); m1Emitter.sendEvent(event2);

}

// end M1 emitter sphere m1Emitter.releaseAndEndECS(M1ECSCurrentID); m1Emitter.close();

Method M2 creates a new sphere, sends an event, and then calls M3 and M4.

Since the M2 sphere is open when we call M3 and M4, both the M3 and M4

spheres have a parent sphere of M2. See Example 2-17.

Example 2-17 Event correlation sample part 3

71

72

73 private void M2() throws CompletionException, EventsException {

String M2ECSCurrentID = System.currentTimeMillis() + ":M2";

74

75 // start new sphere

76 ECSEmitter m2Emitter = new ECSEmitter(

77 "com/ibm/events/configuration/emitter/Default",

78 M2ECSCurrentID);

Chapter 2. Common Event Infrastructure programming 157

86

87

88

89

90

91

79

80

81

82

83

84

85

// create M2_event

CommonBaseEvent event = m2Emitter.createCommonBaseEvent("M2_event"); event.complete(); m2Emitter.sendEvent(event);

M3();

M4();

}

// end M2 emitter sphere m2Emitter.releaseAndEndECS(M2ECSCurrentID); m2Emitter.close();

Methods M3 and M4 are very similar to method M2. See Example 2-18.

Example 2-18 Event correlation sample part 4

92

93

94

95 private void M3() throws CompletionException, EventsException {

String M3ECSCurrentID = System.currentTimeMillis() + ":M3";

96

97

// start new sphere

ECSEmitter m3Emitter = new ECSEmitter(

98 "com/ibm/events/configuration/emitter/Default",

99 M3ECSCurrentID);

100

101

102

103

104

105

106

107

// create M3_event

CommonBaseEvent event = m3Emitter.createCommonBaseEvent("M3_event"); event.complete(); m3Emitter.sendEvent(event);

108

109

110 }

111

// end M3 emitter sphere m3Emitter.close(); m3Emitter.releaseAndEndECS(M3ECSCurrentID); m3Emitter.close();

112 private void M4() throws CompletionException, EventsException {

113

114

115

String M4ECSCurrentID = System.currentTimeMillis() + ":M4";

116

117

// start new sphere

ECSEmitter m4Emitter = new ECSEmitter(

118 "com/ibm/events/configuration/emitter/Default",

119 M4ECSCurrentID);

120

121

122

// create M1_event1

CommonBaseEvent event1=m4Emitter.createCommonBaseEvent("M4_event1");

158 Using the WebSphere Business Integration Server Foundation Programming APIs

123

124

125

126

127

128

129

130

131

132

133

134 }

135 } event1.complete(); m4Emitter.sendEvent(event1);

// create M1_event2

CommonBaseEvent event2=m4Emitter.createCommonBaseEvent("M4_event2"); event2.complete(); m4Emitter.sendEvent(event2);

// end M4 emitter sphere m4Emitter.releaseAndEndECS(M4ECSCurrentID); m4Emitter.close();

The last event we emit is the

servelet_session_stopped

event to mark the stop of

our root sphere. This is shown in Example 2-19. This event closes our root

sphere and is located in a session listener class. This is because we only want to close the root sphere when a session ends. A session listener listens for the end of a session. For this event we set a stop situation (lines 20-24). Line 32 ends the root sphere for this session. Notice how you can get the sphere id from the emitter.

Example 2-19 Event correlation session listener

7

8

5

6

1 public class SessionListenerImpl implements ServletContextListener,

2 ServletContextAttributeListener, HttpSessionListener,

3 HttpSessionAttributeListener {

4 public void sessionDestroyed(HttpSessionEvent arg0) {

ECSEmitter emitter=(ECSEmitter)arg0.getSession().getValue("emitter"); if (emitter != null) {

13

14

15

16

9

10

11

12

// create CBE

CommonBaseEvent stopEvent = emitter.createCommonBaseEvent("servlet_destroyed");

17

18

19

20

// create event factory

InitialContext ctx; try { ctx = new InitialContext();

EventFactory eventFactory = (EventFactory) ctx.lookup(

"com/ibm/websphere/events/factory");

21

22

// create a stop situation

Situation stopSituation = eventFactory.createSituation(); stopSituation.setStopSituation("INTERNAL", "SUCCESSFUL",

24 stopEvent.setSituation(stopSituation);

Chapter 2. Common Event Infrastructure programming 159

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41 }

42 }

43 } stopEvent.complete(); emitter.sendEvent(stopEvent);

// end the root sphere emitter.close(); emitter.releaseAndEndECS(emitter.getCurrentEcsID());

} catch (NamingException e) { e.printStackTrace();

} catch (CompletionException e) { e.printStackTrace();

} catch (EventsException e) { e.printStackTrace();

}

In order for the session listener to work correctly the following must be in the

Web deployment descriptor:

<listener>

<listener-class>SessionListenerImpl</listener-class>

</listener>

Table 2-11 shows the events that the code in Example 2-19 on page 159

produces. Notice the sphere values for the ECSCurrentID and the ECSParentID.

Table 2-11 Correlation events

Creation Time Name

2004-10-06T21:4

3:24.866Z

2004-10-06T21:4

3:25.267Z

Servlet _session

_started

M1_event1

M1_event2 2004-10-06T21:4

3:25.347Z

2004-10-06T21:4

3:25.477Z

2004-10-06T21:4

3:25.727Z

M2_event

M3_event

ECSCurrentID

1097099004636c alculate

1097099005257:

M1

1097099005257:

M1

1097099005467:

M2

1097099005717:

M3

ECSParentID Situation

Start Situation

1097099004636c alculate

1097099004636c alculate

1097099004636c alculate

1097099005467:

M2

Other Situation

Other Situation

Other Situation

Other Situation

160 Using the WebSphere Business Integration Server Foundation Programming APIs

Creation Time

2004-10-06T21:4

3:25.918Z

2004-10-06T21:4

3:26.168Z

2004-10-06T21:4

3:41.590Z

Name

M4_event1

M4_event2

Servlet _session

_stopped

ECSCurrentID

1097099005908:

M4

1097099005908:

M4

1097099004636c alculate

ECSParentID

1097099005467:

M2

1097099005467:

M2

Situation

Other Situation

Other Situation

Stop Situation

2.6 Sample code

This section has the instructions for using the sample codes of CEI scenarios provided with this Redpaper.

Follow these steps for importing and setting up the server.

1. Import the SAW424EAR.ear file into your WebSphere Studio Application

Developer Integration Edition 5.1.1 workspace.

2. Follow the instructions provided in Appendix B, “Configuration and setup” on page 199 to enable CEI on the unit test environment server.

2.6.1 Event source sample code

Follow these steps to run an event source sample code.

1. Start the server that you configured.

2. Go to SAW424Web

WebContent

jsp, select Welcome.jsp, right-click, and select Run on Server.

Note: You can also start this sample in a Web browser by using the URL http://localhost:9080/SAW424Web/jsp/Welcome.jsp

A welcome page opens with options to run different examples.

3. Click Generate a simple event link.

You can see that a simple event is created and a success message is displayed. You can see the server console to check that the event

extensionName: MySimpleEvent is created.

Alternatively you can see the event in the CBE event browser. For more

instructions on the CBE event browser, see “CBE event browser” on page 130.

Chapter 2. Common Event Infrastructure programming 161

4. Similarly you can generate complex events by clicking Generate a complex

event.

5. Now take a look at SAW424Web

JavaSource

→ com.ibm.ral.itso.cei

EventGenerator.java and ComplexEventgeneration.java file to examine the code.

2.6.2 Event consumer sample code

Our sample code also shows how to perform as an event consumer.

Using JMS interface

Follow the instructions to configure CEI and MDB described in Appendix B,

“Configuration and setup” on page 199.

Observe that whenever a new event is created, it is consumed by the Message

Driven Bean.

Go to SAW424EJB

→ ejbModule

→ com.ibm.ral.itso.cei.mdb

ConsumerBeanBean.java to examine the code.

Follow the instructions below.

1. Uncomment the

.setEventSelector(..)

at line 78. Save the file.

2. Restart the server.

3. Start the examples welcome page on the server.

4. Generate a complex event. Observe in the server console, that the MDB does not consume this event.

5. Open the ComplexEventGenerator.java used in Event source sample code.

6. Update the code to set the severity of the events to be more than 30, say 40.

7. Save the file.

8. Restart the server.

9. Start the examples welcome page on the server.

10.Generate a complex event. Observe in the server console that the MDB now consumes the event.

Using the event access interface

Follow these steps to run an event consumer using our event access interface sample code. Make sure you create some simple and complex events before running this.

1. Start the server that you configured.

162 Using the WebSphere Business Integration Server Foundation Programming APIs

2. Go to SAW424Web

WebContent

jsp, select Welcome.jsp and right-click it.

3. Select Run on Server.

The welcome page opens with options to run different examples.

4. Click Consume events from database link.

You can see that a events are read from the persistent data store and a success message is displayed. You can see the server console to check the event details. You can verify the same using CBE event browser.

5. Look at the SAW424Web

JavaSource

→ com.ibm.ral.itso.cei

EventConsumer.java file to examine the code.

2.6.3 Purging events sample code

Follow these steps to run the sample code to delete the events from the persistent data store. Make sure you created some simple and complex events before running this.

1. Start the server that you configured.

2. Go to SAW424Web

WebContent

jsp, select Welcome.jsp, right-click, and select Run on Server.

The welcome page opens with options to run different examples.

3. Click Delete all events link.

You can see the count of events purged from the data store in the server console.

4. Look at the SAW424Web

JavaSource

→ com.ibm.ral.itso.cei

EventRemover.java file to examine the code.

Chapter 2. Common Event Infrastructure programming 163

164 Using the WebSphere Business Integration Server Foundation Programming APIs

3

Chapter 3.

Business Process

Choreographer and CEI

This chapter discuss the use of the (CEI) with the Business Process

Choreographer. We develop a more detailed example to show how to use CEI and the Business Process Choreographer together.

© Copyright IBM Corp. 2004. All rights reserved.

165

3.1 Business processes and CEI

As described in Chapter 2, “Common Event Infrastructure programming” on page 93 the Common Event Infrastructure emits and later on consumes arbitrary

events. One of the most interesting and gainful use cases for CEI is to apply this technology in the context of business processes. Business relevant events can be emitted and later on be consumed for various analysis, for example to optimize business processes, find bottlenecks or critical paths or learn more about the modelled business itself. CEI can also monitor business processes and trigger actions when certain circumstances occur.

To emit events within the context of a business process, you can use the CEI API

as described in Chapter 2, “Common Event Infrastructure programming” on page 93. The respective CEI API methods can be used in a Java Snippet activity

or by an implemented service, for example by a session enterprise bean or a

Java class, which is called by the process via the Invoke activity. The advantage of using the CEI API directly is that you have full control over the data to be emitted. You can emit exactly the data you need when consuming the events.

One drawback is that you have to instrument your business process by inserting

Java Snippets or Invoke activities to emit relevant events.

As an alternative, Business Process Choreographer provides a predefined set of events that you can very easily enable by just marking the respective Business

Process Choreographer object (process, activity, variable or link) as business relevant in the BPEL editor. The predefined set contains events for:

򐂰 the life cycle of process instances (process started, completed, failed, etc.)

򐂰 the life cycle of activities (activity ready, claimed, completed, failed, etc.)

򐂰 updates of variables

򐂰 evaluation of links

Every emitted Business Process Choreographer event contains a set of settled

data. Details of the events and the data emitted are described in 3.4, “Business

Process Choreographer event reference” on page 172. In contrast to using the

CEI API directly and emitting arbitrary data, you cannot emit specific data in addition to the predefined set of properties, when using Business Process

Choreographer events.

Using the CEI API directly or using the predefined set of Business Process

Choreographer events is not mutually exclusive. You can use both approaches

166 Using the WebSphere Business Integration Server Foundation Programming APIs

together if necessary. For example Figure 3-1 shows a process that invokes an

enterprise bean, that itself emits CEI events.

Figure 3-1 Correlation spheres

The blue circles indicate the CEI correlation spheres. The process activities run in their own correlation spheres with the process instance correlation sphere as their parent sphere. If ’TheEJB’ was programmed to start a new correlation sphere, it has its own sphere with the correlation sphere of the Invoke activity as its parent. Otherwise the enterprise bean runs in the same correlation sphere as the Invoke activity.

The reminder of this chapter focuses on the predefined set of Business Process

Choreographer events, describing how to configure your process model so that events are emitted, and different approaches to consume those events. Later techniques can also be used for arbitrary events emitted via the CEI API directly.

Note: Heavy event traffic sent through CEI can have an impact on the performance of your applications. This Redpaper does not cover these issues, but in general you should try to emit events only for the processes, activities, variables, and links that you are really interested in. Additionally, you may take advantage of CEI filtering and as well the performance tuning options for

WebSphere and the database system you use.

Chapter 3. Business Process Choreographer and CEI 167

3.2 Emitting Business Process Choreographer events

It is very easy to configure business processes to emit CEI events for process instances, activities, variables, and links. Here are the steps to perform:

1. Open the business process in the BPEL editor.

2. Select the respective object: process, activities, variables, or the flow activities containing the links in which you are interested.

3. Click the Server tab.

4. Check / uncheck the Business relevant flag.

5. Save, and redeploy the business process.

Note: In order to configure the business process to emit link events, mark the flow activity containing the link as business relevant. Be aware that this causes the process engine to emit link events for

every

link contained in that flow activity.

Figure 3-2 Business relevant flag for processes

Figure 3-2 shows the Server properties including the business relevant flag for

business processes. Figure 3-3 on page 169 shows the same for link events. In

the latter case the containing flow activity has to be selected.

168 Using the WebSphere Business Integration Server Foundation Programming APIs

When marking Business Process Choreographer objects as business relevant, the granularity is all or nothing. There is no way to configure Business Process

Choreographer to emit only selected events (for example only the activity claimed events for a staff activity or only the process failed event for a process instance). CEI filtering can be used to prevent undesired events being put on the event bus. It is also possible to code the event consuming application so that it ignores Business Process Choreographer events of no interest.

Note: The WebSphere Studio Application Developer Integration Edition BPEL editor offers the possibility to set the Business relevant flag on every activity.

Be aware that there are no events emitted for structuring activities such as

Sequence, Switch, Pick, and so on.

Figure 3-3 Business relevant flag for links

Note: By marking a Business Process Choreographer object as business relevant, events are not only emitted on the CEI event bus, but they are also written in the audit log database table. Please make sure to maintain/purge this table on a regular basis for systems in production.

3.3 Using Business Process Choreographer events

3.2, “Emitting Business Process Choreographer events” on page 168 explained

how to set up business processes to emit Business Process Choreographer events for process, activity, variable, and link events. This section describes the

Chapter 3. Business Process Choreographer and CEI 169

possibilities for analyzing and consuming those events after or while the business processes are running.

Emitting Business Process Choreographer events does not require the user to write a single line of code as it is sufficient to just mark the respective Business

Process Choreographer object as business relevant, the out of the box capabilities for analyzing and consuming such events are limited. WebSphere

Studio Application Developer Integration Edition comes with a J2EE application to view CBE events, but to use and take advantage of the emitted events in a real scenario, you have to write your own code that processes these events.

Note: As Business Process Choreographer uses the Common Event

Infrastructure to emit events, we do not repeat details of the respective programming practice, but describe business process specific applications.

3.3.1 Using the CBE viewer

The CBE viewer, which comes with WebSphere Studio Application Developer

Integration Edition, allows you to retrieve and display events found in the CEI datastore. There are no possibilities to aggregate events, for example displaying the duration of a business process by using the process started and process completed events of a process instance.

The CBE viewer is very useful for the CEI novice or when coding an event consuming application to get a better understanding of the events of which the user is dealing. The CBE viewer allows the user to view the event details, for example the ContextDataElement and ExtendedDataElement properties, or to check if events were emitted properly.

Note: For a description of the CBE viewer, go to WebSphere Business

Integration Server Foundation

Administering

Applications

Application Services

Viewing events with the event browser in the

WebSphere Studio Application Developer Integration Edition help.

To view Business Process Choreographer events with the CBE viewer, perform

the steps described in “CBE event browser” on page 130.

3.3.2 Retrieving events from the data store

As described in Chapter 2, “Common Event Infrastructure programming” on page 93, there are two different ways of consuming CEI events:

򐂰 Subscribing to the respective JMS queue or topic to process events as they arrive

170 Using the WebSphere Business Integration Server Foundation Programming APIs

򐂰 Querying the CEI data store.

Querying the data store is done via the queryEvents*() methods offered by the event access enterprise bean.

The CEI data store approach retrieves a single event or correlates multiple historical events, for example in order to statistically analyze business processes.

The average duration of process instances or activities, the average duration till a staff activity is claimed, the ratio of expired or failed activities, the number of process paths and their frequency are relatively obvious properties that can be calculated. Other figures may include business data available through Business

Process Choreographer variable update events or events not emitted by

Business Process Choreographer but for example generated by an enterprise bean invoked from a business process. The possibilities are nearly boundless.

The calculated figures are helpful in detecting bottlenecks or critical paths and can optimize business processes. You can also use these figures to get a better understanding of the business itself.

All retrieved Business Process Choreographer events contain at least the process instance ID (PIID) of the process instance that emitted the event. The

PIID is accessible via the ECSCurrentID or ECSParentID property of the

ContextDataElement (described in 3.4, “Business Process Choreographer event reference” on page 172). The PIID or other event properties such as the activity

instance ID (AIID) or process template name can be used in Business Process

Choreographer API calls to get more information about the process instance, activities, variables, and so on, or to trigger some actions.

Note: If the process instance that emitted the retrieved events was deleted, you may get exceptions when using such event properties as arguments in

Business Process Choreographer API method calls.

The first sample of this chapter provides a good starting point to become acquainted with retrieving Business Process Choreographer events from the CEI data store.

3.3.3 Retrieving events from topics and queues

Use the other approach, which retrieves events by subscribing to topics or queues, when you are interested in specific events as they arrive in order to trigger some action. For example if a compensation in doubt event is consumed, an employee is notified to review the respective process instance.

Chapter 3. Business Process Choreographer and CEI 171

In many cases the absence of an event is of interest, rather than the occurrence of the event. For example if a work item is not claimed within a certain period of time, some actions are triggered. This is achievable by consuming the related starting event (in the example the activity ready event) and triggering the desired actions in case the event of interest (in the example the activity claimed event) does not occur within a certain time period. The second sample of this chapter shows how you can use the scheduler service to obtain the same results.

Business Process Choreographer event properties such as PIIDs, AIIDs, or template names can be used as arguments in Business Process Choreographer

API method calls to retrieve more information about Business Process

Choreographer objects or to trigger some action.

Tip: The Business Process Choreographer API methods getActivityInstance(), getProcessInstance(), getVariable() and getCustomProperty() are quite useful to get additional information about the respective Business Process

Choreographer objects.

The second sample of this chapter shows you how to retrieve events from the preconfigured CEI AllEvents topic and how to trigger some actions when certain

Business Process Choreographer events arrive.

3.4 Business Process Choreographer event reference

This section gives an overview of all events emitted by the process engine along with a description of the data provided with each specific event. As described in

Chapter 2, “Common Event Infrastructure programming” on page 93, CBE

events consist of several parts: top-level properties, ComponentIdentification,

Situation, ContextDataElements and ExtendedDataElements. For Business

Process Choreographer events some of these properties are common, others depend on the event type (process instance, activity, variable, and link events) or even the specific event. A description of the common CBE properties follows.

Tip: Some of the tables in the following sections are available in the

WebSphere Studio Application Developer Integration Edition online help in a condensed form. Go to WebSphere Business Integration Server

Foundation

Administering

Applications

Business Process

Choreographer

Monitoring business processes using Common Base

Events.

172 Using the WebSphere Business Integration Server Foundation Programming APIs

3.4.1 CBE properties common to Business Process Choreographer events

Table 3-1lists the CBE attributes set by the process engine. The creationTime

provides information about the time the event was created. The extensionName property distinguishes the different Business Process Choreographer events.

Table 3-1 Common Base Event attributes set by Business Process Choreographer

Attribute Description creationTime globalInstanceId

The time when the event was created

The identifier of the Common Base Event instance sequenceNumber severity version extensionName

The number of Common Base Events generated

The impact that the event has on process choreographer

This attribute is set to 10 (information).

Set to 1.0.1.

Value depends on the process choreographer object that creates the event: WPC:ProcessInstanceEvent,

WPC:ActivityEvent, WPC:VariableEvent, WPC:LinkEvent

For example the code snippet in Example 3-1 shows how to retrieve all Business

Process Choreographer process instance events by using the extensionName property in the eventSelector XPath expression in the queryEventsByEventGroup() method of the EventAccess enterprise bean:

Example 3-1 Using the extensionName property in the eventSelector XPath expression

// lookup and create eventAccess enterprise bean

EventAccess eventAccess = ...;

CommonBaseEvent[] events = eventAccess.queryEventsByEventGroup(

“All events”,

“CommonBaseEvent[@extensionName = 'WPC:ProcessInstanceEvent']“, true);

// process events

...

Table 3-2 on page 174 summarizes the sourceComponentId attributes set by

Business Process Choreographer. For example you can use the componentType and subcomponent attributes in the eventSelector XPath expression when retrieving events via the EventAccess bean to get only Business Process

Choreographer events.

Chapter 3. Business Process Choreographer and CEI 173

Attributes such as exectutionEnvironment, component, instanceId, and location provide useful information about the operating system, WebSphere Business

Integration Server Foundation version, JDK version, and the server on which the event was emitted.

Table 3-2 sourceComponentId attributes set by Business Process Choreographer

Attribute Description component Set to WBI-SF followed by the version number of the software stack.

componentIdType executionEnvironment instanceId

Set to ProductName.

A string that identifies the operating system.

The identifier of the server. This identifier has the format

<cell name>/<node name>/<server name> location locationType processId subcomponent threadId componentType

Set to the host name of the executing server.

Set to Hostname.

The process identifier of the operating system.

Set to WPC.

The thread identifier of the Java Virtual Machine.

Set to: www.ibm.com/namespaces/autonomic/Workflow_Engine

A description of the CBE Situations used by Business Process Choreographer resides in the following section of the WebSphere Studio Application Developer

Integration Edition online help: WebSphere Business Integration Server

Foundation

Administering

Applications

Process Choreographer

Monitoring business processes using Common Base Events

Situations

used in process choreographer events.

174 Using the WebSphere Business Integration Server Foundation Programming APIs

3.4.2 Process instance events

Process instances run through different states during their life cycle. Along with

the different states traversed, respective events (listed in Table 3-3) are emitted

by the process engine.

Figure 3-4 Process states and transitions

Process Running

(Started)

Process

Terminated

Process Finished

(Completed)

Process

Failed

Process

Compensated

Process

Compensating

Process

Deleted

Compensation in Doubt

Figure 3-4 shows the process states along with their transitions. If the emitted

event is named differently from the respective process state, the state contains the event name in brackets. There are no CEI events emitted for the process compensating state.

Table 3-3 Process instance events

Event code Situation Description

21000 Start Process started

21004

21005

42001

42004

42030

Stop

Stop

Fail

Stop

Report

Process completed

Process terminated

Process failed

Process compensated

Compensation in doubt

Chapter 3. Business Process Choreographer and CEI 175

Event code

21020

Situation

Destroy

Description

Process deleted

For every process instance event:

򐂰 The CBE extensionName property is set to WPC:ProcessInstanceEvent.

򐂰 The ECSCurrentID property of the CBE ContextDataElement element contains a string representation of the process instance ID (PIID) of the process that emitted the event.

򐂰 The ECSParentID is set to the value that was the ECSCurrentID at the time the process was started.

򐂰 The CBE ExtendedDataElement element contains the WPCEventCode and

the processInstanceExecutionState properties (see Table 3-4).

Table 3-4 ExtendedDataElement properties of process instance events

Attribute Description

WPCEventCode processInstanceExecutionState

The Business Process Choreographer event

code (see Table 3-3 for details).

A string representation of the state of the process.

For process started events (WPCEventCode ‘21000’), the ExtendedDataElement

element contains additional properties (listed in Table 3-5), for example the

process template name or the user who started the process.

Table 3-5 Additional ExtendedDataElement properties for process started events

Attribute Description processTemplateName The name of the process template from which the instance was derived processTemplateValidFrom processTemplateID processInstanceDescription

Username processInstanceExecutionState

The date from which the template is valid

The identifier of the process template

If this attribute is set, it is the description of the process instance.

The name of the user who created the process instance

A string representation of the state of the process

176 Using the WebSphere Business Integration Server Foundation Programming APIs

For process failed events (WPCEventCode ‘42001’) the ExtendedDataElement element contains the additional property processFailedException containing a string description of the exception that caused the process to fail.

3.4.3 Activity events

Processes are activities run through different states during their life cycle. Along with the different states traversed, Business Process Choreographer emits

respective events. Figure 3-5 shows the activity states and their transitions. If the

emitted event is named differently from the respective activity state, the state

contains the event name in brackets. Figure 3-5 does not contain the loop

condition true/false events.

Inactive

Claim

Activity Running

(Started) /

Activity Claimed

Timeout

Force retry

Acitvity Ready Timeout

Terminate

Cancel claim

Activity Expired

Terminate

Activity Stopped

Force complete with fault

Force retry

Unhandled fault

(stop on error)

Unhandled fault

(continue on error)

or handled fault

Activity Failed

Complete /

Implementation complete

Activity Finished

(Completed)

Activity Terminated

Force complete with result

Figure 3-5 Activity states and transitions

Table 3-6 on page 178 lists the complete set of Business Process Choreographer

activity events.

Chapter 3. Business Process Choreographer and CEI 177

Table 3-6 Activity instance events

Event code Situation Description

21006

21007

Start

Start

Activity ready

Activity started

21011

21027

42015

21080

Stop

Stop

Stop

Fail

Activity completed

Activity terminated

Activity stopped

Activity failed

21081

21022

21021

42037

42038

Report

Report

Report

Report

Report

Activity expired

Activity claimed

Claim canceled

Loop condition true

Loop condition false

For every activity event:

򐂰 The CBE extensionName property is set to WPC:ActivityEvent.

򐂰 The ECSCurrentID property of the CBE ContextDataElement element contains a string representation of the activity ID (AIID) of the activity that emitted the event.

򐂰 The ECSParentID property contains a string representation of the process instance ID (PIID) of the containing process instance.

򐂰 The CBE ExtendedDataElement element contains the WPCEventCode, the

activity kind, and the activity state (see Table 3-7).

Table 3-7 ExtendedDataElement properties of activity events

Attribute Description

WPCEventCode activityKind

The Business Process Choreographer event

code (see Table 3-6 for details)

A string value that identifies the activity kind

This value has the format: <kind number>-<kind description>

178 Using the WebSphere Business Integration Server Foundation Programming APIs

Attribute state

Description

A string value that represents the state of the activity

It has the format: <state number>-<state description>

Tip: The com.ibm.ral.itso.bpe.cei.statistics.WPCEventConstants class in the provided sample (SAW424Web project) contains constant declarations for

Business Process Choreographer event codes, activity kinds, activity states, and so on.

The activity ready, claimed and claim canceled events (WPCEventCode ‘21006’,

‘21022’, 21021’) apply only for staff activities. For activity claimed events the

ExtendedDataElement element contains the additional properties username and principal, containing information about the user who claimed the activity and the principal who initiated the claim.

The loop condition true/false events (WPCEventCode ‘42037’, ‘42038’) only apply for while activities. Whenever the while condition is evaluated the respective loop condition true/false event is emitted.

The activity expired event (WPCEventCode ‘21081’) only applies for activities that can expire (invoke and staff activities). The BPEL editor offers the possibility to specify an expiration for pick activities (onAlarm), but there are no activity expired events emitted in that case.

For activity failed events (WPCEventCode ‘21080’) the ExtendedDataElement element contains the additional property activityFailedException containing a string description of the exception that caused the activity to fail.

Table 3-8 Additional ExtendedDataElement properties for activity events

Attribute Description activityTemplateName If this attribute is set, it is the name of the activity template from which the instance was derived. activityInstanceID activityInstanceDescription

The identifier of the activity instance.

If this attribute is set, it is the description of the activity instance.

Chapter 3. Business Process Choreographer and CEI 179

The first event of a business relevant activity instance contains additional

properties in the ExtendedDataElement element, listed in Table 3-8. The first

event of an activity depends on the activity kind, see Table 3-9 for details.

Table 3-9 First activity event emitted

Activity kind

Staff

Invoke, Receive, Wait

Assign, Empty, Reply, Java Snippet,

Terminate, Throw

While

First event emitted

Activity ready

Activity started

Activity completed, terminated, failed, stopped, expired

Loop condition true/false

3.4.4 Variable event

Whenever a process variable marked as business relevant gets updated a respective variable update event is emitted by the process engine as shown in

Table 3-10.

Table 3-10 Variable event

Event code Situation

21090 Report

Description

Variable update

For variable events:

򐂰 The CBE extensionName property is set to WPC:VariableEvent.

򐂰 The ECSCurrentID property of the CBE ContextDataElement element contains a string representation of the process instance ID (PIID) of the containing process instance.

򐂰 The ECSParentID is set to the value that was the ECSCurrentID at the time the containing process started.

򐂰 The CBE ExtendedDataElement element contains the WPCEventCode, variable name and a string representation of the variable value (see

Table 3-11).

Table 3-11 ExtendedDataElement properties of variable events

Attribute Description

WPCEventCode elementName

The Business Process Choreographer event code (set to

‘21090’).

The name of the variable that was changed.

180 Using the WebSphere Business Integration Server Foundation Programming APIs

Attribute variableData

Description

A string representation of the content of the variable. The string represents the name-value pairs.

The updated content of the variable is accessible via the variableData property of the ExtendedDataElement element. For variable parts of non primitive data types, the toString() method of the respective Java class is called to get a string representation of the part value.

3.4.5 Link events

Whenever a link marked as business relevant was evaluated a respective link evaluated true/false event is emitted by the Business Process Choreographer as

shown in Table 3-12.

Table 3-12 Link events

Event code Situation

21034

42000

Report

Report

Description

Link evaluated true

Link evaluated false

For every link event:

򐂰 The CBE extensionName property is set to WPC:LinkEvent.

򐂰 The ECSCurrentID property of the CBE ContextDataElement element contains a string representation of the process instance ID (PIID) of the containing process instance.

򐂰 The ECSParentID is set to the value that was the ECSCurrentID at the time the containing process was started.

򐂰 The CBE ExtendedDataElement element contains the WPCEventCode, link

name, and an optional description (see Table 3-13).

Table 3-13 ExtendedDataElement properties of link events

Attribute Description

WPCEventCode The Business Process Choreographer event code (see

Table 3-12 for details)

elementName

Description

The name of the link that was evaluated

If this attribute is set, it contains a description of the link

Chapter 3. Business Process Choreographer and CEI 181

3.5 Sample scenarios

Now we introduce two scenarios that show how you can leverage the CEI data store to calculate some statistics for business processes, and how you can use the JMS based distribution of CEI events to trigger some actions on the occurrence of specific events as they arrive.

3.5.1 Calculating statistics for processes and activities

In the first scenario, Business Process Choreographer events calculate some statistics for processes and activities found in the CEI database. The statistics include:

򐂰 Minimum, maximum and average duration of process instances

򐂰 Number of process instances

򐂰 Ratio of completed, terminated and failed process instances

򐂰 Number of different process paths navigated

򐂰 Process paths (list of navigated activities) and frequency

򐂰 Minimum, maximum and average duration of activities

򐂰 Average duration of activities in relation to the average duration of the process instance

򐂰 Ratio of completed, terminated, failed and expired activities

Preparation

You need to install iFix PQ93161 with the WebSphere UpdateManager in order to get activity claimed and claim canceled events. You can download the iFix from the IBM support pages at the following Web address: http://ibm.com/software/integration/wbisf/support/

Note: This interim fix is included in Cumulative Fix 1 for Version 5.1 of

WebSphere Business Integration Server Foundation.

Running the sample

The sample code is generic in the way that it does not require certain processes to run; however, as it analyzes Business Process Choreographer events found in the CEI datastore, you should run some process instances of arbitrary business processes to populate the CEI datastore first. For example you can use the

IncidentReport process introduced in the previous chapters or the orderProcess or claimsHandlingProcess coming with WebSphere Studio Application

Developer Integration Edition 5.1.1. Please refer to the Infocenter help on how to install and run these processes.

Install the SAW424* projects. Create and configure a CEI enabled test server as

described in Appendix B, “Configuration and setup” on page 199.

182 Using the WebSphere Business Integration Server Foundation Programming APIs

To run the sample, perform the following steps:

1. Switch to the Servers view.

2. Select and start the test server.

3. When the server is ready for business, expand the SAW424Web project.

4. Navigate to the WebContent/jsp/bpe folder.

5. Select the WPCStatistics.jsp.

6. Right-click and choose Run on Server....

7. Select the desired test server, accept the defaults, and click Finish.

A Web browser window displaying the statistics should open.

Note: If the CEI database contains a large number of events, the analysis can take a while.

Figure 3-6 on page 184 shows a sample result of one evaluation. The first table

lists all process templates with minimum, maximum, and average duration of process instances for each template. It also lists the total amount and the number of completed, terminated, and failed process instances. The last column provides the number of different process paths taken.

Chapter 3. Business Process Choreographer and CEI 183

Figure 3-6 Sample result of WPCStatistics.jsp

For each process template, two additional tables are displayed: one containing similar data as in the first table, but not for each activity. The number enclosed in brackets in the average duration column is the average duration of the activity relative to the average duration of the process. So it is very easy to recognize activities that take a big share of the total duration of the process.

The second table lists the different process paths taken along with their frequency. A process path is the list of activities traversed during the run of one process instance. The table detects paths that are taken very often.

184 Using the WebSphere Business Integration Server Foundation Programming APIs

Code analysis

In order to analyze the sample code, expand the SAW424Web project and look at the classes in the com.ibm.ral.itso.bpe.cei package. ProcessData,

ProcessStatistics, ActivityData, and ActivityStatistics are just containers for process instance, process statistic, activity, and activity statistic data are not explained here (except the ProcessStatistics.addProcessPath() method which will be explained later). Please review the source code for details.

Note: This section focuses on the code to retrieve and process Business

Process Choreographer events. The JSP to display the results, and the code to calculate the statistics are not covered. Please review the source code in the com.ibm.ral.itso.bpe.cei package and the WPCStatistics.jsp in the jsp/bpe folder for these purposes.

The most interesting class in this sample is WPCEventAnalyzer. It contains a method to get hold of an EventAccess enterprise bean instance shown in

Example 3-2 and two methods to analyze process instance and activity events.

Example 3-2 Method to lookup and create an instance of the EventAccess bean private static EventAccess getEventAccessBean()

{ if (eventAccessBean == null) { try {

// obtain the default initial JNDI context

Context initialContext = new InitialContext();

// lookup the home interface of the EventAccess bean

Object result = initialContext.lookup("ejb/com/ibm/events/access/EventAccess");

// convert the lookup result to the proper type

EventAccessHome eaHome =

(EventAccessHome)javax.rmi.PortableRemoteObject.narrow( result, EventAccessHome.class);

// create an instance of the bean eventAccessBean = eaHome.create();

} catch (Exception ex) { ex.printStackTrace();

}

} return eventAccessBean;

}

The analyzeProcessEvents() method contains the logic to retrieve and analyze

Business Process Choreographer events in the CEI database. This method is called by the WPCStatistics.jsp. The returned map contains ProcessStatistics

Chapter 3. Business Process Choreographer and CEI 185

instances for every process template for which process events were found in the

CEI database. The analyzeProcessEvents() method retrieves all Business

Process Choreographer process instance events as shown in Example 3-3:

Example 3-3 Retrieve process instance events

EventAccess eventAccess = getEventAccessBean();

CommonBaseEvent[] events = eventAccess.queryEventsByEventGroup(

"All events",

"CommonBaseEvent[@extensionName = 'WPC:ProcessInstanceEvent']", true);

Then the retrieved process instance events are analyzed in a for loop. As described in the reference section, for Business Process Choreographer process instance the ECSCurrentID property of the CBE ContextDataElements element contains the PIID. As the getContextDataElements(“ECSCurrentID”) call returns an EMF EList with one single object of type ContextDataElement, the first entry is acquired (via the EList get(0) method call) and casted to ContextDataElement. getContextValue() returns a String representation of the PIID of the process instance that caused that event. In a similar way the Business Process

Choreographer event code is retrieved from the ExtendedDataElements element

as shown in Example 3-4.

Example 3-4 Retrieve event code from ExtendedDataElements

String piid =((ContextDataElement)events[i]

.getContextDataElements(WPCEventConstants.CBE_ECSCURRENTID)

.get(0)).getContextValue();

String eventCode = ((ExtendedDataElement)events[i]

.getExtendedDataElements(WPCEventConstants.CBE_WPCEVENTCODE)

.get(0)).getValuesAsString();

Note: As the ascendingOrder parameter in the queryEventsByEventGroup() was set to true, the events in the returned array are ordered in ascending order according to creation time. So when looping through the array in ascending order, process started events are traversed before the respective process completion event.

Depending on the Business Process Choreographer event group, different branches are executed: In the case of a process started event, the PIID, process template name, and creation time are stored in the processInstances map under the key of the actual process instance ID. In the case of a process completed, terminated, or failed event, the data for the respective process instance is retrieved via the processInstances map. The ProcessStatistics class for the respective process template counts the process instance as completed,

186 Using the WebSphere Business Integration Server Foundation Programming APIs

terminated, or failed. If the process instance completed successfully, the duration of the process instance is taken into account.

Note: This sample does not analyze process compensated and compensation in doubt events. The sample is intended to show you the principles of how to process Business Process Choreographer events in the CEI data store. You can easily modify the code to process compensation related events.

At the end of the analyzeProcessEvents() method, the code loops over all found process instances and analyzes the navigated activities as shown in

Example 3-5. For every process activity the ECSParentID property of the CBE

contextDataElements element contains the process instance ID for that activity.

This characteristic is used in the queryEventsByEventGroup() call to get all activities for the respective process instance.

Example 3-5 Analyze activities

// loop over all process instances and calculate statistics for activities for (Iterator it = processInstances.values().iterator(); it.hasNext(); ) {

ProcessData pd = (ProcessData)it.next();

// retrieve all activities for process instance events = eventAccess.queryEventsByEventGroup(

"All events",

"CommonBaseEvent[@extensionName = 'WPC:ActivityEvent' and contextDataElements[@name = 'ECSParentID' and @contextValue = '"+pd.getPiid()+"']]", true); analyzeActivityEvents(pd.getTemplateName(), events);

}

Example 3-6 lists the complete analyzeProcessEvents() method.

Example 3-6 analyzeProcessEvents() method public HashMap analyzeProcessEvents() { try

{

System.out.println("looking up eventAccessBean ...");

EventAccess eventAccess = getEventAccessBean();

CommonBaseEvent[] events = eventAccess.queryEventsByEventGroup(

"All events",

"CommonBaseEvent[@extensionName = 'WPC:ProcessInstanceEvent']", true);

System.out.println("found "+events.length+" process instance events

...");

Chapter 3. Business Process Choreographer and CEI 187

for (int i=0; i<events.length; i++)

{

String piid = ((ContextDataElement)events[i]

.getContextDataElements(WPCEventConstants.CBE_ECSCURRENTID).get(0))

.getContextValue();

String eventCode = ((ExtendedDataElement)events[i]

.getExtendedDataElements(WPCEventConstants.CBE_WPCEVENTCODE).get(0))

.getValuesAsString(); map if (WPCEventConstants.PROCESS_STARTED.equals(eventCode))

{

// store creation time, process template name and PIID in a hash

String processTemplateName = ((ExtendedDataElement)events[i]

.getExtendedDataElements(WPCEventConstants.CBE_PROCESSTEMPLATENAME).get(0))

.getValuesAsString(); processInstances.put( piid, new ProcessData(events[i].getCreationTimeAsLong(), piid, processTemplateName));

} else if (WPCEventConstants.PROCESS_COMPLETED.equals(eventCode)

|| WPCEventConstants.PROCESS_FAILED.equals(eventCode)

|| WPCEventConstants.PROCESS_TERMINATED.equals(eventCode))

{

ProcessData pd = (ProcessData)processInstances.get(piid); if (pd !=null) { long duration = events[i].getCreationTimeAsLong()-pd.getCreationTime(); pd.setDuration(duration);

ProcessStatistics ps =

(ProcessStatistics)processStatistics.get(pd.getTemplateName()); if (ps == null)

{ ps = new ProcessStatistics(pd.getTemplateName()); processStatistics.put(pd.getTemplateName(), ps);

} if (WPCEventConstants.PROCESS_COMPLETED.equals(eventCode))

{ ps.countCompletedInstance(duration);

} else if (WPCEventConstants.PROCESS_FAILED.equals(eventCode))

{ ps.countFailedInstance();

}

188 Using the WebSphere Business Integration Server Foundation Programming APIs

else if

(WPCEventConstants.PROCESS_TERMINATED.equals(eventCode))

{ ps.countTerminatedInstance();

} found");

}

} else

{

System.out.println("no starting event for process "+piid+"

}

}

// loop over all found process instances and calculate statistics for activities for (Iterator it = processInstances.values().iterator(); it.hasNext(); )

{

ProcessData pd = (ProcessData)it.next();

// retrieve all activities for process instance events = eventAccess.queryEventsByEventGroup(

"All events",

"CommonBaseEvent[@extensionName = 'WPC:ActivityEvent' and contextDataElements[@name = 'ECSParentID' and @contextValue =

'"+pd.getPiid()+"']]", true); analyzeActivityEvents(pd.getTemplateName(), events);

}

} catch (Exception e)

{ e.printStackTrace();

} return processStatistics;

}

The analyzeActivityEvents() method shown in Example 3-7 analyzes the

activities navigated during the run of a single process instance. It takes the process template name and the array of traversed activities during the process instance run in ascending order as arguments.

Example 3-7 analyzeActivityEvents() method public void analyzeActivityEvents(String processTemplateName, CommonBaseEvent[] events) { try {

Chapter 3. Business Process Choreographer and CEI 189

HashMap activities = new HashMap();

StringBuffer pathTaken = new StringBuffer();

} for (int i = 0; i<events.length; i++)

{

String aiid = ...

String eventCode = ...

String kind = ...

String state = ...

ActivityData ad = (ActivityData)activities.get(aiid); if (ad == null){

String templateName = ((ExtendedDataElement)events[i]

.getExtendedDataElements(WPCEventConstants.CBE_ACTIVITYTEMPLATENAME)

.get(0)).getValuesAsString(); ad = new ActivityData( events[i].getCreationTimeAsLong(), aiid, templateName, kind); activities.put(aiid, ad);

} else { ad.setDuration( events[i].getCreationTimeAsLong()-ad.getCreationTime());

} ad.setMostRecentEventCode(eventCode);

} catch (Exception e)

{ e.printStackTrace();

} pathTaken.append(ad.getTemplateName()); pathTaken.append(

"["+WPCEventConstants.ACTIVITY_STATES.get(state)+"] - ");

}

ProcessStatistics ps =

(ProcessStatistics)processStatistics.get(processTemplateName); ps.addProcessPath(pathTaken.toString(), activities);

The code loops over the activities array (containing all activity events occurred during a single process instance run), gets hold of some activity properties (AIID,

WPCEventCode, activity kind and state) in a similar way as shown for process events, and constructs a string representation of the process path taken by concatenating each traversed activity along with the activity state. At the end, analyzeActivityEvents() invokes the ProcessStatistics.addProcessPath() to update the respective ProcessStatistcs instance with the path and activity information.

190 Using the WebSphere Business Integration Server Foundation Programming APIs

Every ProcessStatistics instance contains a path taken hashmap with the string representation of the taken path as key and an Integer representing the frequency of this path as value. When entering the addProcessPath() method the count is initialized or incremented. Afterwards the code loops over all activities

and updates the respective ActivityStatistics instance as shown in Example 3-8.

Example 3-8 ProcessStatistics.addProcessPath() method public void addProcessPath(String pathTaken, HashMap activities) {

Integer count = (Integer)pathsTaken.get(pathTaken); if (count == null) pathsTaken.put(pathTaken, new Integer(1)); else pathsTaken.put(pathTaken, new Integer(count.intValue()+1));

} for (Iterator it = activities.values().iterator(); it.hasNext(); ) {

ActivityData ad = (ActivityData)it.next();

ActivityStatistics asd =

(ActivityStatistics)activityStatistics.get(ad.getTemplateName()); if (asd == null) { asd = new ActivityStatistics(ad.getTemplateName(), ad.getKind()); activityStatistics.put(ad.getTemplateName(), asd);

} if (WPCEventConstants.ACTIVITY_COMPLETED

.equals(ad.getMostRecentEventCode())) { asd.countCompletedInstance(ad.getDuration());

} else if (WPCEventConstants.ACTIVITY_FAILED

.equals(ad.getMostRecentEventCode())) { asd.countFailedInstance();

} else if (WPCEventConstants.ACTIVITY_TERMINATED

.equals(ad.getMostRecentEventCode())) { asd.countTerminatedInstance();

} else if (WPCEventConstants.ACTIVITY_EXPIRED

.equals(ad.getMostRecentEventCode())) { asd.countExpiredInstance();

}

}

The WPCStatistics.jsp uses the getter methods of the ProcessStatistics and

ActivityStatistics instances to retrieve and display the information captured in

Figure 3-6 on page 184. Please review the JSP for details.

Chapter 3. Business Process Choreographer and CEI 191

3.5.2 Triggering actions on specific events

Our second scenario of this chapter demonstrates how to trigger actions on the occurrence of specific events (or more precisely the absence of specific events).

The sample uses the IncidentReport process introduced in Chapter 1, “Business

Process Engine programming” on page 1. If instances of the IncidentReport

process have not finished within two minutes after they started, a message to look at the process instance is printed to the console. This is just for simplicity as we want to focus on the event handling part of the scenario. In real life scenarios you could send out e-mails, start other processes, and so on, instead of just writing to the console.

Code analysis

To achieve the functionality the sample consists of a Message Driven Bean

(com.ibm.ral.itso.bpe.cei.mdb.EventConsumerBean) that is subscribed to the

CEI AllEventsTopic, a stateless session bean that implements the TaskHandler remote interface of the scheduler service (WpcCeiTaskHandlerBean in the com.ibm.ral.itso.bpe.cei.taskhandler package), and a helper class containing the logic (com.ibm.ral.itso.bpe.cei.taskhandler.OverdueProcessesController).

Note: Please review the WebSphere Business Integration Server Foundation

V5.1 Handbook, SG24-6318 for details on the scheduler service.

Whenever a CEI event is published, the onMessage() method of the Message

Driven Bean is called. If a process started event for an IncidentReport instance is found, the PIID of this instance is added to the list of processes to be monitored along with the time when the action should be triggered. If the event passed to the onMessage() method is either process completed, terminated, or finished, the respective process instance is removed from the list. Please see

Example 3-9 and OverdueProcessesControllerdetails.java for details.

Example 3-9 The onMessage() method of EventConsumerBean public void onMessage(javax.jms.Message msg) { try

{ if (getNotificationHelper().getNotificationType(msg) ==

NotificationHelper.CREATE_EVENT_NOTIFICATION_TYPE)

{

CommonBaseEvent event = notificationHelper.getCreatedEvent(msg); if ("WPC:ProcessInstanceEvent".equals(event.getExtensionName()))

{

String eventCode = ((ExtendedDataElement)event

.getExtendedDataElements(WPCEventConstants.CBE_WPCEVENTCODE)

.get(0)).getValuesAsString();

192 Using the WebSphere Business Integration Server Foundation Programming APIs

}

String piid = ((ContextDataElement)event

.getContextDataElements(WPCEventConstants.CBE_ECSCURRENTID)

.get(0)).getContextValue(); if (WPCEventConstants.PROCESS_STARTED.equals(eventCode))

{

String processTemplateName = ((ExtendedDataElement)event

.getExtendedDataElements(WPCEventConstants.CBE_PROCESSTEMPLATENAME)

.get(0)).getValuesAsString(); if ("IncidentReport".equals(processTemplateName))

{ long overdueTime = System.currentTimeMillis()+120000;

OverdueProcessesController.getSingleInstance()

.registerProcess(piid, overdueTime);

}

} else if (WPCEventConstants.PROCESS_COMPLETED.equals(eventCode)

|| WPCEventConstants.PROCESS_FAILED.equals(eventCode)

|| WPCEventConstants.PROCESS_TERMINATED.equals(eventCode))

{

/* The processTemplateName property is not contained in process completed,

* failed or terminated events. In order to avoid retrieving this property

* every time, there is no check and the removeProcess() method is called

* on every process finished event.

*/

OverdueProcessesController.getSingleInstance()

.removeProcess(piid);

}

}

}

} catch (Exception e) { e.printStackTrace();

}

When the OverdueProcessesController is accessed the first time via the getSingleInstance() method, it registers the process instance. Afterwards the

WpcCeiTaskHandler.process() method is called on a regular basis by the scheduler service. The process() method itself calls the triggerActionsForOverdueProcesses() method which loops over the list of processes to be monitored. Process instances that did not finish within the anticipated time are removed from the list (to ensure that the action is only triggered once). A message that reminds the user to complete the process is

written to the console. See Example 3-10.

Example 3-10 Key methods in the OverdueProcessesController class public static OverdueProcessesController getSingleInstance() { if (task == null)

Chapter 3. Business Process Choreographer and CEI 193

}

{ try { task = new OverdueProcessesController();

// lookup the scheduler instance to be used

Scheduler scheduler =

(Scheduler)new InitialContext().lookup("BPEScheduler");

BeanTaskInfo taskInfo =

(BeanTaskInfo) scheduler.createTaskInfo(BeanTaskInfo.class);

// find the session bean to be called when the task executes

Object o =new InitialContext().lookup(

"ejb/com/ibm/ral/itso/bpe/cei/taskhandler/WpcCeiTaskHandlerHome");

TaskHandlerHome home = (TaskHandlerHome) javax.rmi.PortableRemoteObject.narrow(o,TaskHandlerHome.class);

// now set the start time and task handler to be called taskInfo.setTaskHandler(home); taskInfo.setStartTime(new Date(System.currentTimeMillis())); taskInfo.setName("WPCCEITask"); taskInfo.setRepeatInterval("1minutes");

TaskStatus ts = scheduler.create(taskInfo);

} catch (Exception e) { e.printStackTrace();

}

} return task; public synchronized void triggerActionForOverdueProcesses() { long currentTime = System.currentTimeMillis();

ArrayList processesToRemove = new ArrayList(); for (Iterator it = processes.keySet().iterator(); it.hasNext(); )

{

String piid = (String)it.next(); long overdueTime = ((Long)processes.get(piid)).longValue(); if (overdueTime<=currentTime)

{

// trigger action printNotification(piid); processesToRemove.add(piid);

}

}

// remove overdue items for (Iterator it = processesToRemove.iterator(); it.hasNext(); )

{ processes.remove(it.next());

}

}

194 Using the WebSphere Business Integration Server Foundation Programming APIs

public void printNotification(String piid) { try {

BusinessProcess bp = getBusinessProcessEjb();

ProcessInstanceData pd = bp.getProcessInstance(piid);

String incidentID = pd.getName();

String incidentAbstract = pd.getCustomProperty("abstract");

System.out.println("===================================================

========================");

System.out.println("Process "+piid+" has not finished in the given time.");

System.out.println("IncidentID: "+incidentID);

System.out.println("Abstract: "+incidentAbstract);

System.out.println("Please have a look at the process instance / complete it.");

System.out.println("===================================================

========================");

} catch (Exception e) { e.printStackTrace();

}

}

Running the sample

To run the sample perform the following steps:

1. Run the Incident.jsp as described Chapter 1, “Business Process Engine programming” on page 1.

2. Create and submit a new incident.

3. Wait for a approximately two minutes.

You should get a message in the console similar to the one shown in

Example 3-11.

Example 3-11 Console message for incidents

Process _PI:90030101.a00429c5.feffff80.c6350000 has not finished in the given time.

IncidentID: 293599

Abstract: Incident Abstract

Please have a look at the process instance / complete it.

This section described how to trigger some actions on the absence of certain events by leveraging the scheduler service. Executing some code on the occurrence of specific events is much easier. Just check for the respective event

Chapter 3. Business Process Choreographer and CEI 195

in the onMessage() method of the Message Driven Bean, and trigger the desired action.

196 Using the WebSphere Business Integration Server Foundation Programming APIs

A

Appendix A.

Additional material

This Redpaper refers to additional material that you can download from the

Internet as described in the following sections.

Locating the Web material

The Web material associated with this Redpaper is available in softcopy on the

Internet from the IBM Redbooks Web server. Point your Web browser to: ftp://www.redbooks.ibm.com/redbooks/ REDP3915

Alternatively, you can go to the IBM Redbooks Web site at:

ibm.com/redbooks

Select the Additional materials and open the directory that corresponds with the IBM Redbook form number.

Using the Web material

The additional Web material that accompanies this Redpaper includes the following files:

File name

REDP3915.zip

Description

Zipped Code Samples

© Copyright IBM Corp. 2004. All rights reserved.

197

System requirements for downloading the Web material

We recommend the following system configuration:

Hard disk space: 1 MB minimum

Operating System: Windows

Processor:

Memory:

Pentium® III 1GHz or higher

512 MB or higher

How to use the Web material

Create a subdirectory (folder) on your workstation, and download the Web material zip file into this folder.

For details of the sample code and instructions on how to install and work with

our samples refer to Appendix B, “Configuration and setup” on page 199.

198 Using the WebSphere Business Integration Server Foundation Programming APIs

B

Appendix B.

Configuration and setup

This appendix provides some of the configurations and setup required to run our samples on WebSphere Studio Application Developer Integration Edition 5.1.1.

We describe the following items:

򐂰

“Configuring CEI on unit test environment” on page 200

򐂰

“Configuring for working with Message Driven Bean event consumer” on page 209

򐂰

“Installing and setting up the Redpaper samples” on page 212

© Copyright IBM Corp. 2004. All rights reserved.

199

Configuring CEI on unit test environment

To enable J2EE applications for CEI, enable the test environment server for CEI.

Following are the general steps for doing this:

1. Creating a CEI Enabled server and server configuration.

2. Setting a JMS provider for the server configuration.

3. Configuring security (optional).

Creating a CEI Enabled server and server configuration

To enable your J2EE applications for CEI you need to create a CEI-enabled

WebSphere Business Integration Server Foundation 5.1.1 server. in WebSphere

Studio Application Developer Integration Edition. Ensure that the Business

Integration Perspective is opened, then do the following steps:

1. From the menu, select File

New

Other. The New window opens. The

Select page opens.

2. From the navigation tree, click Server.

3. From the pane, click Server and Server Configuration.

4. Click Next. The Create a new server and server configuration page opens.

5. From the navigation tree for the server type, click WebSphere version 5.1

Integration Test Environment.

6. In the Server name field, type WBI-SF-CEI

. See Figure 3-7 on page 201.

200 Using the WebSphere Business Integration Server Foundation Programming APIs

Figure 3-7 Server and server configuration for CEI

7. Click Next. The WebSphere Server Configuration Settings page opens.

8. Select the Enable the Common Event Infrastructure check box.

9. Click Finish. See Figure 3-8 on page 202.

Appendix B. Configuration and setup 201

Figure 3-8 Enable CEI

Setting a JMS provider for the server configuration

CEI uses messaging for the registration and generation of events. Specifically it uses queues and publish/subscribe services. WebSphere Studio Application

Developer Integration Edition 5.1.1 pre-configures the default JMS settings for

CEI as you can see in the server configuration editor on the JMS tab.

By default, event distribution is enabled for the server. Event distribution requires topic-based messaging; therefore, either WebSphere MQ or WebSphere MQ

Embedded Messaging must be installed and properly configured since the MQ

Simulator for Java Developers does not support topics. If you do not need event distribution, disable it. This allows you to continue working with only MQ

202 Using the WebSphere Business Integration Server Foundation Programming APIs

Simulator. The configuration of JMS providers are described in the following sections:

򐂰

“Configuring WebSphere Embedded Messaging as the JMS provider” on page 203

򐂰

“Configuring MQ Simulator for Java developers as the JMS provider” on page 205

We do not discuss configuring WebSphere MQ as the JMS provider.

Configuring WebSphere Embedded Messaging as the JMS provider

1. Install WebSphere Embeded Messaging.

2. Run the launchpad of the WebSphere Studio Application Developer

Integration Edition 5.1.1 installation.

3. Select Install embedded messaging client and server as shown in

Figure 3-9 on page 204.

Appendix B. Configuration and setup 203

Figure 3-9 Installing WebSphere Embeded Messaging

Use the following steps to set up WebSphere Embedded Messaging as the JMS provider:

1. Click the Servers tab.

2. From the servers list, double-click WBI-SF-CEI. The editor opens for

WBI-SF-CEI server configuration.

3. Click the JMS tab.

4. Click the Embedded Messaging radio button.

204 Using the WebSphere Business Integration Server Foundation Programming APIs

Figure 3-10 Select JMS provider

5. Click the Variables tab.

6. Under the Defined variables for the Node Settings, set

MQ_INSTALL_ROOT to the location where embedded messaging was installed, for example, C:/Program Files/IBM/WebSphere MQ .

7. Similarly, set WAS_PUBSUB_ROOT to the location where embedded publish/subscribe is installed, for example C:/Program Files/IBM/WebSphere

MQ/WEMPS .

Figure 3-11 Set MQ path

8. Save and close the server configuration.

Configuring MQ Simulator for Java developers as the JMS provider

You can also set up CEI to work with the MQ Simulator for Java Developers.

However, as mentioned earlier, this type of JMS provider does not support topics. The steps here show how to disable event distribution so that topics are not used.

1. After creating the server, ensure that the JMS provider on the JMS tab is set to MQ Simulator for Java Developers.

2. Open the server configuration editor for the new server (double-click the server).

Appendix B. Configuration and setup 205

3. Select the Configuration page, and check Enable the administration

console.

Figure 3-12 Enable Admin Console

4. Close and save the editor.

5. Start the server, right-click WBI-SF-CEI, and select Run administrative

console.

6. Log into the administration console, and select Resources

Event Infrastructure Provider.

Common

7. Select Cell, and click Apply.

8. Click Event Server Profile, then click Default Common Event

Infrastructure event server.

9. Uncheck Enable Event Distribution.

10.Click Apply, save to the master configuration, then log out of the administrative console.

11.Restart the server.

Note: Follow the same steps to enable Event Distribution. For all the examples in this Redpaper we keep the event distribution enabled.

206 Using the WebSphere Business Integration Server Foundation Programming APIs

Figure 3-13 Event Distribution option

Configuring security

If you want to have security enabled you also need to change some security settings.

1. Click the Security tab, and select Enable Security. Note that this only uses operating system authentication. Using another method, such as LDAP, is beyond the scope of our Redpaper.

2. From the table, select

localhost/BPEAuthDataAliasEmb_localhost_server1.

3. Click Edit. The Edit JAAS Authentication Entry window opens.

4. In the User ID field, type your user id.

5. In the Password field, type your password.

Appendix B. Configuration and setup 207

6. Click OK.

7. From the table, select

localhost/CommonEventInfrastructureJMSAuthAlias.

8. Click Edit. The Edit JAAS Authentication Entry window opens.

9. In the User ID field, type your user id.

10.In the Password field, type your password.

11.Click OK.

12.From the table, select

localhost/localhost/server1/EventAuthDataAliasCloudScape.

13.Click the Edit push button. The Edit JAAS Authentication Entry window opens.

14.In the User ID field, type your user id.

15.In the Password field, type your password.

16.Click OK.

17.Click Ctrl-s.

18.Close the WBI-SF-CEI server configuration.

208 Using the WebSphere Business Integration Server Foundation Programming APIs

Configuring for working with Message Driven Bean event consumer

To set up to use the Message Driven Bean event consumers:

1. Click the Servers tab.

2. From the table, double-click WBI-SF-CEI. The editor opens for WBI-SF-CEI server configuration.

3. Click the JMS tab.

4. Under the WASTopicConnectionFactory entries select

ComonEventInfrastructre_AlleventsTopicCF, and click Edit.

The edit WASTopicConnectionFactory window opens.

5. Change the port selection from DIRECT to QUEUED as shown in Figure 3-14 on page 210.

Appendix B. Configuration and setup 209

Figure 3-14 Modify topic connection

6. Click OK.

7. Click the EJB tab.

8. Click Add to add a new Listener Port.

9. Set the values as shown in Figure 3-15 on page 211.

210 Using the WebSphere Business Integration Server Foundation Programming APIs

Figure 3-15 Add Listener Port

10.Click OK.

11.Save and close the server configuration.

12.Restart the server.

Appendix B. Configuration and setup 211

Installing and setting up the Redpaper samples

This section describes how to install and set up the Redpaper sample code. We assume that you already downloaded the additional material as described in

Appendix A, “Additional material” on page 197.

Importing the sample code

The REDP3915.zip file downloaded as additional material for our Redpaper is a

WebSphere Studio project interchange file containing sample projects that you can import into your WebSphere Studio Application Developer Integration Edition workspace. The steps to follow are:

1. Start WebSphere Studio Application Developer Integration Edition.

2. Choose File

Import.

3. Select Project Interchange, and click Next. See Figure 3-16 on page 213.

212 Using the WebSphere Business Integration Server Foundation Programming APIs

Figure 3-16 Import project interchange

4. Click Browse, and select the REDP3915.zip downloaded from our Redpaper additional material.

5. Click Select All to import all the projects in the interchange file as shown in

Figure 3-17 on page 214.

Appendix B. Configuration and setup 213

Figure 3-17 Import all projects

6. Click Finish.

Tip: If after the project is imported, you have errors listed in the tasks view referring to the ejb-jar.xml in IncidentReportEjb project you can fix this by regenerating the IncidentReport process.

To regenerate the IncidentReport process, if necessary, the steps are:

1. Select the IncidentReport.bpel file found in the com.ibm.ral.itso.bpe.incident package of the IncidentReport services project.

2. Right-click, and choose Enterprise Services

Generate Deploy Code.

See Figure 3-18 on page 215.

214 Using the WebSphere Business Integration Server Foundation Programming APIs

Figure 3-18 Generate deploy code

3. Accept the default values for the deployment, and click OK to generate the

BPEL deploy code. See Figure 3-19 on page 216.

Appendix B. Configuration and setup 215

Figure 3-19 Deploy code settings

4. If a validate error, similar to that shown in Figure 3-20, appears, click OK to

proceed with the deployment. After the generation finishes, there may still be errors in the IncidentReportEJB project, but you can clear these by repeating the generation of the deploy code for the IncidentReport.bpel.

Figure 3-20 Validation errors.

216 Using the WebSphere Business Integration Server Foundation Programming APIs

Setting up sample projects

Use the following steps to prepare the Redpaper samples to run on the

WebSphere Studio Application Developer Integration Edition test server:

1. Generate the deploy code for the EJBs in the SAW424EJB project: a. In the J2EE Hierachy view, select the SAW424EJB project, right-click, and choose Generate

Deployment and RMIC Code. See Figure 3-21.

Figure 3-21 Generate EJB deploy code b. Click Select All to choose all the EJBs, and then click Finish. See

Figure 3-22 on page 218.

Appendix B. Configuration and setup 217

Figure 3-22 Select all EJBs

2. In the Servers view, select the WBI-SF-CEI server, right-click, and choose

Add and remove projects.

3. Add all the Redpaper sample projects, and click Finish. See Figure 3-23 on page 219.

218 Using the WebSphere Business Integration Server Foundation Programming APIs

Figure 3-23 Add projects to test server.

4. Make sure that the test server is stopped.

5. In the Servers view, select the WBI-SF-CEI server, right-click, and choose

Create tables and data sources.

A dialog similar to that shown in Figure 3-24 on page 220 should appear.

6. Click OK.

Appendix B. Configuration and setup 219

Figure 3-24 Generated tables and data sources

220 Using the WebSphere Business Integration Server Foundation Programming APIs

Abbreviations and acronyms

AIID

API

BPE

BPEL

CBE

CEI

EAR

ECS

EIS

EJB

FDML

HTML

HTTP

IBM

ISC

ITSO

J2EE

J2SE

JAAS

JCA

JMS

JNDI

JRE

JSP

Activity instance ID application programming interface

Business Process Engine

Business Process Execution

Language

Common Base Event

Common Event Infrastructure

Enterprise archive

Emitter Correlation Sphere

Enterprise Information

System

Enterprise Java Bean

Flow definition markup language

HyperText Markup Language

HyperText Transfer Protocol

International Business

Machines Corporation

Integrated Solutions Console

International Technical

Support Organization

Java 2 Platform, Enterprise

Edition

Java 2 Platform, Standard

Edition

Java Authentication and

Authorization Service

J2EE Connector Architecture

Java Message Service

Java naming and directory interface

Java Runtime Environment

JavaServer Pages

JVM

PIID

SNMP

SQL

WCCM

WSDL

WSIF

XML

XPath

XSD

Java Virtual Machine

Process instance ID simple network management protocol structured query language

WebSphere Common

Configuration Model

Web Services Description

Language

Web Service Invocation

Framework eXtensible Markup Language

XML Path Language

XML Schema Definition

221 © Copyright IBM Corp. 2004. All rights reserved.

222 Using the WebSphere Business Integration Server Foundation Programming APIs

Related publications

The publications listed in this section are considered particularly suitable for a more detailed discussion of the topics covered in this Redpaper.

IBM Redbooks

For information about ordering these publications, see “How to get IBM

Redbooks” on page 224. Note that some of the documents referenced here are

available in softcopy only.

򐂰 WebSphere Business Integration Server Foundation V5.1 Handbook,

SG24-6318

Online resources

The following Web sites are also relevant as further information sources:

򐂰 Canonical Situation Data Format: The Common Base Event V1.0.1

http://dev.eclipse.org/viewcvs/indextools.cgi/~checkout~/hyades-home/docs/c omponents/common_base_event/cbe101spec/CommonBaseEvent_SituationData_V1.0.1

.pdf?rev=1.1&content-type=text/plain

򐂰 Hyades javadocs http://dev.eclipse.org/viewcvs/indextools.cgi/~checkout~/hyades-home/docs/c omponents/common_base_event/cbe101/overview-summary.html

򐂰 Customizing the Business Process Choreographer Web Client http://www-106.ibm.com/developerworks/websphere/library/techarticles/wasid/

WPC_Client1/WPC_Client1.html

򐂰 WebSphere Business Integration Server Foundation Business Process

Choreographer http://www.ibm.com/developerworks/websphere/zones/was/wpc.html

򐂰 Work items and the query() API call http://ibm.com/developerworks/websphere/library/techarticles/wasid/WPC_Quer ies/WPCQueries.html

򐂰 Autonomic computing http://www.ibm.com/autonomic

© Copyright IBM Corp. 2004. All rights reserved.

223

򐂰 Eclipse Test and Performance Tools Platform http://www.eclipse.org/hyades/

򐂰 XML Schema Part 2: Datatypes dateTime http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/#dateTime

򐂰 XML Path Language (XPath) Version 1.0

http://www.w3.org/TR/xpath

򐂰 Eclipse Modeling Framework http://www.eclipse.org/emf

򐂰 WebSphere Business Integration Server Foundation support http://ibm.com/software/integration/wbisf/support/

How to get IBM Redbooks

You can search for, view, or download IBM Redbooks, Redpapers, Hints and

Tips, draft publications, and Additional materials, as well as order hardcopy redbooks or CD-ROMs, at the following Web site:

ibm.com/redbooks

Help from IBM

IBM Support and downloads

ibm.com/support

IBM Global Services

ibm.com/services

224 Using the WebSphere Business Integration Server Foundation Programming APIs

Back cover

WebSphere Business

Integration Server

Foundation

Using the programming

Understanding the business process engine API

Using the common event infrastructure

Code examples and solutions

This Redpaper describes the application programming interfaces (APIs) used to interact with the WebSphere

Business Integration Server Foundation V5.1 Business

Process Container. It also investigates how to use the

Common Event Infrastructure (CEI) API to log, retrieve, and manage events from the Business Process Container. We wrote this Redpaper as a practical guide for developers who need to write code that uses these APIs. Weprovide practical code examples and implementation samples so that developers can understand how to code using the available

APIs.

Red

paper

INTERNATIONAL

TECHNICAL

SUPPORT

ORGANIZATION

®

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.

For more information: ibm.com

/redbooks

Download