Business Process Management


Business Process Management (BPM) is about modeling, implementing, and managing the execution of automated business processes. Automated means that the process is driven by an application that orchestrates the interaction of the various human resources and software components that are required to perform the business process. With a few "green field" exceptions, BPM application development generally is a "meet-in-the-middle" process, which comprises these two elements:

  • A high-level requirements specification of the business functions that an enterprise wants to offer or perform, to achieve a business goal within certain constraints (cost and time limits, quality of service, and so on). Often this requirements specification is derived from the results of a more or less formal business process analysis effort. In other cases, the functions to be provided are dictated by public standards or external partners. In any case, the process specifications are likely to change frequently.

  • A set of existing application components that encapsulate operational data or perform business functions that need to be integrated into process execution. These components can be legacy applications, packaged applications, new J2EE components, or web services provided by external partners. Since they were not built specifically for use in a particular business process, some adaptation needs to be done to fit these components into the overall process.

The goal of BPM application development is to fill the gap between these two ingredients and make it easier to do the following:

  • Incorporate existing application components and resources into the process and manage the interactions of human process participants.

  • Add new business logic and modify previously defined behavior of the process without affecting other components used by the process.

  • Manage execution of the processes from a business user's perspective. This includes capability to suspend execution of the process or parts of the process if necessary.

  • Monitor status of the process at any point in time, providing information about progress of the overall process, status of individual process tasks, and resources used by the process.

  • Analyze business process execution, providing an execution trace of the process that offers sufficient information to analyze performance of one or more processes. This can be used to evaluate process performance, compare it to the objectives defined earlier, and enable process optimization based on lessons learned.

Further background and explanation of business process management would be going into too much detail. It suffices it to say that the challenge in the application server space is to meet these BPM goals in a way that is complementary and appropriate for application server-based business solutions. This really means that we need to expose and present these capabilities in a way that is natural and reasonable to those engaged in J2EE-centered development activities. The preceding statements are actually useful as a manifesto and set of guidelines for any infrastructure base that intends to support BPM. In our case, the infrastructure base is J2EE and web services.

As is usually the case, existing specifications for J2EE 1.3 could be pushed to the limits and used to implement many of the concepts just described. However, to more appropriately address these challenges, additional services and capabilities are called for. Let's see some of the services supported by WASE, starting with Process Choreography, and later Business Rules.

Process Choreography

The model for execution of a business process is often called a workflow. In software, workflow represents the automation of a business process or part of a business process. Sometimes workflow is refered as to just flow, while talking about a specific automated business process. WASE has a new feature called Process Choreographer. The workflow capabilities of WebSphere are categorized and measured under this umbrella. Process Choreographer in the runtime involves execution and management of flow-based applications. WebSphere Studio Application Development, Integration Edition (WAS IE) offers tooling that assists developers creating flow-based applications for later execution on the WASE runtime.

WebSphere's support for workflow brings about the true integration of the Java and J2EE worlds with the workflow world. Accessing non-Java artifacts during business processes is possible and simplified through the use of service-oriented architecture. However, when new activities are necessary, they can be constructed in Java using the full power of the J2EE programming model.

Workflow can be depicted graphically using a directed graph. The graph nodes represent individual steps in a flow. The graph edges or connectors describe the execution order of those steps (including conditional and concurrent execution), as well as the data that is needed by the activities. Each of the activities references an "activity implementation", which can be a sub-flow or an elemental operation; for example, a method of an EJB or a web service. People can be assigned to activities if humans perform the respective steps. Actions performed by humans demand that the infrastructure have in place an organizational model and demand that the workflow runtime have access to that. The following figure shows a very simple process as a series of steps shown in WebSphere Studio Application Developer, Integration Edition. Each step executes a different kind of activity just for purposes of demonstration. More refined and complete examples will follow later in this chapter:

click to expand

At run time, the business process engine executes instances of business processes, either in memory for short running flows, or with persistent state for long running flows. The individual activity implementations are invoked when needed, the state of the business process is tracked, work items are assigned to people if and when needed, and access to this information is provided via a worklist handler interface and associated GUI. The Process Choreographer capabilities of WebSphere can be used to describe a variety of "executables", from short running scripts involving a couple of service invocations up to long running business processes involving B2B interactions and people.

Many existing IBM products use flows of various types as their execution model – some examples are WebSphere MQ Integrator (formerly MQSeries Integrator), Lotus Workflow, WebSphere Adapters (formerly MQSeries Adapter Offering), Enterprise Access Builder, and MQSeries Workflow. Each of these products is specific to certain environments and certain types of flows. WebSphere MQ Integrator, for example, is optimized to flows that manage the routing and handling of messages in a messaged system.

WebSphere's Process Choreographer adds a general-purpose flow engine (Business Process Container) to the application server, which allows for the seamless management and efficient execution of all kinds of flows in the application server. Business processes, a term we will use interchangeably with flows, are deployed as part of EAR files, and are managed by the WAS admininistration console. WebSphere's Process Choregrapher is based on a business process engine written in pure Java that was designed with extensibility, flexibility, and performance in mind. With these design principles in place, it is intended that numerous kinds of flows can be executed using this technology to solve many business process problems in a wide variety of environments. The next section provides more details on the possible role for automated business processes.

The Role for Business Processes

Automated business processes can play a key role in architectures, which are based on the application server. This section will elaborate upon some of those architectures, and suggest some of the features that are necessary and available in WebSphere's Process Choreography support. These features make the creation of solutions that conform to the suggested architectures possible.First, if we look back to our discussion of the business model earlier in this chapter, we will see that the premise was made that the basic elements of the business process are implemented with session beans. The simplest application of flows involves implementing that session bean using flow technology. What happens is that the basic steps necessary to execute a business process are scripted using a flow. This flow probably also involves conditionally calling and leveraging EJBs that are in the solution architecture. These very simple flows are generally short lived in nature and are synchronously executed. These synchronous flows are called micro-flows or non-interruptable processes.Secondly, we begin to see more complex business processes being represented by workflow. These processes involve a flow that choreographs or scripts the usage of a number of sub-processes. These sub-processes may also be non-interruptable processes or just traditionally created session beans. What is important is that the system supports the ability to conditionally execute various sub-processes based on business rules. These more complex flows may also run for longer periods of time and are able to live beyond the lifetime of a given server instance. Activities in these flows often contain asynchronous invocations also. These are what would be characterized as macro-flows or interruptable processes. An interruptable process is shown in the following figure. It shows four major activities and suggests that each activity implementation is a session bean calling some entities. Obviously, actions that are more complex are allowed in the activity implementations. This will be further detailed later in the chapter. The stick figures in the figure represent human-interaction as part of one or more of the activities performed within the business proress:

click to expand

Next, we begin to see these basic short and long-lived business processes taking on various additional roles, leveraging some different features along the way. It is possible that flows will have a series of user-interactions, which are necessary to complete one or more of the steps in the business process. This requires workflows to play a more direct role in the presentation of the business process. The business process then is reacting directly to an ongoing stream of inputs driven by user interactions.Some business processes will begin executing based on an inbound message rather than some direct invocation from within an existing servlet or session EJB. There is a role for flows in message-oriented applications. The flow continues to drive a series of steps that execute a business process. The difference is that the flow is started by an inbound message. In message-based flows, the results of a flow are also often transmitted with messages as well.These basic patterns for flow usage begin to suggest some powerful ways to implement the processes that make up our business model. Beyond an individual organization, flows that span businesses or business units should also be considered. The same basic building blocks apply. A business process that spans businesses is called a public process. Each step in the public process may indeed involve utilizing some of the patterns we have just described.With this set of possibilities in place, the details on the more basic elements that make up the business process programming model can be described. This is the topic of the next section.

Business Process Programming Model Concepts

As we have already seen in the previous sections, there are multiple usage scenarios for flows, resulting in flows of quite different capabilities. The capabilities necessary to support these scenarios are described in this section.

Worklist Handler

Starting from an end user's point of view, a specific user is typically involved in flows implementing various business processes, for example, ordering processes, travel expense processes, production processes, and so on. This involvement results in work assignments (also called work items) for that user being generated by the business process engine during the execution of a specific instance of a business process, and put into the user's worklist. That worklist thus contains work assignments from many business processes, which typically are instances of a number of different business process models that implement different external business processes. To efficiently work with assigned work items, an end user requires the ability to query work items, using appropriate filters and sort criteria. In addition, the user needs the ability to "check-out" a work item (claim exclusive access of the associated activity to work on it), and "check it in" (complete it) again when done with it.

The above requires the existence of a generic business process engine API component (often called a worklist handler API), as shown in the figure. We will talk more about this figure as we go along:

click to expand

It is important to note that this component needs access to work items from all business process instances from all business process models, including the message and document formats that are associated with them. This "global visibility" of work items is achieved by putting them into a shared relational database, which also allows for efficient filtering and sorting (the use of a relational database is encapsulated by the workflow runtime). The business process engine API and worklist handler GUI also support business process-related functions, for example, to start and monitor business processes.

Interruptable Process

