Sunteți pe pagina 1din 21

Customize Your SAP NetWeaver BPM through APIs

Applies to:
SAP NetWeaver 7.30 and higher

Summary
With the release of SAP NetWeaver 7.30, SAP NetWeaver BPM is offering a set of APIs, which allow to access process and task related data in order to customize the behavior of applications built using BPM. This document gives an introduction into the available functionality and provides some simple code examples how to call the respective features. Author: Company: Created on: Stefan Henke SAP AG August 2012

Author Bio
Stefan Henke joined SAP in 2004. He is working as a team architect for SAP NetWeaver BPM. During his time at SAP, he contributed to many projects in the java space like Composite Designer, Composite Application Framework and NetWeaver Mobile.

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 1

Customize Your SAP NetWeaver BPM through APIs

Table of Contents
Overview ............................................................................................................................................................. 3 Motivation ........................................................................................................................................................ 3 Concepts ......................................................................................................................................................... 4 Setting up the System ......................................................................................................................................... 7 Using the APIs .................................................................................................................................................... 9 Authentication ................................................................................................................................................. 9 Transaction Handling .................................................................................................................................... 11 Coding Samples ............................................................................................................................................... 14 Start a Process Instance ............................................................................................................................... 14 Querying Tasks and Starting a Single Task.................................................................................................. 16 Completing a Task ........................................................................................................................................ 18 Related Content ................................................................................................................................................ 20 Copyright........................................................................................................................................................... 21

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 2

Customize Your SAP NetWeaver BPM through APIs

Overview
Motivation If you are a user of SAP NetWeaver Composition Environment (CE) and in particular of its component Business Process Management (BPM), you might have wondered if there is a way to build your own components as extensions to SAP NetWeaver BPM or to replace existing components with your own ones, which better fit your specific scenario. There is good news for you. With the 7.30 release of the SAP NetWeaver platform, SAP NetWeaver BPM comes with an Application Programming Interface (API) that exposes parts of the BPM functionality for external usage. Later on, you will see that it is not only about querying data from BPM, but also about modifying data and triggering actions. This gives you the flexibility and freedom to do things you were not able to do before. Of course, one can imagine really cool things. In the following, only a few possible use cases will be explained (maybe the most obvious ones): Implement your own task list for end users If the Universal Work list (UWL), which is integrated in the Enterprise Portal (EP) does not fit to your requirements (e.g. maybe because you require a smoother integration into your application), you might consider creating your own task list providing all tasks for a user. Therefore, the BPM API offers methods to query tasks directly assigned (as Actual Owner) or potentially assigned (as Potential Owner) to a user. Additionally, these tasks can also be filtered based on their status. Build your own task execution UI If the task UI provided by default is too generic for you or you want to use a different UI technology than Web Dynpro for task users, you can do so by implementing an own UI, for example, with Flash or Java Server Faces (JSF) and render it using HTML5. In principle, you can make use of any UI technology that is able to access a Java-based API and that can be deployed to the Application Server Java (AS Java). In order to do this, the BPM API offers methods to read the complete data of a task. Additionally, input and output data, which gets mapped from and to the embedding process, can be read. Trigger task operations (e.g., completing a task) from external applications Using the new BPM API, you can also directly trigger operations on a task. This can be used to integrate such operations into your own UI or include e.g. a link into a mail that directly approves or rejects a leave request. The BPM API offers, among others, the possibility to claim a task or complete it. Enable mobile devices to display tasks All use cases described so far of course could also be implemented for mobile devices like an iPhone or Android based phones. In the releases before 7.30, it was hardly possible to do this because the supported UI technologies (Web Dynpro Java and ABAP) dont fit well into the paradigm of mobile computing. However, this is definitely changing as the new API is opening SAP NetWeaver BPM to also allow remote access to its data.

As already mentioned before, you are free in the choice of the used technology for your component: be it a standard Java technology like EJB, JSP, JSF, or any open source technology, which meets your requirements. The only requirement is that it can be deployed to the AS Java, on which SAP NetWeaver BPM is running. There is a very nice article, which guides you how to deploy Apache CXF on the AS Java [1]. You can follow this approach for other technologies as well. When it comes to technologies that cannot be run on the AS Java, there is still a gap that has to be bridged as the BPM API does not provide remote enablement out of the box. If you want to access SAP NetWeaver BPM via a network protocol, you first have to expose the required functionality for remote access. However, you are again free in choosing the technology: be it a normal SOAP-based Web service, a RESTful service, or something completely different. The diagram in Figure 1 is outlining how the different components might play together. All boxes inside the gray box Business Process Management are existing components delivered as part of SAP NetWeaver BPM. All boxes on top represent hypothetical components implemented based on the BPM API.

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 3