A typical business process in an enterprise involves a mixture of people-based steps that are realized by humans checking-out activities, working on them, and checking them back in, and automatic steps that are realized by invoking (new or existing) services.People are associated with the business process flow by means of staff queries against the enterprise directory (or a number of such directories). Typically, these directories contain the organizational structure of the enterprise, including responsibilities described by roles. Staff queries determine which people should be performing the people-based steps in a business process. At runtime, work assignments are created for each person or group of people, and put onto the worklists, as described in the previous section.A particular instance of such a business process runs for a long time, up to weeks or even months. Its execution consists of multiple transactions, which are chained together in a forward recoverable manner, involving transacted messaging. Interruptable business processes, or macro-flows as they are sometimes called, may persist beyond the lifetime of the server process in which they begin execution. If the server shuts down, the current state of the flow is persisted. When the server restarts, the business process engine then resumes execution of the business process instance.For the invocation of operations associated with automatic steps, there are some choices. Most notable is the distinction between asynchronous invocations (messaging-style) and synchronous invocations (RPC-style).Operations invoked on behalf of an interruptable process can be private to the flow in the sense that the particular operation requires specific formats and protocols known only by the specific interruptable processes. Examples of thse types of activities would be staff queries or events specific to the flow. In addition to private operations in a flow, other services are used and reused across different flows. These operations invoked by the interruptable process are most often J2EE-based calls, such as those to a session bean or business rule, or are based on a service interface as expressed in WSDL and done according to the service-oriented architecture described in an earlier chapter.

Non-Interruptable Process

The usage of standard invocation protocols as well as standard message formats is very desirable for enterprise-wide flows. However, existing applications typically require their own protocols and formats. In addition, the granularity of the operations provided by existing applications might be too fine for the actual business operation required in an interruptable process.A non-interruptable process, or micro-flow, can be used to solve these kinds of problems. A non-interruptable process is used to script together a couple of operations, with very little performance overhead. A non-interruptable process runs all steps in the flow in a single unit of work. There is no asynchronous communication done by the business process engine.

As discussed in previous chapters, unit-of-work will normally mean a transaction. However, it is possible that a non-interruptable process could be running in a local transaction or an activity session.

Referring to the figure in the Worklist Handler section, the non-interruptable process exposes a business service interface using the service-oriented architecture or an EJB interface. The implementation involves a series of actions that use private formats, appropriate conversion operations, and existing applications available in the application server as needed. Thus, a non-interruptable process is short running, to the order of milliseconds or seconds, and is enclosed by a single transaction. Operations invoked on its behalf can only be of the synchronous RPC style, hence any service bindings used should be synchronous in nature.Invocation of a non-interruptable process is via fa ades that are generated automatically by the Process Choreography tooling from the signature of the business process. A fa ade session EJB provides a Call() method with the non-interruptable process's signature. A fa ade message-driven Bean (MDB) is also provided, which accepts a JMS message in the correct format for the non-interruptable process, and responds with a JMS message on completion of the flow. Further details on these interfaces will be provided later in the chapter.

Compensation

The compensation pattern supports writing business processes, which automatically run activities in the exceptional case where the business process cannot continue. Compensation processing in business process applications supports "undo" processing for actions taken during execution of a business process, for example, restoring the content of business entities manipulated by the process or performing actions that reverse the result of actions performed in the course of the "regular" process. The compensation pattern has two main ingredients: compensation pairs and compensation spheres.

A compensation pair, as shown above, associates a normal activity in a business process, shown as the Do Action with an Undo Action that can be performed to reverse the actions taken in the original activity. When the compensation pair is invoked during normal execution, it invokes the Do Action. The system then stores information that would be later needed to perform the Undo Action. When the compensation pair is invoked after the process has reached a state where it cannot continue forward, it performs the Undo Action, using the previously stored information.

A compensation example would be a business process involving travel booking where steps in the business process would be to acquire a plane ticket, a car reservation, and a hotel reservation. If the business process achieved acquisition of the plane ticket and the car reservation, but could not acquire a hotel reservation, then compensation would begin. The compensation, or undo, actions would have to get refunds for the purchased tickets, cancel reservations, potentially paying penalties, issue notices, and so forth. Data about the purchased tickets and confirmed reservations would be needed during the compensation to accurately carry out the undo actions.Application developers implementing activities in a flow may define compensation pairs for the actions they implement in the form of operations on business services. Often it is good design practice to design the undo operations while designing a service (for example, place order or cancel order) and design the undo actions for operations on a business service that may be aggregated into another business service. Often, however, business process assemblers will define compensation pairs for operations they use in the context of a business process and collaborate with component providers to implement the services providing the necessary undo operations.A compensation sphere establishes compensation scope and facilitates compensation processing by keeping track of execution status of compensation pairs executed within its scope. The compensation coordinator of such a sphere is informed whenever a compensation pair performs an action in the scope of the compensation sphere and provides a "log" of compensation pairs that need to be involved in compensation processing. When compensation processing is initiated, the compensation executor uses this information to dynamically build the undo process that needs to be executed to compensate actions that had been performed in the compensation sphere. The major pieces involved with a compensation sphere are shown in the following figure:

click to expand

A compensation sphere can encapsulate an interruptable process, which uses compensation pairs as implementations of selected activities. During "regular" execution of the interruptable process, the "do" actions of these pairs are invoked, and compensation pairs store context information and register with the compensation coordinator. When compensation processing is initiated (for example, by a process administrator or due to an exception during execution of the business process model), the compensation executor constructs the "reverse" business process model, which essentially executes the "undo" facets of the compensation pairs that have been executed before compensation processing kicked in.

Comparing how compensation spheres and compensation works to a more traditional two-phase commit global transaction monitor is worth considering. A key difference is that the activities in a process are commited at each step in a process. Furthermore, the "undo" operations often involve activities rather than just rolling back uncommitted changes.

These are the basic flow concepts that are supported by the WAS. These can certainly help to fill out and more quickly create and enrich the business model that we started describing earlier in this chapter.

Creating a Process Application

To better describe and detail the business process capabilities of WASE, a concrete example will be used. This will describe the basic process of creating a business process and become the basis for describing how to unit test and debug a business process within the WSAD-IE tooling. It will also serve as the basis for describing how to start a business process and manage it from the WASE runtime.

Extending PlantsByWebSphere

To demonstrate how to create and run a simple business process application, we will leverage the Plants-By-WebSphere application. Only selected features of the business process capabilities of WASE will be leveraged in the example. Details on some of the additional features will be covered at the end of this section.

The business requirement for the example is to provide an interface that will allow the caller to change the price on items that are sold by the Plants-By-WebSphere business. The requirement is that this interface be provided as a service to ensure that it is accessible from a wide variety of clients. A service in this context is not necessarily a web service, but rather a service in the context of the service-oriented architecture, which was introduced in Chapter 7.

The further requirement states that the application should provide the ability to increase the price on a specified item in inventory by a specified percent. Let's assume we are in the role where we provide any service to those within the Plants-By-WebSphere team, hoping to leverage our catalog capabilities.