Customize Your SAP NetWeaver BPM through APIs

Mobile App (Apple, Android)

Custom Uis (WebDynpro, JSF etc.)

WebService Wrapper

Task Management
R R

Process Management
R

UWL

NWA

Business Process Management NetWeaver AS Java

Figure 1: Accessing SAP NetWeaver BPM through APIs

There are already a few prototypes available demonstrating the capabilities of the BPM API. To name only two those are also available on SAP Code Exchange: RESTful wrapper for NetWeaver BPM [2] NetWeaver BPM on Ruby [3]

Concepts The BPM API is designed in a service-like manner. This means, for each operation a client wants to execute, a specific method of the available services has to be called. In some cases, the method will return data transfer objects containing the requested data (e.g., task instance data). The services are grouped by the entity they offer methods for. Therefore, the following services are available: ProcessDefinitionManager for operations on Process Definitions ProcessInstanceManager for operations on Process Instances TaskInstanceManager for operations on Task Instances

Additionally, there is one manager, which is somehow an exception as there is no entity that directly maps to it. The ProcessStartManager provides methods to start a new process instance. So, all about, there are four manager classes, which will be described in more detail later in this article. All these manager classes can be resolved via the class com.sap.bpm.api.BPMFactory, which is implemented as singleton-like class. It provides static methods to get an instance of each of the mentioned managers. More information about this you find in the official Java Doc [4] as well as in the documentation of the BPM API [5].

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 4

Customize Your SAP NetWeaver BPM through APIs

The following sections contain several concepts that are applied across the BPM API:

URIs All entities, which can be dealt with in SAP NetWeaver BPM can be addressed via a unique URI. When executing an operation for a specific entity, it is exactly this URI you have to pass as input to trigger the operation. The nice thing about this URI is that it will never change for an entity. So, URIs returned by BPM, may be stored by clients to identify the entity again at a later point in time. Even if the entitys state is changed (e.g., by claiming a task or canceling a process), the URI will remain the same. It always consists of two major parts: on the one hand side it contains the type of the entity it refers to (e.g., a task or a process instance) and on the other side a unique identifier for the entity. This identifier is equal to the identifier that you can use in the SAP NetWeaver Administrator to locate a task or process instance.