The WSDL that represents this basic interface is shown here (we'll create this using the WSAD-IE tooling shortly):

 <?xml version="1.0" encoding="UTF-8"?> <definitions name="PriceUpdateServiceInterface" targetNamespace   ="http://pbwpricing.pbw.ibm.com/PriceUpdateServiceInterface"   xmlns=http://schemas.xmlsoap.org/wsdl/ xmlns:tns   ="http://pbwpricing.pbw.ibm.com/PriceUpdateServiceInterface"   xmlns:xsd="http://www.w3.org/2001/XMLSchema">   <message name="UpdateSingleMsg">     <part name="ItemID" type="xsd:string"></part>     <part name="Percent" type="xsd:float"></part>   </message>   <portType name="PriceUpdaterIntfc">     <operation name="UpdateSingleItem">       <input name="UpdateSingleRequest"               message="tns:UpdateSingleMsg">       </input>     </operation>   </portType> </definitions> 

This interface is completely independent of how it is implemented. Our job is now to implement the UpdateSingleItem operation.

UpdateSingleItem Implemented by a Business Process

After an analysis of existing methods provided by the current Plants-By-WebSphere application, it is decided that a business process can implement the UpdateSingleItem operation being requested.

Here is the simple workflow that will implement the requested price increase:

  1. Input and accept item identifier and percent increase requested

  2. Get price of inventory item

  3. Set price to current price multiplied by the requested increase

Rather than writing a new session bean or session bean method to do this, we will implement the price increase using a business process, leveraging the Process Choreography feature of WASE. However, a review with the business experts indicated that price increases at PlantsByWebSphere are not done automatically today and that all requests for price increases need to be approved. Today this person uses a manual process to approve price increases. In fact, it was suggested that perhaps that person could run this new application rather than having it initiated externally from elsewhere in the organization.

As it turns out, WASE has the facilities to automate this workflow by using a human interaction as part of the business process. Therefore, the business process to be automated is extended to include the following steps:

  1. Input and accept item identifier and percent increase requested

  2. Get price of inventory item

  3. Seek approval for price increase

  4. Set price to current price multiplied by the requested increase

Creating the Business Process in WSAD-IE

This section will step you through creation and implementation of a business process using WSAD-IE.

The basic steps in the tooling to prepare the environment for building our business process are as follows:

  1. Create a new service project

  2. Create the service interface

  3. Create the basic business process

  4. Complete the basic steps of the business process

  5. Add more Java snippets and control flow

  6. Perform additional necessary activities

  7. Generate code

We will now go through each of these steps in detail.

Create a New Service Project (PlantsByWebSpherePricingProcess)

First open the Business Integration perspective, select File | New | Service Project. You will get a screen as shown:

click to expand

Enter PlantsByWebSpherePricingProcess as the project name and click Next. Switch to the Projects tab, and select the PlantsByWebSphereEJB project. This is the name of the project where you have the EJBs that are part of the Plants-By-WebSphere example:

click to expand

This has given us an empty project, pointed back to the project EJBs from which we can begin to fill in the pieces necessary to implement our business process.

Create the Service Interface

In the Services view on the main screen, right-click on the service project PlantsByWebSpherePricingProcess, and select New | Empty Service. The creation wizard will open. Fill in the package name of com.ibm.pbw.pbwpricing and the interface name PriceUpdateServiceInterface and the rest will automatically appear:

click to expand

Click on Finish, and now there is an empty WSDL file ready to be filled in:

click to expand

Click on the Port Types view and add the PriceUpdaterIntfc port and the UpdateSingle operation as shown below:

click to expand

Notice that One-way was selected for the Operation type, from the bottom of the window. This suggests that the caller of the service submits the request and will not get a synchronous response to the request. Since we have added a human interaction to our business process, it will not be happening synchronously. We are building an interruptable business process as discussed earlier in this chapter.

Now select the Messages view and add UpdateSingleMsg to the messages. Then add two parts, ItemID and Percent. Use the Built-in type to give them type xsd:string and xsd:float respectively, as shown:

click to expand

Go back to the Port Types and add the UpdateSingleMsg to the Input part of the screen, using the Browse button, as shown below:

click to expand

Next, go to the Source view and verify that the WSDL source is the same as that shown earlier in this chapter.

Save your work to this point.

The basic interface for the business process is created and is part of the project. The next step is to create the business process that will implement the interface.

Note

This WSDL is independent of business processes and can be created in any convenient way. It does need to be in the WSAD-IE tool, so that we can build the proper service and binding that will implement the interface.

Create the Basic Business Process

With our PlantsByWebSpherePricingProcess service project selected, right-click and select New | Business Process and enter the following:

click to expand

Click Next and the select Use existing WSDL for business process interface. Fill in the Interface file (PriceUpdateServiceInterface.wsdl) by using the Browse button. This is telling WASD-IE which WSDL we will be implementing with this business process:

click to expand

Let's skip the output operation for now, and come back to it later. Click on Finish, and an empty business process will be displayed:

click to expand

We can now go back to our original design of the process and place our activities onto the palette (remove the control link that connects the input and output). Notice that there are two EJB activities and a staff activity. Right-clicking on them allows you to change the label that appears with them on the display. The result is as shown:

click to expand

The basic business process is now on the palette. These activities will remain here throughout the development of the example. We will add some intermediary activities and put details behind each of the activities in the upcoming steps.

One other thing that we should do now before we start more detailed implementation is to mark our business process as 'Interruptible'. Click on the Server view of the business process editor and set it to Run Process as Interruptible:

click to expand

The operation that we created on the PriceUpdateIntfc, was marked as "One-way". This fact, combined with the notation above, which checks the box named Always Run Process as Interruptable, will ensure that this business runs as a macro-flow. A non-interruptable business process or micro-flow would be marked as "Request-response" in the WSDL and correspondingly not check the box above.

Note

During the last two steps, we have followed the sequence that started with a WSDL and then created a business process that implements it. This is one of the many possible paths through the development process. Another possible pattern is to create a business process, and then later create a WSDL interface from that process. Which path is followed is a matter of preference, since each results in the same final outputs. For our purposes, the ability to hand the WSDL off to potential users early in the development process is appealing. We are free to continue to refine the way we implement the WSDL through the rest of our steps.

Complete the Basic Steps of the Business Process

We are now ready to fill in the details behind the steps in our process. We will start with the calls to the EJB. From the process palette, right-click on the first EJB activity (GetPrice). Select Properties, and from that page, select Implementation and start with this empty form:

click to expand

Fill in the class (actually is a EJB method) to be called, by pressing the Browse button. From the list displayed (type the first few letters of "catalog" to narrow the list), select the Catalog interface, as shown here, and click on OK:

Now we find the method to call. Select the getItemPrice() method as shown:

click to expand

Press Apply. This will generate some WSDL messages for you, under the covers.

Now create new variables for the input, the output, and the exception. First choose the Input parameter and then click on New Variable to give you the following default screen:

click to expand

Click on OK and you you will return to the earlier screen with the variable name added:

click to expand

Follow the same steps for the Output terminal and click on Apply.

At this step in the process, we are to call the getItemPrice(String) method on the EJB. We can expect to find a String in the variable named getItemPriceRequest, and will expect to see a resulting float placed into the variable getItemPriceResponse.

We also need to fill in the JNDI: input field with the JNDI name that represents where the EJBs will be in the running system. For our example, fill in plantsby/CatalogHome.

Follow the same pattern for SetPrice EJB activity. The completed implementation form for the setItemPrice call should look like this:

click to expand

Filling in the GetApproval staff node is the next task. So far, we have variables in our business process that handle the requests and responses from the EJB calls:

click to expand

Note

Before moving on to create the variables that our staff node will use, we may need to update the input variable. If it's already set to type UpdateSingleMsg as above then you're OK. If not, use the Modify button and set the variable type to External, pointing at PriceUpdateServiceInterface.wsdl.

What we need now is a variable to feed into the staff activity. We can assert that none of the existing messages has enough data to be used as the type for this message. We need to send in a new variable to the GetApproval step in our business process, and send the current price of the item, the item ID, and the requested increase. Whoever is going to "approve" or "disapprove" the price increase request needs all the available data from which to make the decision. This data is available from the various variables that we have and can be pulled together into a getApprovalRequest variable. First, we need a variable so we will need to define a WSDL message from which we can get a Java type for this variable.

This is our first variable that is not created for us by the system. To create a variable, click on File | New | Empty Service. Fill in the details as shown below:

click to expand

Once it is created, we can select this file and add our message. Under the Messages view, add the getApprovalRequestMsg with an itemID (xsd:string), existingPrice (xsd:float), and increasePercent (xsd:float) parts:

click to expand

Save, so the new message can be used.

Now we can create a variable, leveraging our new message, to be used by our staff node for input. This means we go back to the process and select the staff node, bring up the Properties menu as before, and select the Data node and add a new variable for input as shown here:

click to expand

Similarly create a getApprovalResult variable for the output and assign it the default Boolean type. After that you should get the following screen:

click to expand

Now we have a variable to feed into the GetApproval step. Next, we need to add a small piece of Java code to prepare that input. This input needs to be gathered from the available data at this step in the process.

Add a Java snippet to the canvas with a label, prepApprovalReq. Then add the control links as shown:

click to expand

A Java snippet is a piece of Java code that can be used to glue various pieces of the business processes together. For our example, we need to get the three pieces of data from the various variables that already exist to place into the new variable we just added. Fill in the Java snippet by selecting the Java snippet from the canvas, and then press the Show Java button. You will get in a window like this:

click to expand

Writing this snippet of Java code is relatively simple. We have a constrained environment where we work with the Java types for the WSDL messages and assign the next variable in the business process to the values from the previously set variables. The code to fill into the snippet is shown here:

public void javaSnippet_6 () throws com.ibm.bpe.api.ProcessException {     //user code begin {Java Snippet Activity}     //get a copy of the message we are going to fill in     GetApprovalRequestMsgMessage msg = getGetApprovalRequest();     //grab first piece of data from existing variable     float existingPrice = getGetItemPriceResponse().getResult();     //grab 2nd piece of data from original input     float increaseAmt = getInput().getPercent();     //grab 3rd piece of data form original input     String itemID = getInput().getItemID();     //now set this data into our copy of the mesage     msg.setIncreasePercent(increaseAmt);     msg.setExistingPrice(existingPrice);     msg.setItemID(itemID);     //put the message back into the global data area     setGetApprovalRequest(msg);     //user code end   }

The number of the snippet you create (javaSnippet_6) may vary based on other actions you have already performed in WASD-IE.

Remember that the variables are stored between steps in the process and are available when needed throughout the process. Our job is just to keep the right data going into each step in the process. The WSAD-IE tool is good at helping us along the way. Whenever you are working in the Java editor, you can press Ctrl-Space and see a list of choices that match the type you are working with. This helps expedite the snippet coding process.

Make sure there are no syntax errors in the Java snippet. WSAD-IE helps you do this with an added tool. Right-click on errors in the snippet and use the options available in the context menu such as, Open Declaration, Search, and so on, to help work your way through this process. Depending on exactly how you created the artifacts, additional imports might be necessary. For our example, you might see an error message about GetApprovalRequestMsgMessage. That was the message we defined in a separate WSDL file earlier in this step. There should be an error message in the Tasks pane as shown below.

click to expand

Right-clicking should provide an option of Quick Fix to get the proper imports set up. Save the changes and ensure that the error has gone away. If not, right-click on the offending text and choose Source | Organize Imports.

We can now complete the staff node in our business process. Right-click on the GetApproval activity, and from the Properties menu, select the Staff option, as shown:

click to expand

This is where we can assign these staff activities to specific users. Select Potential Owner and click on Change. The menu that comes up lets us decide who should be performing activities in this business process.

We can assign work items for staff activities to individual users, groups, specific roles, and so on. This selection will then transform into a specific query against a staff plug-in. A staff plug-in is something we will see later when we test this business process at run time.

For our example, we will assign the Potential Owner role. Now all approvals must go through someone that has this user name, TestId1, in the system. Queries that are more complex can be described here. An example would be enabling anyone from a given department to perform the approval:

click to expand

This completes the specification of the staff activity. Make sure you save your work at this point.

The main activities in our business process are now filled in. The next steps are to glue together the remaining activities.

Add More Java Snippets and Control Flow

At this point in the process, the major pieces of the business process are created. What we need next is a few more Java snippets. They will perform the transformations that get the data to the various steps in the process.

The completed process, as far as control links goes, is shown here:

click to expand

The prepGetPriceReq snippet needs this code:

public void javaSnippet_7() throws com.ibm.bpe.api.ProcessException {     //user code begin {Java Snippet Activity}     //get a copy of the message we are going to fill in     GetItemPriceRequestMessage msg = getGetItemPriceRequest();             //get value from input message     String internalItemID = getInput().getItemID();     //set value into message     msg.setInventoryID(internalItemID);     //set message back into business process     setGetItemPriceRequest(msg);     //user code end   }

The prepSetPriceReq needs this code:

public void javaSnippet_8() throws com.ibm.bpe.api.ProcessException {     // user code begin {Java Snippet Activity}     //get a copy of the message we are preparing     SetItemPriceRequestMessage msg = getSetItemPriceRequest();     //get values we need from existing variables     float existingPrice = getGetItemPriceResponse().getResult();     String itemToUpdate = getInput().getItemID();     //set values into message     msg.setInventoryID(itemToUpdate);     //make new price calculation and set result into price     msg.setPrice(existingPrice * (1 + (getInput().getPercent() / 100)));     //put the message back as we are ready     setSetItemPriceRequest(msg);     //user code end   }

Notice the line here where we actually calculate the new price by taking the existing price and doing some multiplication. Other than that, these snippets are taking data that is available in the variables of the business process and getting the right subset of that date to the next step in the business process.

There is one more piece of business logic to consider. If the result of the staff activity is that this price increase is not approved, then we need a path through the business process that will indicate this.

To specify how the control flow after GetApproval should proceed, we need to right-click on the control arrow that goes between GetApproval and prepSetPriceReq. The Properties option should bring up the following display that should be changed as shown:

click to expand

Our condition will be described in Java code. Go back to the main screen and select the same control arrow and we will now see the opportunity to put in some Java code.

The calculation is simply based on the result of our GetApproval step. Place the following code in the Java editor:

public boolean controlCondition_FlowNode_5_out_FlowNode_9_in()     throws com.ibm.bpe.api.ProcessException {     boolean result = true;     //user code begin {Condition Expression}     result = getGetApprovalResult().getValue();     //user code end     return result; }

The other control link coming out of GetApproval, which currently goes to Output, needs to be set to otherwise, from the Properties menu, as this is where the business process will proceed if the condition does not evaluate to true. Think of the set of control conditions as a case statement where the true condition is checked first. The change can be made as shown:

click to expand

We have only a few more steps to follow to complete our business process.

Perform Additional Necessary Activities

The basics are in place for our process. We need to deal with the business process output and we will be done. The output of a business process that is executed asynchronously also uses a service. What you place underneath this service is pretty much up to you, and probably something that you want to tailor for testing versus what you might want in production. For our simple business process, the desire is to print the ID of the product, the new price, and whether or not the price increase was actually done. This will come out in the console when the business process is executing.

To simplify the process of building this output handler, we will first create a simple Java class. With our project selected, select New | Java | Class, and press Next. Fill in the name of the class as PricerOutput as shown below:

click to expand

Press Finish and a basic Java editor will open up. Fill in the code as shown:

package com.ibm.pbw.pbwpricing; public class PricerOutput {   public void PricingComplete(String itemID, float newPrice,        boolean approved) {     if (approved) {       System.out.println("Price uncrease approved");       System.out.println("ItemID is:");       System.out.println(itemID);       System.out.println("New Price is: ");       System.out.println(newPrice);     } else {       System.out.println("Price increase disapproved");       System.out.println("ItemID is:");       System.out.println(itemID);     }   } }

Now we can build a service from this class to get the output from our business process. With our PricerOutput.java selected, right-click and select New | Service built from:

click to expand

Press Next and then select the class and method as shown here:

click to expand

Press Next and then arrive here:

click to expand

All the default values should be correct and just what we want. Click on Finish and we have now built a service from the Java class, complete with a binding that is ready to use.

Now we can go back to our process and select the Output terminal. From there, we go to the Implementation node from the Properties menu, and fill in the name of the operation that we want to have executed upon completion of our business process. Using the Browse button, pick the new PricerOutput service WSDL file as shown below:

click to expand

Press OK and this should bring us back to the implementation for Output:

click to expand

Fill in the rest of the details as shown. As a side effect of this activity, we now have a type for our output variable. You can look at the variables now and you should see the output variable to be of type PricingCompleteRequest.

Note

In the case of handling the output, we chose the model of bottom up, where we prepared a Java class and then built a service from this Java class. It is also possible to build this service by starting with WSDL and then generating an implementation from the WSDL. This is a matter of choice. In fact, you might have a different service at the end of a business process when it is in production versus when it is in unit test.

As with any activity that is going to be executed, the input to that activity must be prepared. Another Java snippet will help us do that, so we add in prepOutput:

click to expand

As you can see, we have wired both of the control flows to this snippet before proceeding to the output. Make sure you graphically change the control links. If you do remove the control link between GetApproval and Output and reestablish a new one between GetApproval and prepOutput, then you will have to go back and mark it as "otherwise" as was described earlier.

The code to fill in this snippet is:

public void javaSnippet_9() throws com.ibm.bpe.api.ProcessException {     //user code begin {Java Snippet Activity}     PricingCompleteRequestMessage msg = getOutput();     //get values I need to fill in the blanks     boolean approved = getGetApprovalResult().getValue();     float newPrice = getGetItemPriceResponse().getResult();     String itemID = getInput().getItemID();     //set values into message     msg.setApproved(approved);     msg.setNewPrice(newPrice);     msg.setItemID(itemID);     //put the message back as we are ready     setOutput(msg);     //user code end   }

We have completed the hard part of creating a business process. Now we have to generate the deployed code, and unit test and debug this business process application. Make sure you save your work.

Generate Code

We have completed our process creation. Right-click on the PBWPricingProcess1.process file and select Enterprise Services | Generate Deploy code. Select EJB for a binding type as shown:

click to expand

Press Next. Take the defaults on this page:

click to expand

Then make a note of this string on the next page:

click to expand

Click on Finish.

Note

We chose the session EJB for our inbound binding. There are three inbound binding choices; Session Bean, JMS – Message-Driven Bean, and SOAP. We will come back later in the chapter to describe the bindings that exist for business processes.

You now have what you need to run in the unit test environment. Select the project and use Export to export the PlantsByWebSpherePricingProcessEAR. This will provide you the artifact you need to install the application into the WASE runtime.

Unit Testing a Business Process Application

The WebSphere Studio Application Developer has a rich unit test environment for testing J2EE applications.

WSAD-IE builds upon that base and provides a unit test environment as well. The WSAD-IE test environment allows testing of applications that leverage WASE features as well as all of those supported by the base application server. The WSAD-IE unit-test environment provides the ability to directly unit-test business processes, like the example we created in this chapter.

Runtime and Administration Integration

The exported EAR file from the previous section is nearly a regular EAR file as defined by J2EE. The only thing that is different is that there are artifacts in the EAR file that will be handled by the business process infrastructure during run time.

Before installing the EAR file with the business process in it, the runtime should be properly configured. Other than the normal configuration in the application server, we need to concern ourselves with the business process execution container and the staff plug-ins.

Configuring the Business Process Execution Container

There are three ways to configure the business process execution (BPE) container:

The first way is to configure it during WAS Enterprise installation. This option will create a business process execution container that leverages Cloudscape and the Embedded JMS Provider that ships with WAS. Choose this option if you are going to be testing business processes in a single-user environment:

click to expand

This is found under the custom install option of WebSphere Application Server Enterprise 5.0.

The second method is to use the administration console. Expand the Servers tree in the navigation tree on the left, open the Application Servers link and select your server's link from the main pane and then scroll towards the bottom of the various additional properties, and you will find Business Process Container as shown:

click to expand

Click on Business Process Container and you will get the following screen:

click to expand

Here you can choose your JMS provider and the queues to be used. You can also choose the database that you want the business process container to use. Various security settings for JMS can also be entered at this point. To install the container, add a JMS user and password and hit the Install button. Note that once you've installed this you can't change any of the values again.

The final path that can be used to install the BPE container is via a jacl script, which ships as a sample. Look for the bpeconfig.jacl in the ProcessChoreographer\samples directory in your WebSphere installation. This script is invoked using the standard wsadmin model:

 wsadmin –f bpeconfig.jacl 

The script leads you through a series of choices about how to configure the container. Choices about which JMS provider and which database to use are key prompts in the script.

Configuring the Staff Plug-In

Before configuring the staff plug-in, go back to WSAD-IE and look at the properties for PlantsByWebSpherePricingProcess service project, and select the Staff node:

click to expand

The JNDI name shown for the staff plug-in configuration above is what we need to make sure exists in the runtime environment. This is what links the output of the tooling during run time. For our example, we will use the defaults. A default staff provider for the user registry is provided.

The first screen shows the definition of the staff provider. This includes the name of the plug-in file that is going to execute those staff queries, which we placed into our business process. In our case, we are going to execute those queries against the user registry on a Windows 2000 machine.

click to expand

The second screen, shown next, shows the name of the transformation file that will be used to convert the staff queries into something that can be executed by the underlying staff provider:

click to expand

Notice that the JNDI name in the second screenshot matches up with the one shown in the WSAD-IE project page shown earlier.

The Staff Support Service component acts as an intermediary between Staff Queries as defined at application development time and the actual directory infrastructure of a production application server.

Specialized staff plug-ins provide access to specific directories such as LDAP directories or the UserRegistry. They are used to implement abstract staff query verbs for a given deployment environment.

When a business prcoess is deployed, the JNDI name of a specialized plug-in is provided as a deployment descriptor variable. During the business process deployment, the internal Staff Support Service component is invoked to deploy a particular staff query. It converts the staff query extensibility element using a verb conversion XSLT.

Predefined Staff Query Verbs are provided in the context of flow tooling and are utilized by the Staff Support Service component. Each verb defines an abstract Staff Query that can be defined without knowledge about the specific directory infrastructure. The predefined "verbs" used are:

  • User

  • Group Members

  • Department Members

  • Role Members

  • Manager of Employee

  • Person

  • Group Search

  • Native

    Important

    Note, while running business processes that leverage staff support, global security on WebSphere needs to be turned on.

Install Business Processes

Installing business processes into the BPE container happens when you install an EAR file. There are no special steps. You can install business processes using wsadmin, the administration console interface, or in any other way that works for you. During any of these, the business process deployment tools will be called transparently as part of installing the J2EE application. Follow the installation instructions described in Chapter 6 to upload our PlantsByWebSpherePricingProcess.ear file.

Testing Business Processes

Once you have got the business process installed, you can use the web client to help test and manage business processes. However, before we can do this we need to make sure we set up the correct permissions and user for the process. Recall that we set the potential owner of the GetApproval process to TestId1, and that the Staff plug-in user registry was just going to be the local OS registry.

Therefore, when we use the BPE web client, we need to log on with the correct user and permissions to be able to approve the process. To do this we first need to create a new user in the local OS. For Windows 2000 this is condigured through Administrative Tools | Computer Management:

click to expand

You also need to give this user additional operating system privledges (Act as part of the operating system). This can be set through the Local Security Policy Administrative tool.

Now make sure the security is enabled for the server – refer to Chapter 13 for more details on how to do this.

The BPE web client is located at http://localhost:9080/bpe/webclient. The webclient is intended primarily to enable application developers to easily test business processes. You will first be prompted to log in. This will determine the user and thus if you have permission to control any of the processes. Log-in as TestId1.

A default initial screen is shown next:

click to expand

From this client we can create a new instance of a business process by selecting the template and clicking on Start. Our screenshot has the default choice shown, as it is the only one on the server being used. From here, we will move on to a screen like this:

click to expand

Next, we can actually start the instance of the business process. After entering valid values for the ItemId and Percent that are desired, and then starting the business process, we are lead to a blank My To Dos screen. Refreshing the My To Dos link again, shows our process:

click to expand

We are interested in the new one that is ready. If we click on it (GetApproval), we are lead here:

click to expand

We can claim the activity and then decide if we are going to "approve" this price increase. After pressing Claim Activity, we are brought to the following screen:

click to expand

We mark it to true, to approve the price increase and then can complete the activity. We could temporarily save our choice, but not complete the business process. However, we can to complete this activity and see if it ends properly. After pressing Complete Acivity, we are lead to:

click to expand

This means that we have completed our workitem and there are no more workitems at this time.

That was a quick tour through configuring the runtime and running business processes in the runtime. The combination of the admin console and the web client for business processes let us easily manage business processes in the WASE environment.

Debugging a Business Process

It is possible that your business processes will not all work the first time you try to execute them in the unit test environment or in the runtime. Debugging business processes can be done using the same debuggers that are used for debugging other J2EE programs in WebSphere. However, in addition to these more traditional debugging capabilities, WSAD-IE comes with a business process debugger. This allows business processes to be debugged at a level of abstraction similar to that used while constructing the business process. The business process debugger is shown below:

click to expand

As you can see from the display, debugging takes place at the process level. A breakpoint is set between the Input activity and the prepGetPriceReq activity. From a breakpoint, one can inspect the current values of the variables in the business process. Notice that all of the views available when you develop a business process are available on the debugger, acting as the source for the business process you are debugging.

Basic navigation through the business process uses a series of capabilities to Run the Process, Step Into an activity, Step Over an activity, Step Out of an activity, or Run to Completion. These options are available as icons in the Process Debug window.

These capabilities for debugging processes will let you find problems such as:

  • Incorrectly wired activities (for example, outputs connected to the wrong inputs)

  • Incorrect condition branching in transition conditions

  • Infinite loops in processes

These debugging capabilities become more valuable as processes that are more complex involve sub-processes and complex conditions are built.

If you need to drop into source code level debugging, it can be done at any point in the process using Step Into Source Code and Step Over Source Code facilities, which are available as icons in the Process Debug window.

This debugger will work against an application server that is part of the unit test environment or against any application server that is configured and running on the machine. There is a specific port on the application server and debugger agent process that coordinates the interactions between the debugger interface and the application server. The application server must be configured to run with debug turned on.

Instructions that are more complete are provided with the WSAD-IE help text.

More Process Choreography Support

There is still more to Process Choreography support in WASE. Going into more detail would be beyond the scope of this book. Some of the additional capabilities are summarized here.

Interfacing with Business Processes

In our example, we generated an EJB for our business logic and used a web client to test out our business processes. The web client that was used to test our business process is not intended as the way that production applications will access business processes. Custom-written applications will be created that deal with workitems and handling the initiation and lifecycle of business processes.

In addition to the web client, the WSAD-IE tooling will generate three interfaces to a business process. In addition to these generated artifacts, there is a more direct interface to the business process engine. In total then there are five ways to easily access business processes:

  • Web client

  • EJB generated by WSAD-IE

  • MDB generated by WSAD-IE

  • SOAP interface generated by WSAD-IE

  • Direct interface to business process engine

These will be covered one at a time with the exception of the web client, which we have already covered in detail earlier.

  • EJB generated by WSAD-IE
    When you select the EJB option, a session bean is generated that can then be called from anywhere in the J2EE server or from any J2EE client. The session bean interface for our example is shown below:

     public interface PriceUpdaterIntfcService extends javax.ejb.EJBObject {   /**   /* UpdateSingle   /* @generated   */   public void UpdateSingle(java.lang.String argItemID, float argPercent)     throws javax.ejb.EJBException, java.rmi.RemoteException; } 

    This EJB has an internal implementation that handles the necessary interactions with the business process container. The implementation is obviously different if a non-interruptable business process is called as opposed to the launching of an interruptable business process.

  • MDB generated by WSAD-IE
    If we want to launch our business process by sending a JMS message, then we can use this option, which generates a message-driven bean (MDB). Our example business process generates the following MDB interfaces:

     /**    * onMessage    * @generated    */   public void onMessage(javax.jms.Message msg) {     try {       executeFlowOperation(msg);     } catch (WSIFException e) {       e.printStackTrace();     } catch (javax.jms.JMSException e) {       e.printStackTrace();     } catch (ProcessException e) {       e.printStackTrace();     } catch (javax.naming.NamingException e) {       e.printStackTrace();     } catch (javax.ejb.CreateException e) {       e.printStackTrace();     }   } 

    This is a normal onMessage() method in terms of signature, like that which we would expect to find on any MDB. The implementation has the interesting call to executeFlowOperation() method. This calls a number of other methods internally and handles the calling or initiation of the business process. All you have to do is configure the MDB as part of the business process application, and you can send a message to start a business process.

  • SOAP interface generated by WSAD-IE
    The SOAP interface merely creates a SOAP binding and service for our original WSDL file named PriceUpdaterIntfc. There is nothing special about this, as it is normal web services capability being leveraged.

  • Direct interface to business process engine
    The implementation of the MDB and the EJB session bean interfaces to the business process, are all using an interface from the package com.ibm.bpe.api. This package has some key interfaces in it that can be called directly from any Java code that has access to the application server and can call session beans. The com.ibm.bpe.api.BusinessProcessService interface is actually another EJB Session bean that wrappers all of the capabilities that one might want to use in calling, initiating and working with business processes. Some of the key methods on the BusinessProcessService interface are listed here:

    • call()
      Creates and executes a process instance from the specified process template. This is how to start a non-interruptable business process.

    • claim()
      Claims a ready activity instance for user processing.

    • complete()
      Completes a claimed activity instance.

    • delete()
      Deletes the specified top-level process instance and its sub-processes from the database.

    • getWorkItems()
      Retrieves workitem assignments for the specified process instance or activity, depending on which variation of the method is used.

    • initiate()
      Creates a named process instance. This is how to start an interruptable business process

    • query()
      Retrieves selected object properties persistently stored in the business process container configuration database.

    • sendEvent()
      Sends the specified event to the specified process instance.

Many of these methods have multiple signatures. You are encouraged to consult the Javadoc that accompanies WASE for more details.

Activity Types

In addition to the staff nodes, Java snippets, and EJB calls that were described in the preceding example, other things can be called as part of an activity implementation. These include:

  • Services
    According to the service-oriented architecture, anything that can be expressed as a service can be invoked. This would include calls to external web services, JavaBeans, and JMS calls. The JMS activity in an asynchronous process is worth detailing. If an activity makes an asynchronous JMS call via a service, the business process engine will wait for a response to be received on a reply-to queue, before proceeding to the next step. This pattern fits well into the asynchronous style of long-running business processes.

  • Process
    It is an activity that represents a separate business process that is being invoked within a larger one. Unlike the Block activity, the Process activity is a complete process, and can exist on its own outside the primary process, and is used by other processes.

  • Events
    The Event activity represents an activity in the business process that waits for one or more external events to happen before continuing. These external events come in through interfaces to the business process via the EJB session bean. We would have seen more methods on our example session bean presented earlier if we had used Events in our business process.

  • Blocks
    These constructs let you build more complex business processes. Looping is a distinct activity that you create as a subset of your primary process. The loop will repeat the activities within it as long as the condition within it remains true. This is also known as a "while-do" loop. When a false condition is encountered, the loop is exited, and the next activity in the process is executed. Use the Block activity to simplify your diagram by decomposing your process into individual distinct portions; each representing an entire nested business process that runs within a larger one.

  • Loops
    This activity is a specialized form of a Block that can be iterated so that the operation executes more than once during the business process. The execution of the loop is controlled by a conditional expression, and will continue to execute as long as this conditional expression evaluates to true.

  • Empty Activity
    An empty activity has no defined implementation and can be used for two reasons; it can act as a placeholder in the design stage to be filled out later, and it can be used when a fault needs to be caught and suppressed.

Compensation

Within the Service activity type is yet another kind of service. This is known as a Compensation. The properties panel for a service is shown here:

click to expand

As you can see, there is a compensation selection. This means that for every service that is invoked, a corresponding compensating service can be registered. This means we can register two services for each service icon on our business process.

A "compensatable service" enables compensation for the operations of a primary service, by associating the primary service with an appropriate compensation service. A compensatable service is invoked from within a compensation sphere that has been created by the business process container. When a compensatable service is run, it runs a primary operation and registers information with a compensation coordinator to enable compensation if required. Then, if the business process cannot continue forward, all the registered compensating services are executed.

The use of compensation in business processes is shown in the following figure:

click to expand

This figure shows a business process that calls several actions, some of which use operations of compensatable services. Each compensation pair runs its primary operation then registers with the compensation coordinator, creating a proclet to be used if compensation is needed. When a business process is started, it creates a new compensation coordinator to start a compensation sphere.

Each compensation pair called as a node of the business process registers with the compensation coordinator, runs its primary operation, and stores the information needed to run its compensation operation if the business process needs to be compensated.

A fault node that is reached at a top-level process (not a sub-process) will cause compensation to be executed. The compensation service invokes proclets in reverse order of the time when their primary services completed.

This completes the description of workflow capabilities within WASE.

Business Rules

The concept of dynamic business policy management is a key feature of WASE. This capability further enhances our ability to implement and maintain business models, with a strong emphasis on maintenance.

Various business policies or rules need constant changing based on external forces such as economic trends. Some examples are pricing algorithms and customer classification into categories for determining customer status, purchase discounts, and so on. Government regulations also change frequently, sometimes back and forth, for things such as tax rates and retirement ages.

Many of these dynamic and policy-driven business processes, which are implemented using application server features, depend on data-driven algorithms. These implementations must be able to cope with the often-changing requirements that are typical in normal business lifecycles. The Business Rules facility, also known as BRBeans, provides a framework for managing this kind of dynamic business logic.The primary objectives of BRBeans include:

  • Isolation of volatile business logic from application code
    Business logic and application code are implemented separately. Any J2EE application component can leverage business rules. This includes servlets, J2EE clients, and EJBs. Business rules themselves must be implemented as Java classes. Application code interacts with business rule implementations exclusively through well-known interfaces, which maintains this important abstraction.

  • Keeping knowledge of business rule implementation external to the application
    Variable business rule data is not embedded in the application calling rule and can be easily accessed with the Rule Management Application. More details on the Rule Management Application will come later in the chapter.

  • Administrative maintenance of business logic
    Application behavior can be changed through an administrative process using the Rule Management Application or applications customized for specific business users. The Rule Management Application and application-specific management applications can modify business behavior in two ways:

  • By specifying a different rule implementor for a BRBeans rule

  • By changing variable business rule data

The rest of our discussion on rules will demonstrate these benefits and provide details on how to leverage the rules capabilities in WASE.

The Role for Rules

Rules provide us with an additional option when implementing business logic. Refering back to the earlier discussion about application structure, there are actually a couple of places where rules can plug in. The most obvious requirement for rules-based capabilities comes in implementing the business model, independent of the presentation logic. The business model is the point in the application architecture where business logic and decision making is occurring. A modified application structure is presented to provide a view as to where rules fit in. It is expected that rules either will be called from session beans within the business model or potentially be accessed directly from the presentation layer applications.

While it is also possible to have rules used to provide a customized view or presentation, our focus in this chapter will deal with rules and how they are used in business logic. The WebSphere Personalization product, which runs on top of the WAS, actually uses the same underlying infrastructure and mechansism as is described in this section. WebSphere Personalization focuses on customized views and presentations.Rules provide us with a vehicle to separate and independently manage pieces of business logic. Rules can and should be applied in the application architecture in places where business policy is represented in code. If there is a reasonable chance that the business policy can change and a way to create an abstraction of that policy exists, then rules should be considered. One example that we will use periodically in this section is classification of customers into categories such as silver, gold, and platinum, to determine things such as discounts and benefits received. Data that can change might be the threshold of purchases that would put one into the next category. Algorithms that might change could be how the calculation is done. Maybe we give "double counting" during certain times of the year. This is similar to how an airlines changes the way it calculates its frequent flier miles.

In fact, it is often the case that there are a number of rules that apply to do proper classification. Again, in a commercial or retail setting, some times of the year or of a business cycle might require more rules than others to determine how to proceed with the rest of the business logic.

Before diving into the rest of the concepts and details of rules, let us go into some development process thinking. Should rules be created first in the development process and then leveraged as business processes or implemented as part of the business model? Should existing applications be re-engineered to take advantage of rules?These are questions that do not have a universally correct answer. However, if your organization has a growing set of reusable assets being constructed, then using rules as an architectural factoring mechanism is a true possibility. Just as reusable entity beans and reusable session beans, each with proper interfaces, can be built up over time, a set of reusable rules can be a valuable asset. Rules, and more precisely the rule implementations, are fine-grained reuse opportunities. It may be the case that only higher-level components are the reuse objective and if so, then rules can be considered in the role of implementation technology.As an implementation technology, rules are about creating flexible applications, where behaviors can be altered at run time, thus avoiding redeployment.Who changes the rules or the rules data in a system that leverages Business Rules? It is possible that rules can enable a non-programmer class of users to actually alter the behavior of the system. While users can alter system behavior today by providing alternative input data to a running system, rule-based systems allow applications to evolve and respond not only to different data inputs, but to an evolved set of business logic as well. This idea of having a non-programmer changing the behavior of the application in this way is a new "role" or at least an enhanced role. The idea that these kinds of changes can occur without a request to the application development team is appealing. On the other hand, it suggests strongly that the interface used by these non-programmers must be carefully designed and contain rich validation code.The complete set of possibilities for rules will perhaps become clearer as we dig into the concepts and learn more about creating and deploying rules and applications that leverage those rules.

Rule Programming Concepts

Leveraging the Business Rules support in WebSphere is a simple process. We need to understand a few key concepts before the process of using, creating, and modifying rules can begin. The key concepts to understand are trigger points, Rule Management, Rule Implementor, and the business rules infrastructure that pulls it all together. The following diagram provides a big-picture view as to how these pieces fit together:

click to expand

Rule Client and Trigger Point

Let's start with a J2EE application that wants to take advange of rules. The first thing to do is to find the places in the application that have code segments that are desirable to factor out into rules. Trigger points are placed in the code at these points instead of the application logic that is being factored into a rule. A trigger point is the place where the call is made into the rules infrastructure.Underneath the trigger points is the trigger point framework. This framework provides a link to the Rule Infrastructure. The trigger point framework takes the client request and sends it into the infrastructure where the Rule Implementors are selected and executed, and where the results are formulated and formatted. This might sound like a lot of work to do just to execute some business logic. The BRBeans infrastructure also has inbuilt caching. A cache of rules is kept locally, avoiding doing costly rule lookups repeatedly. An administratively controlled setting indicates the frequency of cache refresh.

Part of the trigger point framework involves something called strategies. A strategy, in this context, is a mechanism to control the process of triggering a rule, or set of rules. We could assert that these are rules that effect how rules are found, filtered, fired, and combined, but that would further overload the "rule" term. When a trigger point is called, four kinds of strategies are used for customization and modification; they are:

  • Finding Strategy
    This strategy controls how the rules are found. The default finding strategy chooses active rules, where the current date is in between the start and end dates of the rule. A precedence setting is used to determine the order in which the rules are returned. Precedence is set using the Rule Management Application. The highest precedence is the lowest value. We will describe the Rule Management Application later in the section entitled Configuring Rules. For now, it is sufficient to know that the Rule Management Application is a utility that comes as part of the BRBeans support in WebSphere, and is used by those managing applications that leverage rules.

  • Filtering Strategy
    The filtering strategy lets the rules that are found be filtered before firing. A finding strategy can sometimes return many rules. It may or may not be desirable to fire more than one rule for a given trigger point. The values that can be set for the filtering strategy include:

  • Accept Any: Use all rules returned by the finding strategy

  • Accept One: One rule is expected to be found

  • Accept First: Only the first rule found by the framework will be fired

  • Accept Last: Only the last rule found by the framework will be fired

  • Combining Strategy
    The combining strategy provides different ways to handle rules' results. The values possible here are:

  • Return All: The results of all fired rules are returned

  • Return First: The result of the first rule fired is returned

  • Return Last: The result of the last rule fired is returned

  • Return AND: The results are combined based on the logical AND operator

  • Return OR: The results are combined based on the logical OR operator

  • Throw Violation: Returns a true if all fired rules are successful

  • Firing Strategy
    This strategy determines the order in which rules are fired and the parameters that are passed to each one. The default firing strategy fires the rules in the same order in which they are returned, passing in the same set of parameters to each rule.

Custom strategies can be created if the defaults provided are not what are desired for a particular application or set of applications.

Rules and Rule Implementors

BRBeans supports two kinds of rules: classifier rules and base rules. Classifier rules return a classification based on the rule logic and available data. Classifier rules can be used to determine the ways in which variables are classified, and are returned in the form of a java.lang.Object, which is often just a java.lang.String. Classifier rules are triggered with the TriggerPoint.triggerClassifier() method.

A classifier rule is used to compute a classification for a particular business situation. The classification returned is required to be a String. For instance, a Plants-By-WebSphere customer may be classified into Gold, Silver, and Bronze categories, based on their spending history.Base rules are the most common type of rule used, and are triggered with the TriggerPoint.trigger() method. Base rules return java.lang.Object. There are a number of base rules:

  • Derivation rule
    A rule that uses an algorithm to return a value. It can return any type of value that makes sense in the business context in which it is used. For example, a derivation rule may calculate a discount or compute the total price of an order.

  • Constraint rule
    A rule that confirms that an operation has met all of its obligations, and that a particular constraint has been met. For instance, it may check that a value entered by an external user is within legal bounds. BRBeans provides a special return type: com.ibm.websphere.brb.ConstraintReturn, which can be returned by the constraint rule. A ConstraintReturn object contains a Boolean value, and if it is false, it can contain information that can be used to produce an external message explaining what constraint was not met.

  • Invariant rules
    A rule that ensures that multiple changes made by an operation are properly related to one another.

The state of a rule in the infrastructure is what determines if it can actually be used at run time by a client. Rules can have one of five states:

  • In effect
    This means that the BRBeans rule is active and is available for use. This is the state a rule needs to be in so that it can be fired.

  • Scheduled
    This state indicates that the rule is set to be in effect as some future date.

  • Expired
    This state means that the rule is no longer active and has no future time set for it to take effect.

  • Invalid
    This indicates that there are configuration errors in the rule.

  • Unavailable
    This state means that the rule is not ready for use.

BRBeans can also be configured with a firing location. A local firing location tells the infrastructure that the client and the Rule Implementor are in the same server. This information allows the infrastructure to make optimizations. It is configurable via the Rule Management Application. BRBeans Rule Implementors are Java classes that provide implementation for the business logic that can be factored out of the application and placed under the management of BRBeans.

Rule Infrastructure

The Rule Infrastructure pulls together the clients that have trigger points and the implementations of rules. The Rule Infrastructure is the rest of the implementation code that makes up the BRBean's implementation in WebSphere. It has the basic machinery for holding the configuration information. It has the logic for executing the strategies that come into the infrastructure through the trigger point framework.

Management Client and Tools

The Rule Management Application is a tool that comes as part of WASE. It is used for administering and maintaining BRBeans rules. The tool is an interface into the Rule Infrastructure. It allows the browsing and modification of BRBeans rule configuration data such as rule name, implementation class, start and end date, and initialization parameters.This application is primarily used by developers to test rules and applications that are leveraging rules. End users are unlikely to use this tool.However, the programming interfaces used by the implementation of the Rule Management Application are also available to be used by developers to build custom Rule Management Applications. These are standard Java and J2EE interfaces. One of the key benefits of business rules is the ability to turn over the management of rules to the business people who know more about what they want to change and when they want to change things. Obviously, exposing these capabilities must be done carefully and opening up control of the entire rules environment is not something that would be commonplace. It is expected that specified business situations will require specific pieces of the rule environment to be exposed. Therefore, programming interfaces are provided so that custom applications can be built.The Rule Management Application allows the import and export of rule configuration data as XML files. This can be used to move configuration data between various servers in an organization.

Summarizing Rule Concepts

The development process for leveraging business rules involves deciding on trigger points in the code and then ensuring that the necessary Rule Implementors are available. Once these two components are in place, then testing of the application can take place. The Rule Management Application facilitates configuration and testing of BRBeans applications.The run-time flow for a rule-enabled application is as follows:

  1. Client code triggers the rule infrastructure passing in parameters to be used by Rule Implementors.

  2. Rule Infrastructure decides which rules are to be fired for the particular trigger point, given the inputs provided by the calling application and what is configured in the configuration data.

  3. Rules Infrastructure triggers specific rules, which are linked to Rule Implementors.

  4. Rule Implementors run using input information from the trigger point and specific configuration held in the configuration database to execute the rule.

  5. Rule Infrastructure takes results from rule firings and prepares a response back to the client code that fired the rule.

These basic concepts should now have us prepared to dig into the programming interfaces to be used.

Basic Rule Usage Interfaces

The basic interface for using a rule is a trigger point. A trigger point is placed in the code wherever a rule needs to be executed. The code for a sample rule firing is shown below. This code could be placed into a servlet, session bean, or J2EE client:

  /**    * Trigger a rule to get the customer type (status), based on the amount     * of money spent.     * The type will be either gold, silver, or bronze.    * @param p_moneySpent The amount of money spent.    * @return an object containing the type of customer.    * @throws BusinessRuleBeansException    */   public Object checkCustomerType(double p_moneySpent)        throws BusinessRuleBeansException {     //firing params on the ruleImplementor     Double[] params ={new Double(p_moneySpent)};     //triggerClassifier invoked to find and fire the rule of type Classifier     Object result=standardTp.triggerClassifier (       null,             //the target parameter on the RuleImplementor,                          //which is the target object of the TriggerPoint       params,           //firing parameter on the RuleImplementor,                          //which is RuleValueForRange       classifyCustomersRuleFullyQualifiedName); //the full name of the
//Classifier Rule to find
return (java.lang.String)result; // we know it is a string in this case }

We will actually look at the associated rule and Rule Implementor in the next section.The example above is one of many types of rule firings. There are a number of interfaces associated with the TriggerPoint interface. The types of rule firings include:

  • Simple
    A simple trigger point is used to trigger a rule or rules specified by name. This type of trigger point is used by invoking the trigger method on an instance of the TriggerPoint class. All rules with the specified name will be triggered and the results combined using the combining strategy specified on the TriggerPoint object. This type of trigger point only finds rules that are marked as not being classifiers.

  • Classifier
    This type is what was used in the example above. A classifier trigger point is identical to a simple trigger point except that it only finds rules marked as being classifiers. These are rules whose purpose is to determine what sort of business situation is present and return a classification string indicating the result. Usually these rules are used as part of a situational trigger point, but they can be triggered on their own too. This type of trigger point is used by invoking the triggerClassifier() method on an instance of the TriggerPoint class.

  • Situational
    A situational trigger point is used when the rule or rules to be triggered depend on the business situation. It is the most complex of the methods that are available. The complex trigger method, triggerSituational(), has a sequence of two steps, the first step to find the classification which is fed into the second step. The second step triggers rules that have the classification equal to the value returned in the first step.

Creating Rules

Rules and Rule Implementors are separated when we speak of BRBeans. Rule Implementors are where the code goes that implements a rule. The "rule" abstraction is aware of a Rule Implementor, but has no code itself.Rule Implementors are Java classes and must implement the RuleImplementor interface. The three main methods on this interfacea are:

  • init()
    This method provides the initial state to the rule implementor and is called by the framework before the rule is fired. The initialization parameters can actually be configured by the Rule Management Application.

  • fire()
    This method implements business logic and returns results. This is the main logic of the rule. This is the method that gets invoked by the Rules Infrastructure.

  • getDescription()
    This method returns a string containing a description of the Rule Implementor.

The following snippet shows a simplified init() method of a Rule Implementor:

 public void init(Object [] parms,  String [ ] dependentRules,     String userDefinedData, IRuleCopy rule)throws BusinessRuleBeansException {   //Store the initialization parameters in member variables of the object.   preferredLevel = ((Integer)parms [0]).intValue();   goldLevel = ((Integer)parms [1]).intValue();   platinumLevel = ((Integer)parms [2]).intValue();   initialized = true;  //set implementor member variable } 

We can see from this initialization that there will be three possible results. The values for those three possible results are loaded into the variables preferredLevel, goldLevel, and platinumLevel from the database, which is part of the Rule Infrastructure. These values can be changed independent of the business logic or the application, if the business desired to change them.The primary method is the fire() method and this is shown below:

 public Object fire(TriggerPoint tp, Object target, IRuleCopy rule,     java.lang.Object []parms)throws BusinessRuleBeansException {   String classification = null;   int amount = 0;   if (initialized) {  // check implementor member variable     amount = ((Integer)parms [0 ]).intValue();     if(amount > = platinumLevel){     classification = PLATINUM_LEVEL;   } else if(amount > = goldLevel){     classification = GOLD_LEVEL;   } else if(amount > = preferredLevel){     classification = PREFERRED_LEVEL;   } else {     classification = LEVEL_NA;   }   return classification; } 

This Rule Implementor simply takes the inbound amount and the amounts established at initialization, and performs some simple logic to determine what classification this particular customer should have at this time.

The Rule Implementor shown above was focused on the primary logic path. A helper class that comes with the Business Rules support, called com.ibm.websphere.brb.implementor, should be used while building Rule Implementors. This class provides help in checking that the valid number of parameter values are provided so that the required parameters are indeed set to something besides null. This helper class throws the BRBeansIllegalArgumentException.

Rule Implementors Invocation

When a rule is fired for the first time, the following sequence of events takes place:

  • An instance of the RuleImplementor class is created using the default constructor.

  • The init() method is called, passing the initialization parameters defined for the rule.

  • The fire() method is called to elicit the Rule Implementor's behavior.

It is guaranteed by the rules infrastructure that the init() method is called at least once before the fire() method is called for the first time. Once the RuleImplementor is instantiated, the Rule Infrastructure caches it so that it does not have to be created and initialized again the next time that rule is fired. On subsequent fires, only the RuleImplementor instance's fire() method is called, not its init() method. Hence, the RuleImplementor is generally initialized only once, but can be fired many times.

Provided Rule Implementations

Before creating new Rule Implementors, it is important to note that a large number of Rule Implementors are supplied by WAS. These can be used as the implementors for new rules that you define. The following implementors are in the com.ibm.websphere.brb.implementor package:

  • RuleAND
    A rule comprising two or more rules that are all fired and their results combined via AND logic.

  • RuleOR
    A rule comprising two or more constraint-type rules that are all fired and the OR logic applied on their results.

  • RuleConstant
    A derivation rule that simply returns a persistent constant.

  • RuleConvert
    A derivation rule used to compute and return the result from a generic conversion performed with the formula mx + b.

  • RuleIfThenElse
    A rule comprising three rules. First, a constraint-type rule is fired to determine which of the other two rules to fire. If the first rule returns a true ConstraintReturn or a java.lang.Boolean with a value of true, then the second rule is fired, otherwise the third rule is fired.

  • RuleEqual
    A constraint-type rule algorithm that returns a true ConstraintReturn if x = a, where x arrives as a firing parameter and a is either provided as an initialization parameter or as a firing parameter.

  • RuleGreaterThan
    A constraint-type rule algorithm that returns a true ConstraintReturn if x > a, where x arrives as a firing parameter and a is either provided as an initialization parameter or as a firing parameter.

  • RuleGreaterThanEqual
    A constraint-type rule algorithm that returns a true ConstraintReturn if x >= a, where x arrives as a firing parameter and a is either provided as an initialization parameter or as a firing parameter.

  • RuleLessThan
    A constraint-type rule algorithm that returns a true ConstraintReturn if x < a, where x arrives as a firing parameter and a is either provided as an initialization parameter or as a firing parameter.

  • RuleLessThanEqual
    A constraint-type rule algorithm that returns a true ConstraintReturn if x <= a, where x arrives as a firing parameter and a is either provided as an initialization parameter or as a firing parameter.

  • RuleLink
    It rule fires a dependent rule and returns the result of the dependent rule. This implementor is primarily used to give a rule a second name.

  • RuleIsNull
    A constraint-type rule algorithm that returns a true ConstraintReturn if the input is null.

  • RuleMerger
    A rule comprising three or more rules, one of which is a merger rule. All but the merger rule are fired to get a set of results. The merger rule is then fired to arrive at a combined result.

  • RuleRange
    A constraint-type rule algorithm that returns a true ConstraintReturn if a <= x <= b, where x arrives as a firing parameter and a and b are either provided as initialization parameters, or as firing parameters.

  • RuleRangeNonInclusive
    A constraint-type rule algorithm that returns a true ConstraintReturn if a < x < b, where x arrives as a firing parameter and a and b are either provided as initialization parameters, or as firing parameters.

  • RuleValueForRangeNonInclusive
    This rule returns a string value based on where a number falls with respect to a range.

  • RuleTrue
    This always returns a true ConstraintReturn.

  • RuleFalse
    This always returns a false ConstraintReturn.

As you can see, before you start creating Rule Implementors of your own, the existing set of shipped implementors should be leveraged. They provide many of the basics building blocks for putting together a set of simple rules.

Note

Many of these patterns represented by the provided implementors involve dependent rules. When a business rule triggers other business rules as part of its implementation, the rules that are triggered are called dependent rules of the first rule. Dependent rules are specified in the attributes of the top-level rule where the fully qualified name of each dependent rule is listed. When the top-level rule is triggered, an array of dependent rule names is passed to the rule implementor's init() method. They are stored here until they are triggered by the fire() method.

Configuring Rules

Rules can be configured and managed using the Rule Management Application or by creating custom applications that leverage the available programming API. This section demonstrates configuration using the Rule Management Application.

The Rule Management Application is launched using the rulemgmt.bat file found in the WAS bin directory, passing in a properites file that points to the deployment folders for the beans. For example, the properties file for the sample movie BRBeans looks like:

host=localhost port=2809 RuleJndi=brbeans/moviesample/Rule RuleFolderJndi=brbeans/moviesample/RuleFolder RuleHelperJndi=brbeans/moviesample/RuleHelper

The Rule Management Application is used to configure and maintain the BRBeans that are being used by a WAS environment. The Rule Management Application is used to:

  • Create a new BRBeans rule definition including:

  • BRBeans rule folder and name

  • BRBeans rule start and end date

  • BRBeans rule type

  • BRBeans rule implementor

  • Initialization parameters for the Rule Implementor

  • Dependent BRBeans rules

  • Modify a BRBeans rule definition

  • Export or import BRBeans rule definitions in XML

The primary screen for the Rule Management Application is shown first:

click to expand

From here, we can see a number of rules organized into rule folders. We can also see some of the key properties of a rule. In our screenshot, all rules are in effect. The classifier rules have a label that shows the nature of the classification for each rule. If we pick our gold classifier rule and look at the properties, we can see a number of additional pieces of information:

click to expand

This shows start dates, status, and the nature of the classification. The next screenshot is of the Implementation display:

click to expand

Here we can see the details of how this is implemented, initialized, and fired. The implementation in this case leverages one of the supplied Rule Implementors that come with the WAS.




Professional IBM WebSphere 5. 0 Applicationa Server
Professional IBM WebSphere 5. 0 Applicationa Server
ISBN: N/A
EAN: N/A
Year: 2001
Pages: 135

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net