Error handling When accessing the BPM API, it is important that a consumer is able to react on certain error situations. Thus, there is a set of typed exceptions defined across all manager classes, which makes life easier in case an error occurs when calling one of the BPM APIs. Using the typed exceptions, a consumer will be able to appropriately react on the occurred issue. In detail, the following exceptions are available: BPMIllegalArgumentException Most of the operations require some kind of input data. Depending on the complexity of this input, it might occur that the passed data is not valid for some reason (e.g., if a nonexisting task URI has been passed to the method TaskInstanceManager#getTaskDetail(), it will throw this kind of exception). BPMIllegalAccessException In general, every operation called in the BPM API requires a certain level of permission (e.g., claiming a task is only possible for task administrators or users that are part of the potential owner list). If this exception is thrown when calling an operation, it indicates that the currently logged on user is not allowed to perform the operation. BPMIllegalOperationException Operations that change the lifecycle state of an entity (e.g., a task) assumes certain preconditions to be fulfilled in order to successfully perform the operation. For example, if a consumer wants to complete a task, it needs to be assigned to a user first. If this has not happened before, this type of exception is thrown. See one of the next sections for details.

Contextual data A task or process in SAP NetWeaver BPM consists of static header attributes that are pre-defined by SAP NetWeaver BPM and equal for all instances. This includes, for example, (translatable) names, lifecycle status or priority. Besides this, both entities provide the option to define contextual data that is modeled in the process composer using data objects and mappings between entities. This data normally contains business data relevant for the process and/or task flow, but might also contain technical data. The BPM API is exposing such data for process start events as well as for task input and task output respectively faults. In the BPM API this kind of data has to be handled generically in a non-typed way. So, the client has to be aware of the content structure in order to interpret it. This generic handling is realized using Service Data Objects (SDOs) which provides a well-defined API to read or manipulate the data. In the course of this document, the terms SDO and data object will be used. Though both are somehow identical, the term SDO refers more to the technology as such whereas whenever the term data object is used, it refers to the Java interface or underlying implementation of it. Due to the fact that the interface to access a data object is generic, its instances always have a structure (consisting of properties and nested data objects) that cannot be changed during runtime. Consequently, this means that a data object used as input for a process start event can only be used for this case, but not reused for other process start events. As the data object interface only provides non-typed setter/getter-methods to access the data, a consumer has to know the structure of the data object. Alternatively, he can use the reflective methods of the interface to determine the structure at runtime.

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 5

Customize Your SAP NetWeaver BPM through APIs

For more information about SDOs, please, refer to the specification and especially the standardized API, which is documented in [6]. The sample section later in this document will also provide some code snippets to demonstrate how to work with SDOs in the BPM API.

Task Lifecycle Tasks in SAP NetWeaver BPM always run through a well-defined lifecycle starting from creation and ending with completion or failure. The BPM API offers lifecycle operations in the TaskInstanceManager interface that allow consumers to change the status of a task. Figure 2 visualizes the different states of a task. The operations that are necessary for a status change are annotated in the diagram.

[task created and activated]

Ready

claim or delegate

release

Reserved

release

delegate

start

stop or delegate

In Progress

fail

complete

Failed

Completed

Figure 2: Status lifecycle for tasks

Note: The diagram does not include the states CREATED and SUSPENDED. There is no operation for consumers to move a task into one of these states. This can be done only by the process engine of SAP NetWeaver BPM. CREATED is an intermediate status before the task moves into status READY. A task will change its status to SUSPENDED if a recoverable error occurred either in the task itself or the process the task is running in. In the latter case, the suspension will be propagated to the task. Note: The interface TaskInstanceManager only supports the above mentioned status transitions. Convenient transitions like changing the status directly from READY to IN PROGRESS by calling the start operation are not supported.

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 6

Customize Your SAP NetWeaver BPM through APIs

Setting up the System


This chapter explains the steps that are required upfront to make a system up and running so that one is able to implement components based on the BPM APIs. The API is included in the software component (SC) BPEM-FAADE. Some of the APIs depend on the SDO API as well as the User Management Engine (UME) API which are both located in the SC ENGFACADE.

1) Make the necessary SCs available in your development configuration The very first step that has to be ensured is that the required APIs can be referenced by your development components (DCs). This has to be accomplished by making the mentioned SCs available in your development configuration. Depending on the fact if development happens in a local development configuration (e.g., local development) or in a remote track, there are different things to do. For local development, nothing has to be done as the SCs are already included in the Archive Pool of the SAP NetWeaver Developer Studio (NWDS). For a remote track, it is required to include and import both SCs mentioned above into the track as archives. Most likely this needs involvement of an administrator as this task cannot be done within the NWDS, but only in the Change Management Service (CMS) and the Component Build Services (CBS). The screenshot in Figure 3 shows a development configuration that contains all necessary SCs for usage of the BPM API. The SC CONSUMER will contain the custom DCs accessing the API and thus it is included as editable SC. The SC SAP_BUILDT is not directly required for the BPM API. However, it is required for the creation of DCs of any type (e.g., EJB DCs).
Note: The SC CONSUMER would not be able to contain any process DCs. If this was required, the necessary SC dependencies have to be added in addition.

Figure 3: Development Configuration for usage of BPM API

2) Define SC dependencies to the mentioned SCs Once the SCs are available in the development configuration, the required SC dependencies have to be set for the SC CONSUMER. The necessary steps again differ for local and remote development. In the local case, one can define the new SC dependencies in the Development Infrastructure perspective (Component Properties view) in the NWDS. In the remote case, this needs to be adjusted in the CMS by an administrator. Figure 4 shows the properties of the SC CONSUMER with all necessary SC dependencies.
Note: As in the previous step, if the SC CONSUMER should additionally contain any process DC, the required SCs have to be added to the dependency list.

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 7

Customize Your SAP NetWeaver BPM through APIs

Figure 4: Necessary SC dependencies

3) Set DC dependencies from your DCs Once the DCs have been created, it is necessary to define dependencies to the DCs exposing the BPM APIs and its dependent APIs. In the Component Properties view of the Development Infrastructure perspective, dependencies to the following DCs should be set: tc/bpem/faade/ear (BPEM-FACDE) tc/je/sdo21/api (ENGFACADE) tc/je/usermanagement/api (ENGFACADE) Figure 5 visualizes all DC dependencies that are required for a DC to make use of the BPM API. This especially includes the api public parts of these DCs. The dependency to DC engine.j2ee5.facade is not directly required by the BPM API, but is a default dependency of most DC types (in this case an EJB DC).

Figure 5: Necessary DC dependencies


Note: If you are using EJB/Web modules and EAR DCs, you also have to define a runtime and optionally a deploy-time dependency from your EAR DC to the mentioned DCs.

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 8

Customize Your SAP NetWeaver BPM through APIs

Using the APIs


The following section covers several topics, which most users will come across when using the BPM API. All topics will be held in a generic fashion to cover most of the use cases in which the BPM API can be used. Authentication The BPM API provides a sophisticated authentication concept to prevent uncontrolled access to data in SAP NetWeaver BPM. For example, a task that has been claimed can only be read and changed by the user who is assigned to the task or an administrator of the task. All operations of the API are automatically operating on the currently logged on user. This means the application, which is using the BPM API, has to create a context in which the user is running before calling the API. This can be done with the standard capabilities of JEE and the AS Java. In the following, a description is given how a JEE Web module needs to be configured in order to force incoming requests to provide authentication credentials and build up the necessary user context based on the provided information. If the consumer of the BPM API is a custom UI, you will most likely implement it using JEE technologies (e.g., JSF) in a Web module and therefore, following this approach. In this case, you can configure the authentication mechanism in the web.xml and web-j2ee-engine.xml. The following snippet of the web.xml is basically defining that any user belonging to the JEE role Everyone is allowed to access the URLs of the Web application. However, the user has to authenticate first using BASIC authentication. This will display a browser specific dialog box asking the user for user name and password. Alternatively, you can also replace BASIC by FORM to use a login page provided by the server rather than a dialog box. If the consumer in your Web module is a human user, form-based authentication is recommended as this provides a more convenient user interaction including customization of the login page. For non-human users like a Web service or RESTful service approach, basic authentication is heavily recommended as this allows the client to provide the authentication details in the HTTP header without redirections to the login page. This will reduce the number of HTTP round trips between client and server.
<web-app> <security-role> <description>Everyone</description> <role-name>Everyone</role-name> </security-role> <security-constraint> <web-resource-collection> <web-resource-name>YourWebResource</web-resource-name> <url-pattern>*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>Everyone</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>NONE</transport-guarantee>

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 9

Customize Your SAP NetWeaver BPM through APIs </user-data-constraint> </security-constraint> <login-config> <auth-method>BASIC</auth-method> <realm-name>YourRealm</realm-name> </login-config> </web-app>

Listing 1: Content of web.xml The role definition in the web.xml refers to JEE roles, which are not identical to the roles maintained in the UME. Therefore, it is required to map the JEE role to an UME role in the web-j2ee-engine.xml file as follows. The server-role-name refers to the UME role you want to use. In the sample, it is the role Everyone to which every user automatically belongs.
<web-j2ee-engine > <security-role-map> <role-name>Everyone</role-name> <server-role-name>Everyone</server-role-name> </security-role-map> </web-j2ee-engine>

Listing 2: Content of web-j2ee-engine.xml Of course, it is possible to further restrict the access by specifying another role than Everyone. This depends on the use case and needs to be decided on an individual base. Besides the mentioned authentication mechanism BASIC and FORM, it is very well possible to extend this example with any valid SAP extensions like the login-module-configuration tag to support more sophisticated authentication algorithms like logon tickets. Whatever solution has been chosen, it is important that the user context which is used to call the API has been initialized with a user that has the necessary permission to execute the operation. Otherwise, the operation cannot be performed and will throw an exception. This behavior is common for all provided API operations (for more details, see Concepts). If functionality is exposed via Web service for remote access, it is recommended to take a look at the official documentation at [7], There are multiple options to handle security either on HTTP transport level, which will work similar to the approach illustrated for the custom UI described beforehand or on SOAP document level (including WS-Security). This would be subject of a separate document as it goes beyond the scope of this article. Another security topic, which is closely related to authentication, is securing the communication channel by providing encryption of the data. This can be accomplished using the Secure Socket Layer (SSL) protocol which can be enabled on the AS Java. There is no need to provide project or component specific configuration for this, but only globally on the AS Java. Therefore this document does not provide any documentation on this topic. Please refer to the official AS Java documentation [8] in order to enable SSL on the AS Java.

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 10

Customize Your SAP NetWeaver BPM through APIs

Transaction Handling All operations provided by the BPM API require a transactional context in which the execution takes place. The AS Java is providing sophisticated support for transaction in the means of an implementation of the Java Transaction API (JTA). It is important for consumer of the BPM API to understand the transactional boundaries when performing operations via the BPM API. When calling an operation of the BPM API it will either re-use the transaction the caller is currently running in or if the caller is not running in any transactional context it will create a new transaction. This can be used by consumers, for example, to bundle multiple task operations into a single atomic operation or explicitly execute one task operation in a single transaction. This gives consumers the freedom to implement various patterns and use cases. Typically, the BPM API is called from an EJB or a Servlet (resp. JSP, JSF). Both variants allow consumers to easily set up a transactional context. By default, both variants provide so-called Container Managed Transaction Demarcations. This kind of transaction management allows developers to specify transaction boundaries via Java annotations on EJB or method level. For more details on this, please refer to the respective documentation of the AS Java [9]. The example shown in Listing 3 demonstrates a stateless session bean with two methods. Both methods actually do the same thing, performing a claim operation followed by a start operation on a task. This will move a task from status READY to IN PROGRESS. However, there is a significant difference in the sense of transactional boundaries and consequently the visibility of the operation results. In the first method executeInOneTransaction the method is annotated with the transaction attribute REQUIRES_NEW. In this scenario the EJB container forces the creation of a new transaction when entering method executeInOneTransaction. According to the description given above the transaction of this method is reused when performing the claim and start method. As a consequence the status of the task will directly move from READY into IN PROGRESS. If the transaction gets rolled back due to an exception, no changes at all will get persisted so that the task will stay in its original status READY. The second method executeInTwoTransactions is annotated with the attribute NEVER, which means that it will never participate in any transaction. So, there is no transactional context available that could be reused by the BPM API. As a consequence, the JTA container will automatically create a new transaction when calling a method of the BPM API and commit it when leaving the method. Hence, in the described example, two separate transactions will be used for the claim and the start operation. So, the result of the first operation will be persisted on transaction commit moving the task into the status RESERVED. If the second operation fails, the status will not be rolled back to READY. @Stateless public class MyBean implements My { @TransactionAttribute(value=TransactionAttributeType.REQUIRES_NEW) public void executeInOneTransaction(URI taskUri) throws BPMException { TaskInstanceManager mgr = ...; mgr.claim(taskUri); mgr.start(taskUri); }

@TransactionAttribute(value=TransactionAttributeType.NEVER) public void executeInTwoTransactions(URI taskUri) throws BPMException {

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 11

Customize Your SAP NetWeaver BPM through APIs

TaskInstanceManager mgr = ...; mgr.claim(taskUri); mgr.start(taskUri); } } Listing 3: EJB sample demonstrating transactional behavior of the BPM API Figure 6 and Figure 7 are visualizing the interaction with the transaction manager provided by the JTA implementation of the AS Java. All calls to the transaction manager are performed automatically by the EJB container and thus be invisible for consumers.

Consumer

MyBean

TaskInstance Manager

Transaction Manager

executeInOneTransaction() beginTransaction() claim()

return start()

return commitTransaction() return

Figure 6: Execution in a single transaction

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 12

Customize Your SAP NetWeaver BPM through APIs

Consumer

MyBean

TaskInstance Manager

Transaction Manager

executeInTwoTransactions() claim() beginTransaction()

return start()

commitTransaction() beginTransaction()

return return

commitTransaction()

Figure 7: Execution in two separate transactions

Additionally to the described scenarios, it is also possible for the caller to manage its transaction boundaries on his own (so-called Bean Managed Transaction Demarcations) using user transactions. This can be especially used if the caller is running without any transactional context. The example shown in Listing 4 demonstrates how to create a user transaction that executes a claim and start operation in a single transaction. When committing the transaction, the task status will change from READY to IN PROGRESS. However, if the transaction gets rolled back for any reason, the task will stay in status READY. This is true even if the claim operation did not run into an issue. Semantically this example is identical to the previous example executeInOneTransaction. Please note that you are also responsible to properly rollback the transaction if an exception occurs. TaskInstanceManager mgr = URI taskUri = UserTransaction ut = (UserTransaction)ctx.lookup("java:comp/UserTransaction"); ut.begin(); try { mgr.claim(taskUri); mgr.start(taskUri); ut.commit(); }catch(Exception e) { ut.rollback(); } Listing 4: Accessing task operations in a user transaction

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 13

Customize Your SAP NetWeaver BPM through APIs

Coding Samples
This section contains a set of coding samples for the most common use cases that can be implemented with the BPM API. To provide the biggest value, all of them are based on the same scenario, a very simple leave request approval process. The process context including the start event interface and the task context allows a consumer to provide a set of data when starting the process and task instance. The structure of the context is using nested structures by intention. This allows demonstration how this data has to be passed to the BPM API. Start a Process Instance Though you can always start new process instances by calling the respective Web service endpoint of the start event, it is also possible to do this via the BPM API directly from Java coding. The following source code listing contains a complete example of creating a new process instance via the BPM API. The first step is to resolve the correct process definition (using method ProcessDefinitionManager#getActiveProcessDefinition()) followed by determining the correct start event that should be used (ProcessStartManager#getProcessStartEvents()).
Note: The BPM API allows consumers to query only the active process definition of a model. This is due to the fact that in SAP NetWeaver BPM new process instances can only be started for the active version of the process definition, but not for older versions (this applies to all ways of starting new process instances across SAP NetWeaver BPM).

In order to identify the correct process definition, you have to provide the vendor and the name of the development component the process model has been deployed with as well as the name of the process itself.
Note: If your vendor or DC name contains some special characters like / or ., you have to replace them by ~ (for example myapp/process/leave_request becomes myapp~process~leave_request). Otherwise, the process definition cannot be found.

In the given example, the process contains only one start event. Therefore, we can directly select the first one from the returned list. Before the resolved start event can be used to trigger the new process instance, input data for the new process instance has to be created (see section Concepts for more details). The structure of the input data is defined by the start event and thus the usage of the corresponding data object is bound to this start event. First, an empty instance of the data object has to be created. It will be automatically initialized with the correct structure matching the required input for the start event. The empty data object needs to be filled with the data that should be used for the process start. The structure of the data object used by this example is shown in Listing 5. It is based on the schema defined in the process composer. In this example, it contains data necessary to create a leave request. As mentioned before, you have to use generic setter methods to set the values. Therefore, all properties have to be identified by name in the method DataObject#set(String, String). As you can see in the example, the input for the start event contains a nested structure with name time. For this, a new data object instance has to be created. As it is a child object to the root input object, it can only be created by the same. This can be accomplished by passing the name of the property holding the nested structure (here, time) and calling the create method DataObject#createDataObject(String). The newly created data object can be filled in the very same way as the root object. In this case, data type specific methods are used to set the start and end date (DataObject#setDate(String, Date)) to illustrate another way of setting the data. Similar methods for all data types supported by SDO are also available and could have been used for the root object as well.

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 14

Customize Your SAP NetWeaver BPM through APIs

[http://www.example.org/LeaveRequestSvc/#LeaveRequestData] { actionCode:[UNSET] default=0; //CREATE, EDIT, CANCEL employeeId:[UNSET] default=null; time:[UNSET] default=null; reason:[UNSET] default=null; leaveType:[UNSET] default=0 //REGULAR, HALFDAY, SPECIAL }

Listing 5: Structure of the start data object for the 'Leave Request' process

The final step is to pass the root object to the method ProcessStartManager#startProcess(ProcessStartEvent, DataObject) to finally start the new process instance. The method is returning an identifier to the newly created instance. It will directly turn into the status IN PROGRESS. You can check this for the new process instance, for example, in the SAP NetWeaver Administrator. The used scenario might foresee to create a new task for the approving manager in his inbox.
Note: Starting a new process instance via the BPM API will not involve any load balancing offered by the AS Java. The process instance is started on the cluster node the code calling the method ProcessStartManager#startProcess has been executed. This also includes all follow-up work that is triggered by the process start (e.g. automated activities). This should be kept in mind when starting more than one process instance at once. ActionCode actionValue = . . .; //java enumeration defined for this example LeaveType typeValue = . . .; //java enumeration defined for this example String reason = . . .; String employedId = . . .; Date startDate = . . .; Date endDate = . . .;

ProcessDefinition def = BPMFactory.getProcessDefinitionManager(). getActiveProcessDefinition("demo.sap.com", "leave_request", "LeaveRequestProcess");

ProcessStartEvent event = BPMFactory.getProcessStartManager(). getProcessStartEvents(def.getId()).iterator().next(); DataObject input = BPMFactory.getProcessStartManager(). createDataObjectForStartEvent(event);

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 15

Customize Your SAP NetWeaver BPM through APIs

input.set("actionCode", actionValue.getValue()); input.set("leaveType", typeValue.getValue()); input.set("reason", reason); input.set("employeeId", employeeId); DataObject timeDataObject = input.createDataObject("time"); timeDataObject.setDate("startDate", startDate); timeDataObject.setDate("endDate", endDate);

URI processInstance = BPMFactory.getProcessStartManager().startProcess(event, input);

Listing 6: Sample code 'Start new Process Instance' Querying Tasks and Starting a Single Task The next example combines two different use cases. The first use case shown in Listing 8 includes querying human tasks visible for a user. The second use case also shown in Listing 8 starts one of the returned tasks and reads the task input data. This data can be displayed in an UI for an end user to process the Task. These use cases are closely related to each other so that they will be often used in the described manner. Compared to the previous one, this example will only deal with the TaskInstanceManager provided by the BPM API. Using the method TaskInstanceManager#getMyTaskAbstracts() it is possible to resolve human tasks which are assigned to one specific user. It can be used for end user queries, but does not serve the requirements of queries for administrators. So, in most cases, it will be used to populate a custom work list. The method will internally perform authorization checks to make sure that a user can only access the tasks he or she is allowed to see. Therefore, it is very important for components sending such queries to the BPM API to run in a proper user context by providing authentication mechanisms as described in section Concepts.
Note: Depending on the concrete task status, assigned means that the user is either a potential owner of a task in status READY or actual owner of a task in status RESERVED or IN PROGRESS.

In the given example, only tasks in status READY are queried. The result will be a Set containing the identifiers of all tasks matching the criteria. For simplification reasons, the example is simply picking the first one from the result. The returned instance of TaskAbstract provides access to the header information of the task. As described earlier in this document, this data should be sufficient for displaying an end user work list. From this instance it is possible to get the unique identifier of the task to trigger lifecycle operations for this particular task. Here, the operations claim and start are called changing the task status from READY to IN PROGRESS. The last part of the example covers reading the input data of the task, which provides access to the contextual data of the task. It is accessible only via the details of the task, which can be retrieved using the method TaskInstanceManager#getTaskDetails(URI).This data can be retrieved as SDO in the form of an instance of the class DataObject.
Note: Retrieving the task details (via #getTaskDetails(URI)) is much more expensive than simply retrieving the task header (via #getTaskAbstract(URI)). So, the latter one should be called whenever possible to reduce the number of calls for the task details to a bare minimum.

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 16

Customize Your SAP NetWeaver BPM through APIs

In Listing 8 one can see that the structure of the input data basically contains the data of the leave request used for the process start in the previous example. Additionally, it includes a status of the current leave request handled by the process instance. In contrast to the previous example, the SDO is already filled with data. This data corresponds to the data that has been mapped from the process context to the context of the task respectively human activity in its input mapping in the process composer. The returned SDO includes several nested objects. The first level with name Context is common for all tasks. Only on the next level (here, leaveRequestData respectively leaveRequestStatus), the structure becomes specific to this task. In the last part of the example, the individual properties of the SDO are read. This is done using different methods to demonstrate the various data types offered by SDO as well as the ways to access the same.
[http://demo.sap.com/leave_request_ui/ApproveTaskComponent/ports#ContextTypeINPUT] { Context:[http://demo.sap.com/leave_request_ui/ApproveTaskComponent#Context] { leaveRequestStatus:[UNSET] default=null; leaveRequestData:[ http://demo.sap.com/leave_request_ui/ApproveTaskComponent#Context_leaveRequestData] { actionCode:0; employeeId:[UNSET] default=null; reason:"summer holiday"; leaveType:0; time:[http://demo.sap.com/leave_request_ui/ApproveTaskComponent#Context_leaveReque stData_time] { startDate:"2012-05-04"; endDate:"2012-05-04"} } } }

Listing 7: Structure of the task input data object for 'Leave Request'

Set<Status> status = new HashSet<Status>(); status.add(Status.READY);

Set<TaskAbstract> tasks = BPMFactory.getTaskInstanceManager(). getMyTaskAbstracts(status); TaskAbstract firstTask = tasks.iterator().next();

BPMFactory.getTaskInstanceManager().claim(firstTask.getId());

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 17

Customize Your SAP NetWeaver BPM through APIs

BPMFactory.getTaskInstanceManager().start(firstTask.getId()); TaskDetail detail = BPMFactory.getTaskInstanceManager(). getTaskDetail(URI.create(firstTask.getId())); DataObject inputDO = detail.getInputDataObject();

DataObject contextDO = inputDO.getDataObject("Context"); DataObject dataDO = contextDO.getDataObject("leaveRequestData");

int actionCode = dataDO.getInt("actionCode"); int leaveType = (Integer) dataDO.get("leaveType");

String employeeId = dataDO.getString("employee"); String reason = (String) dataDO.get("reason"); DataObject timeDO = dataDO.getDataObject("time"); Date startDate = timeDO.getDate("startDate"); Date endDate = (Date) timeDO.get("endDate"); Listing 8: Sample code 'Querying Tasks and Starting a single Task' Completing a Task The next logical step in handling tasks with SAP NetWeaver BPM is to complete them. This will be covered by the last example. When completing a task, it is required to pass the so-called output data back to the system. This data will be used to perform the output mapping of the task to the process context. In other words, this is the way to transfer data from the task into the process it is running in. Handling of the output data is similar to the handling of input data, which has been demonstrated in the previous example. Retrieval of the initial SDO is done via the task details. Method TaskDetail#getOutputDataObject() returns an empty SDO containing the structure of the task output. This SDO needs to be filled by the consumer. Typically, the data that has been entered by the owner of the task while processing the same is used. In the given example, the SDO again contains a nested structure, which is constructed and populated in the same manner as in the example starting a new process instance.

Note: If you are unsure about the exact structure of the SDOs in your scenario, you might use the introspective methods the SDO API provides. It offers the possibility, for example, to read details about the type of the SDO (using DataObject#getType()). Note: One might have recognized that the structure of the input and output SDO for the task is actually the same. This needs to be kept in mind when modeling the task as process composer will re-use the same structure for input and output.

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 18

Customize Your SAP NetWeaver BPM through APIs

[http://demo.sap.com/leave_request_ui/ApproveTaskComponent/ports#ApproveTaskApproveEventT ypeOUTPUT] { ApproveTaskApproveEvent:[http://demo.sap.com/leave_request_ui/ApproveTaskComponent #Context] { leaveRequestStatus:[http://demo.sap.com/leave_request_ui/ApproveTaskComponent#Cont ext_leaveRequestStatus]{ status:"APPROVED"; comment:"Approved"}; leaveRequestData:[UNSET] default=null } }

Listing 9: Structure of the task output data object for 'Leave Request' TaskDetail detail = BPMFactory.getTaskInstanceManager().getTaskDetail(URI.create(taskId)); DataObject outputDO = detail.getOutputDataObject(); DataObject innerDO = outputDO.createDataObject("ApproveTaskApproveEvent"); DataObject statusDO = innerDO.createDataObject("leaveRequestStatus");

statusDO.set("comment", "Approved"); statusDO.set("status", "APPROVED"); BPMFactory.getTaskInstanceManager().complete(URI.create(taskId), outputDO); Listing 10: Sample code Completing a Task

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 19

Customize Your SAP NetWeaver BPM through APIs

Related Content
[1] RESTful services development with SAP NetWeaver CE http://www.sdn.sap.com/irj/scn/weblogs?blog=/pub/wlg/20830 [2] RESTful service for NetWeaver BPM http://scn.sap.com/community/bpm/blog/2011/10/27/restful-service-for-netweaver-bpm [3] Building UIs with Ruby and Sinatra on NW BPM http://scn.sap.com/docs/DOC-28977 [4] Javadoc: Process and Task Management Facade (BPM) http://help.sap.com/javadocs/NW73/SPS03/CE/index.html [5] Official BPM API documentation: http://help.sap.com/saphelp_nw73/helpdata/en/9a/eebbdf59b94c3c82af598db638b0d0/frameset.htm [6] Service Data Objects Documentation http://jcp.org/aboutJava/communityprocess/final/jsr235/index.html [7] Web Service Authentication http://help.sap.com/saphelp_nw73/helpdata/en/49/9d40514f133eeee10000000a421937/frameset.htm [8] Configure SSL on the AS Java http://help.sap.com/saphelp_nw73/helpdata/en/4a/015cc68d863132e10000000a421937/frameset.htm [9] Transaction Demarcations in JTA http://help.sap.com/saphelp_nw73/helpdata/en/49/09495268d4105ee10000000a42189d/frameset.htm

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 20

Customize Your SAP NetWeaver BPM through APIs

Copyright
Copyright 2012 SAP AG. All rights reserved. No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG. The information contained herein may be changed without prior notice. Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. Microsoft, Windows, Excel, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation. IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z, System z10, System z9, z10, z9, iSeries, pSeries, xSeries, zSeries, eServer, z/VM, z/OS, i5/OS, S/390, OS/390, OS/400, AS/400, S/390 Parallel Enterprise Server, PowerVM, Power Architecture, POWER6+, POWER6, POWER5+, POWER5, POWER, OpenPower, PowerPC, BatchPipes, BladeCenter, System Storage, GPFS, HACMP, RETAIN, DB2 Connect, RACF, Redbooks, OS/2, Parallel Sysplex, MVS/ESA, AIX, Intelligent Miner, WebSphere, Netfinity, Tivoli and Informix are trademarks or registered trademarks of IBM Corporation. Linux is the registered trademark of Linus Torvalds in the U.S. and other countries. Adobe, the Adobe logo, Acrobat, PostScript, and Reader are either trademarks or registered trademarks of Adobe Systems Incorporated in the United States and/or other countries. Oracle is a registered trademark of Oracle Corporation. UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group. Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, and MultiWin are trademarks or registered trademarks of Citrix Systems, Inc. HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C, World Wide Web Consortium, Massachusetts Institute of Technology. Java is a registered trademark of Sun Microsystems, Inc. JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape. SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP Business ByDesign, and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany and other countries. Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other Business Objects products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of Business Objects S.A. in the United States and in other countries. Business Objects is an SAP company. All other product and service names mentioned are the trademarks of their respective companies. Data contained in this document serves informational purposes only. National product specifications may vary. These materials are subject to change without notice. These materials are provided by SAP AG and its affiliated companies ("SAP Group") for informational purposes only, without representation or warranty of any kind, and SAP Group shall not be liable for errors or omissions with respect to the materials. The only warranties for SAP Group products and services are those that are set forth in the express warranty statements accompanying such products and services, if any. Nothing herein should be construed as constituting an additional warranty.

SAP COMMUNITY NETWORK 2012 SAP AG

SDN - sdn.sap.com | BPX - bpx.sap.com | BOC - boc.sap.com | UAC - uac.sap.com 21

S-ar putea să vă placă și