# 15. Web Services

Chapter Contents | Prev | Next
Keyword Search:
www.openlinksw.com
docs.openlinksw.com
Book Home
Contents
Preface
Web Services
SOAP
WSDL
WS-Security (WSS) Support in Virtuoso SOAP Server
Web Services Routing Protocol (WS-Routing)
Web Services Reliable Messaging Protocol (WS-ReliableMessaging)
Web Services Trust Protocol (WS-Trust)
XML for Analysis Provider
XML-RPC support
SyncML
UDDI
Exposing Persistent Stored Modules as Web Services
Testing Web Published Web Services
BPEL Reference
Activities Protocol Support Process lifecycle Using virtual directories Process archiving Configuration parameters Process Statistics Deployment file suitcase format SQL API BPEL XPath Functions Tables Errors Samples References BPEL4WS VAD Package installation
XSQL

## 15.13. BPEL Reference

Introduction

Business Process Execution Language for Web Services (called BPEL4WS or simply BPEL in the rest of this chapter) provides a means of specifying interactions between web services for accomplishing a potentially long running business task.

Used terms

- WSDL

  Web Services Description Language as described in the corresponding W3C proposed recommendation. This is a notation for declaring services and the types of data they accept and produce. Also the term may be used to refer to the document containing a WSDL description.

- partner

  A service or application which interacts with a BPEL process.

- (BPEL) script

  A document containing BPEL compatible XML constructs.

- (BPEL process) instance

  An instance of a BPEL process, can be running, suspended, aborted or finished.

- activity

  An activity is a building block of a BPEL script. Receiving data, invoking other web services, programming language like control structures are all examples of activities.

- portType

  Container for set of abstract operations see below.

- operation

  An abstract black-box that have an XML input or/and output. Services potentially supports four types of operations: one-way, request-response, notification and solicit-response; this depends of input and/or output allowed and what is their order. The BPEL4WS uses one-way and request-response operations. Operations are grouped in 'ports' which define what operations a particular service supports.

- message

  An abstract XML fragment that is used for operation input and output. In particular this is used inside SOAP Envelope and for value of the BPEL variables. Also the WSDL specification specifies how abstract messages will be used as concrete messages using the SOAP protocol and which encoding will be used.

### 15.13.1. Activities

#### 15.13.1.1. Common attributes and elements

Every BPEL activity accepts the following standart attributes: 'name', 'joinCondition' and 'suppressJoinFailure'. The 'name' attribute is an optional unique within the script NCName (as defined in the XMLSchema) identifying the activity. The 'joinCondition' is a boolean expression which determine how incoming links' state will be tested, by default this is 'true()' which means the logical OR of the states of incoming links. The 'suppressJoinFailure' is a flag to raise or not exception if join condition fails, by default this is 'no'.

The common elements for every activity are 'target' and 'source'. These elements are used together with links and used to designate which link the current activity depends on or for which one it is a prerequisite. See also section for 'flow' activity below.

#### 15.13.1.2. receive

This allows the business process to do a blocking wait for a particular message to arrive.

A BPEL process instance is created by a receive activity with the createInstance attribute set to true.

partnerLink – name of a partner declared in the script from which the process is to receive a message.
portType – name of the 'port' as declared in corresponding WSDL file.
operation – name of the operation
variable – name of the variable to which the received message will be assigned.
createInstance – used to make instance of the BPEL process and start its execution.

    <receive partnerLink="ncname" portType="qname" operation="ncname"
        variable="ncname"? createInstance="yes|no"?
        standard-attributes>
        standard-elements
        <correlations>?
            <correlation set="ncname" initiate="yes|no"?/>+
        </correlations>
    </receive>

#### 15.13.1.3. reply

allows the business process to send a message in reply to a message that was received through a <receive>

partnerLink – name of a partner declared in the script to which to send a message.
portType – name of the 'port' as declared in corresponding WSDL file.
operation – name of the operation
variable – name of the variable whose value will be used as output message.
faultName –

    <reply partnerLink="ncname" portType="qname" operation="ncname"
        variable="ncname"? faultName="qname"?
        standard-attributes>
        standard-elements
        <correlations>?
            <correlation set="ncname" initiate="yes|no"?/>+
        </correlations>
    </reply>

#### 15.13.1.4. invoke

This allows the business process to invoke a one-way or request-response operation on a portType offered by a partner. When both 'inputVariable' and 'outputVariable' are specified this means request-response operation will be performed. Please note that the operation is defined primarily in the partner's WSDL.

partnerLink – name of a partner declared in the script to who send a message and optionally receive a response.
portType – name of the 'port' as declared in corresponding WSDL file.
operation – name of the operation to invoke
inputVariable – name of the variable whose value will be used as the message to the partner.
outputVariable – name of the variable to which the response will be assigned.

    <invoke partnerLink="ncname" portType="qname" operation="ncname"
        inputVariable="ncname"? outputVariable="ncname"?
        standard-attributes>
        standard-elements
        <correlations>?
            <correlation set="ncname" initiate="yes|no"?
                pattern="in|out|out-in"/>+
        </correlations>
        <catch faultName="qname" faultVariable="ncname"?>*
            activity
        </catch>
        <catchAll>?
            activity
        </catchAll>
        <compensationHandler>?
            activity
        </compensationHandler>
    </invoke>

#### 15.13.1.5. assign

can be used to update the values of variables with new data. An <assign> construct can contain any number of elementary assignments (copy sub-elements).

    <assign standard-attributes>
        standard-elements
        <copy>+
            from-spec
            to-spec
        </copy>
    </assign>

##### 15.13.1.5.1. from-spec

This represents in <copy> the right part of the assignment.

    <from variable="ncname" part="ncname"? query="xpath-expression"?/>
    <from partnerLink="ncname" endpointReference="myRole|partnerRole"/>
    <from variable="ncname" property="qname"/>
    <from expression="general-expr"/>
    <from>literal value</from>

##### 15.13.1.5.2. to-spec

This represents in <copy> the l-value of the assignment.

    <from variable="ncname" part="ncname"? query="xpath-expression"?/>
    <from partnerLink="ncname" endpointReference="myRole|partnerRole"/>
    <from variable="ncname" property="qname"/>

#### 15.13.1.6. throw

generates a fault from inside the business process

faultName – the fault code to be thrown.
faultVariable –

    <throw faultName="qname" faultVariable="ncname"? standard-attributes>
        standard-elements
    </throw>

#### 15.13.1.7. terminate

Used to immediately terminate the execution of a business process instance.

    <terminate standard-attributes>
        standard-elements
    </terminate>

#### 15.13.1.8. wait

Wait until a given point in time or for a specified duration.

for – an duration expression as defined in XMLSchema (for example PT10S)
until – an date time expression as defined in XMLSchema

    <wait (for="duration-expr" | until="deadline-expr") standard-attributes>
        standard-elements
    </wait>

#### 15.13.1.9. empty

insert a "no-op" instruction into a business process

    <empty standard-attributes>
        standard-elements
    </empty>

#### 15.13.1.10. sequence

define a collection of activities to be performed sequentially in lexical order

    <sequence standard-attributes>
        standard-elementsactivity+
    </sequence>

#### 15.13.1.11. switch

Select exactly one branch of activity from a set of choices

case – the branch which will be executed if 'condition' attribute returns true.
otherwise – will be executed if all 'case' conditions are evaluated to false.

    <switch standard-attributes>
        standard-elements
        <case condition="bool-expr">+
            activity
        </case>
        <otherwise>?
            activity
        </otherwise>
    </switch>

#### 15.13.1.12. while

Repeat activity while a condition is true.

condition – an XPath expression which will be evaluated every time before contained activities. If this evaluates to false the loop finishes.

    <while condition="bool-expr" standard-attributes>
        standard-elementsactivity
    </while>

#### 15.13.1.13. pick

This blocks and waits for a suitable message to arrive or for a time-out expire. When one of the events specified in the body of the pick occurs the pick completes. Only one of the activities in the body of the pick will actually take place.

createInstance – b This is an alternative of the 'receive' to make a new process instance. And can be expressed as: 'pick' plus 'onMessage' equals to 'receive' activity.

    <pick createInstance="yes|no"? standard-attributes>
        standard-elements
        <onMessage partnerLink="ncname" portType="qname"
            operation="ncname" variable="ncname"?>+
            <correlations>?
    	    <correlation set="ncname" initiate="yes|no"?/>+
    	</correlations>
    	activity
        </onMessage>
        <onAlarm (for="duration-expr" | until="deadline-expr")>*
    	activity
        </onAlarm>
    </pick>

##### 15.13.1.13.1. onMessage

This is to wait for an incoming message from given partner.

The attributes are the same as for receive activity

##### 15.13.1.13.2. onAlarm

This will register a time-wait object whose expiration will trigger the pick. Obviously no more than one can be specified in a given 'pick'

The attributes are the same as for the wait activity

#### 15.13.1.14. scope

defines a nested activity with its own associated variables, fault handlers, and compensation handler

variableAccessSerializable –

    <scope variableAccessSerializable="yes|no" standard-attributes>
        standard-elements
        <variables/>?
        <correlationSets/>?
        <faultHandlers/>?
        <compensationHandler/>?
        <eventHandlers/>?
        activity
    </scope>

#### 15.13.1.15. flow

Specifies one or more activities to be performed concurrently.

    <flow standard-attributes>
        standard-elements
        <links>?
            <link name="ncname"/>+
        </links>
        activity+
    </flow>

#### 15.13.1.16. compensate

This is used to invoke compensation on an inner scope that has already completed normally. This construct can be invoked only from within a fault handler or another compensation handler

    <compensate scope="ncname"? standard-attributes>
        standard-elements
    </compensate>

#### 15.13.1.17. compensationHandler

    <compensationHandler>?
        activity
    </compensationHandler>

#### 15.13.1.18. faultHandlers

    <faultHandlers>?
        <catch faultName="qname"? faultVariable="ncname"?>*
            activity
        </catch>
        <catchAll>?
            activity
        </catchAll>
    </faultHandlers>

##### 15.13.1.18.1. catch

This container will be executed whose 'faultName' attribute value matches the thrown fault.

##### 15.13.1.18.2. catchAll

This container will be executed if non of the 'catch' containers are matched, so if no 'catchAll' is specified, the contained scopes will be compensated and the fault will be re-thrown to the outer scope.

#### 15.13.1.19. eventHandlers

This is a container for events, thus it can contain onMessage or/and onAlarm events. Semantic of the onMessage and onAlarm is same as defined in pick activity, the difference is that here these can be executed asynchronously while the events of the defining scope are running. The events in an event handler section may thus interrupt the execution of the body of the scope. This feature can be used for supporting asynchronous cancel messages or timeouts imposed on a whole sequence of operations..

    <eventHandlers>?
        <onMessage partnerLink="ncname" portType="qname"
    	operation="ncname"
    	variable="ncname"?>*

    	<correlations>?
    	    <correlation set="ncname" initiate="yes|no"/>+
    	</correlations>
    	activity
        </onMessage>
        <onAlarm for="duration-expr"? until="deadline-expr"?>*
    	activity
        </onAlarm>
    </eventHandlers>

#### 15.13.1.20. exec

This is a specific extension of the Virtuoso BPEL implementation. The exec activity allows executing SQL code from inside a BPEL process without having to define a distinct SOAP service for this.

binding – only "SQL", "JAVA" and "CLR" are currently permitted.

    <bpelv:exec binding="SQL">
        insert into dummy values ('hello world');
    </bpelv:exec>

##### 15.13.1.20.1. SQL execution

The additional procedures BPEL.BPEL.setVariableData and BPEL.BPEL.getVariableData allow manipulating BPEL variables. See SQL API for details.

All errors occuring during the SQL execution are translated into BPEL errors.

##### 15.13.1.20.2. Java execution

###### Configuration

First of all, the java support in BPEL4WS is available only for java enabled virtuoso servers. In order to enable java support the following administration steps need to be taken:

- 1. Make java compiler (javac) available for virtuoso server
- 2. Enable "system" call by setting the AllowOSCalls? parameter in virtuoso.ini to 1.
- 3. Add "classlib" directory to CLASSPATH

After the BPEL4WS package has been installed, the server needs to be restarted.

The BPEL4WS package creates the classlib directory in the server's root with BpelVarsAdaptor?.class. This directory and this file are necessary for the proper operation of the Java interface.

###### Using java code in BPEL4WS

There are two elements which support java execution in BPEL4WS scripts: <bpelv:exec binding="JAVA" import?> (namespace is "http://www.openlinksw.com/virtuoso/bpel") and the Oracle compatible form <bpelx:exec import?> (namespace is "http://schemas.oracle.com/bpel/extension"). These tags are equal.

If the tag contains the "import" attribute the appropriate package will be imported. Example:

    <bpelx:exec import="java.util.*"/>

Otherwise, the included code will be executed. It is suggested to use <![CDATA[ statement for representing the java code. Example:

    <bpelx:exec>
       System.out.println("getVariableData returned: " + getVariableData ("request", "req_payload", "/v:destRequest/v:city"));

       setVariableData ("res",
             "repl_payload",
             "/v:destResponse/v:country",
             "KZ");
    </bpelx:exec>

The two "functions" are available for accessing script variables: setVariableData and getVariableData (analogs of the xpath functions with same names).

    void setVariableData (String var_name, String part, String query_path, Object value);

sets the variable. The value to be set is restricted to be string or integer in this version.

    getVariableData

is a full analog of xpath function getVariableData. See details below.

Note, the activity does not commit changes to the database until it finishes successfully, so if in a case of exception the variables are kept untouched. This also means that deadlocks can occur.

The communication errors must be handled and processed in the java code itself.

If some unhandled exception occurs in java code, it will be translated to a BPEL error. See details in the next section.

###### Errors

Two types of errors can be signaled:

- 1. upload time exceptions
- 2. runtime exceptions

The first type exceptions are related to configuration and java syntax errors. These are as follows:

- 1. [BPELX] The "system" call is disabled, it is needed for use java code in BPEL4WS scripts. * This error is signaled when the "AllowOSCalls" is set to 0. So the engine can not call java compiler. It One must set this parameter in ini file to 1 and restart the server to resolve this issue.
- 2. [BPELX] Compilation of java code for NAME failed. Try to call "javac NAME.java" for details. * The compilation of generated class for the activity has failed. Try to call the suggested operation from command prompt whith the same PATH and CLASSPATH global variables to see the javac output.

Runtime errors not handled by java method itself are translated to the BPEL fault in the following form:

    <bpws:javaFault sqlState="SQLSTATE">
     error message
    </bpws:javaFault>

this error can be handled by BPEL fault handler. Here is an example:

    ...
        <receive partnerLink="caller" portType="v:dest" operation="check_dest" variable="request" createInstance="yes"/>
        <scope>
          <faultHandlers>
            <catch faultName="bpws:javaFault" faultVariable="error">
              <assign>
                <copy>
                  <from variable="error" query="/javaFault"/>
                  <to variable="res" part="repl_payload" query="/destResponse/country"/>
                </copy>
              </assign>
            </catch>
          </faultHandlers>
          <bpelv:exec binding="JAVA" name="invokeSomething"><![CDATA[
       System.out.println("Executing Java exec in BPEL");
       System.out.println("getVariableData returned: " + getVariableData ("request", "req_payload", "/v:destRequest/v:city"));

       setVariableData ("res",
             "repl_payload",
             "/destResponse/country",
             "UK");
       if (true)
         throw (new Exception("test"));
       ]] >
           </bpelv:exec>
         </scope>
        <reply partnerLink="caller" portType="v:dest" operation="check_dest" variable="res"/>
    ...

In this code the handler for java exception is set:

    ...
            <catch faultName="bpws:javaFault" faultVariable="error">
              <assign>
                <copy>
                  <from variable="error" query="/javaFault"/>
                  <to variable="res" part="repl_payload" query="/destResponse/country"/>
                </copy>
              </assign>
            </catch>
    ...

The handler takes the error message from the variable which holds it ("error") and puts it into the response variable.

###### BPEL variables accessors

    void setVariableData (String var_name, String part, String query_path,
    	    Object value)

- changes BPEL variable named var_name. The "part" is a part of the message stored in the variable. "query_path" selects the data in the variable to be changed. The "value" can be only string or integer, so if several subdata need to be changed the setVariableData must be called several times. If the "part" and "query_path" must be ignored their can be passed as empty strings ("").

    String getVariableData (String var_name, String part, String query)

- returns selected data from the part named by "part" argument of variable named by "var_name" argument. If the selection failed the NULL is returned.

###### Special variables

There are two special variables: "variables" and "xmlnss_pre". They can be changed in the java code, in this case the behaviour of the engine is unpredictable. So, it is strongly recommended do not use these variables.

###### JavaMail usage example

    <?xml version="1.0"?>
    <process xmlns:jsm="urn:java:sendMail"
    	xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/"
    	name="javaSendMail"
    	targetNamespace="urn:java:sendMail"
    	xmlns:bpelx="http://schemas.oracle.com/bpel/extension"
    	xmlns:bpelv="http://www.openlinksw.com/virtuoso/bpel">

      <bpelv:exec binding="JAVA" import="java.io.*"/>
      <bpelv:exec binding="JAVA" import="java.net.InetAddress"/>
      <bpelv:exec binding="JAVA" import="java.util.Properties"/>
      <bpelv:exec binding="JAVA" import="java.util.Date"/>
      <bpelv:exec binding="JAVA" import="javax.mail.*"/>
      <bpelv:exec binding="JAVA" import="javax.mail.internet.*"/>
      <bpelv:exec binding="JAVA" import="com.sun.mail.smtp.*"/>

      <partnerLinks>
        <partnerLink name="caller" partnerLinkType="jsm:dest"/>
      </partnerLinks>

      <variables>
        <variable name="request" messageType="jsm:destRequestMessage"/>
        <variable name="res" messageType="jsm:destResponseMessage"/>
      </variables>
      <sequence>
        <receive partnerLink="caller" portType="jsm:dest" operation="send" variable="request" createInstance="yes"/>
        <bpelv:exec binding="JAVA" name="sendMail"><![CDATA[
    	String  to, subject = null, from = null;
    	String mailhost = (String) getVariableData ("request", "req_payload", "/jsm:destRequest/jsm:mailhost");
    	String mailer = "OpenLink Virtuoso[BPEL script]";
    	try {
            	to = (String) getVariableData ("request", "req_payload", "/jsm:destRequest/jsm:to");
    	        subject = (String) getVariableData ("request", "req_payload", "/jsm:destRequest/jsm:subject");

    		Properties props = System.getProperties();
    		props.put("mail.smtp.host", mailhost);
    		Session session = Session.getInstance(props, null);

    		Message msg = new MimeMessage(session);
    		if (from != null)
    			msg.setFrom(new InternetAddress(from));
    		else
    			msg.setFrom();
    		msg.setRecipients(Message.RecipientType.TO,
    					InternetAddress.parse(to, false));
    		msg.setSubject(subject);
    	        msg.setText ((String)getVariableData ("request", "req_payload", "/jsm:destRequest/jsm:text"));

    		msg.setHeader("X-Mailer", mailer);
    		msg.setSentDate(new Date());
    		SMTPTransport t = (SMTPTransport)session.getTransport("smtp");
    		try {
    		    t.connect();
    		    t.sendMessage(msg, msg.getAllRecipients());
    		} finally {
    		    System.out.println("Response: " +
    						t.getLastServerResponse());
    		    t.close();
    		}

    	    	System.out.println("\nMail was sent successfully.");
    		setVariableData ("res",
    			"repl_payload",
    			"/jsm:destResponse/jsm:status",
    			"OK");

    	} catch (Exception e) {
    	    String err_str = "Failed: " + e.toString();
    	    e.printStackTrace();
    	    if (e instanceof SendFailedException) {
    		MessagingException sfe = (MessagingException)e;
    		if (sfe instanceof SMTPSendFailedException) {
    		    SMTPSendFailedException ssfe =
    				    (SMTPSendFailedException)sfe;
    		    System.out.println("SMTP SEND FAILED:");
    		    System.out.println(ssfe.toString());
    		    System.out.println("  Command: " + ssfe.getCommand());
    		    System.out.println("  RetCode: " + ssfe.getReturnCode());
    		    System.out.println("  Response: " + ssfe.getMessage());
    		} else {
    			System.out.println("Send failed: " + sfe.toString());
    		}
    		Exception ne;
    		while ((ne = sfe.getNextException()) != null &&
    			ne instanceof MessagingException) {
    		    sfe = (MessagingException)ne;
    		    if (sfe instanceof SMTPAddressFailedException) {
    			SMTPAddressFailedException ssfe =
    					(SMTPAddressFailedException)sfe;
    			System.out.println("ADDRESS FAILED:");
    			System.out.println(ssfe.toString());
    			System.out.println("  Address: " + ssfe.getAddress());
    			System.out.println("  Command: " + ssfe.getCommand());
    			System.out.println("  RetCode: " + ssfe.getReturnCode());
    			System.out.println("  Response: " + ssfe.getMessage());
    		    } else if (sfe instanceof SMTPAddressSucceededException) {
    			System.out.println("ADDRESS SUCCEEDED:");
    			SMTPAddressSucceededException ssfe =
    					(SMTPAddressSucceededException)sfe;
    			System.out.println(ssfe.toString());
    			System.out.println("  Address: " + ssfe.getAddress());
    			System.out.println("  Command: " + ssfe.getCommand());
    			System.out.println("  RetCode: " + ssfe.getReturnCode());
    			System.out.println("  Response: " + ssfe.getMessage());
    		    }
    		}
    	    }
    	    setVariableData ("res",
    			"repl_payload",
    			"/jsm:destResponse/jsm:status",
    			err_str);
    	}

    	]] ></bpelv:exec>
        <reply partnerLink="caller" portType="jsm:dest" operation="send" variable="res"/>
      </sequence>
    </process>

and support WSDL file:

    <?xml version="1.0"?>
    <definitions name="javaSendMail"
      targetNamespace="urn:java:sendMail"
      xmlns:jsm="urn:java:sendMail"
      xmlns:plnk="http://schemas.xmlsoap.org/ws/2003/05/partner-link/"
      xmlns="http://schemas.xmlsoap.org/wsdl/">
      <types>
        <schema attributeFormDefault="qualified" elementFormDefault="qualified"
          targetNamespace="urn:java:sendMail"
          xmlns="http://www.w3.org/2001/XMLSchema">
          <element name="destRequest">
            <complexType>
              <sequence>
                <element name="mailhost" type="string"/>
                <element name="to" type="string"/>
                <element name="subject" type="string"/>
                <element name="text" type="string"/>
              </sequence>
            </complexType>
          </element>
          <element name="destResponse">
            <complexType>
              <sequence>
    	    <element name="status" type="string"/>
              </sequence>
            </complexType>
          </element>
        </schema>
      </types>
      <message name="destRequestMessage">
        <part name="req_payload" element="jsm:destRequest"/>
      </message>
      <message name="destResponseMessage">
        <part name="repl_payload" element="jsm:destResponse"/>
      </message>
      <portType name="dest">
        <operation name="send">
          <input  message="jsm:destRequestMessage" />
          <output message="jsm:destResponseMessage"/>
        </operation>
       </portType>
       <plnk:partnerLinkType name="dest">
         <plnk:role name="destProvider">
           <plnk:portType name="jsm:dest"/>
         </plnk:role>
       </plnk:partnerLinkType>
    </definitions>

##### 15.13.1.20.3. .NET CLR execution

###### Configuration

The CLR is available only for CLR enabled Virtuoso servers. In order to configure the server for CLR support in BPEL4WS engine the following administration steps need to be taken:

- 1. Initiate "CLRAssembliesDir" configuration entry ("Directory where .NET CLR assemblies must be stored") by the path where "virt_bpel4ws.dll", "virtclr.dll" etc are stored.

###### Using the C# code in BPEL4WS

The tag for supporting CLR is <exec binding="CLR" [using | ref ]>.

<exec> with "using" attribute relates to "using" directive in C# code.

    <bpelv:exec binding="CLR" using="System"/>

in BPEL file is a substitution of

    using System;

statement in the C# code.

To import assemblies (with a manifest) the <exec> element with "ref" attribute must be used:

    <bpelv:exec binding="CLR" ref="metad1.dll"/>
    <bpelv:exec binding="CLR" ref="d:\\myassemblies\\sms_service.dll"/>

If the tag does not contain these attributes then the content of the tag is treated as C# code. It is suggested to use CDATA sections for the code. Example:

    <bpelv:exec binding="CLR" name="invokeSomething"><![CDATA[

    	Console.WriteLine("Executing CLR assembly in BPEL");
    	Console.WriteLine("getVariableData returned: " + getVariableData ("request", "req_payload", "/tns:destRequest/tns:city"));

    	setVariableData ("res",
    			"repl_payload",
    			"/destResponse/country",
    			"UK");
    ]] ></bpelv:exec>

Two "functions" are available for accessing script variables: setVariableData and getVariableData (analogs of the xpath functions with same names).

    void setVariableData (String var_name, String part, String query_path, Object value);

sets the variable. The value to be set is restricted to be string or integer in this version.

    Object getVariableData (String var_name, String part, String query)

is a full analog of xpath function getVariableData. See details below.

Note, the activity does not commit changes to the database until it finishes successfully, so in a case of exception the variables are kept untouched. This also means that deadlocks can not occur during C# code execution (naturally, this statement is not true if the code contains direct invokation of SQL through the "in-process" .NET provider).

If the some unhandled exception occured in C# code, it will be translated to a BPEL error. See details in the next section.

###### Runtime Errors

Runtime errors not handled by CLR itself are translated to the BPEL fault in the following form:

    <bpws:clrFault sqlState="SQLSTATE">
     error message
    </bpws:javaFault>

this error can be handled by BPEL fault handler. Here is an example:

    ...
        <scope>
          <faultHandlers>
            <catch faultName="bpws:clrFault" faultVariable="error">
              <assign>
                <copy>
                  <from variable="error" query="/clrFault/text()"/>
                  <to variable="res" part="repl_payload" query="/clr:destResponse/clr:status"/>
                </copy>
              </assign>
            </catch>
          </faultHandlers>
          <bpelv:exec binding="CLR" name="Hotmail"><![CDATA[
    	     String login, passwd;
            	login = (String) getVariableData ("request", "req_payload", "/clr:destRequest/clr:login");
    	       	passwd = (String) getVariableData ("request", "req_payload", "/clr:destRequest/clr:password");
    		Console.WriteLine ("user:" + login + " password:" + passwd);

    		HotmailUsage usage = new HotmailUsage();
    		Console.WriteLine ("Result: " + usage.Call_Hotmail (login, passwd));

    		setVariableData ("res",
    			"repl_payload",
    			"/clr:destResponse/clr:status",
    			"OK");
    	]] ></bpelv:exec>
    	</scope>
        <reply partnerLink="caller" portType="clr:dest" operation="send" variable="res"/>
    ...

In this code the handler for CLR exception is set:

    ...
            <catch faultName="bpws:clrFault" faultVariable="error">
              <assign>
                <copy>
                  <from variable="error" query="/clrFault/text()"/>
                  <to variable="res" part="repl_payload" query="/clr:destResponse/clr:status"/>
                </copy>
              </assign>
            </catch>
    ...

The handler takes the error message from the variable which holds it ("error") and puts it into the response variable.

###### BPEL variable accessors

The name and the signature of BPEL accessors for CLR are fully equal to the java accessors. See java section for details.

###### Special variables

The special variables for CLR are the same as for Java. See java section for details.

###### CLR Sample

    <?xml version="1.0"?>
    <process xmlns:clr="urn:clr:Hotmail"
            xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/"
            name="clrHotmail"
            targetNamespace="urn:clr:Hotmail"
            xmlns:bpelx="http://schemas.oracle.com/bpel/extension"
            xmlns:bpelv="http://www.openlinksw.com/virtuoso/bpel">

      <bpelv:exec binding="CLR" using="HotmailUsageChecker"/>
      <bpelv:exec binding="CLR" ref="l:\\distrib_3_0\\bin\\Hotmail.dll"/>
      <bpelv:exec binding="CLR" using="System"/>

      <partnerLinks>
        <partnerLink name="caller" partnerLinkType="clr:dest"/>
      </partnerLinks>

      <variables>
        <variable name="request" messageType="clr:destRequestMessage"/>
        <variable name="res" messageType="clr:destResponseMessage"/>
      </variables>
      <sequence>
        <receive partnerLink="caller" portType="clr:dest" operation="send" variable="request" createInstance="yes"/>
        <scope>
          <faultHandlers>
            <catch faultName="bpws:clrFault" faultVariable="error">
              <assign>
                <copy>
                  <from variable="error" query="/clrFault/text()"/>
                  <to variable="res" part="repl_payload" query="/clr:destResponse/clr:status"/>
                </copy>
              </assign>
            </catch>
          </faultHandlers>
          <bpelv:exec binding="CLR" name="Hotmail"><![CDATA[
                 String login, passwd;
                    login = (String) getVariableData ("request", "req_payload", "/clr:destRequest/clr:login");
                    passwd = (String) getVariableData ("request", "req_payload", "/clr:destRequest/clr:password");
                    Console.WriteLine ("user:" + login + " password:" + passwd);

                    HotmailUsage usage = new HotmailUsage();
                    Console.WriteLine ("Result: " + usage.Call_Hotmail (login, passwd));

                    setVariableData ("res",
                            "repl_payload",
                            "/clr:destResponse/clr:status",
                            "OK");
            ]]></bpelv:exec>
            </scope>
        <reply partnerLink="caller" portType="clr:dest" operation="send" variable="res"/>
      </sequence>
    </process>

### 15.13.2. Protocol Support

The Virtuoso BPEL implementation supports WS Security and WS Reliable Messaging. These protocols may be enabled and configured for individual partner links. The WS-Addressing protocol is automatically used when the partner has such capabilities.

The Partner link options are stored in XML format in the 'BPEL.BPEL.partner_link_init' table in 'bpl_opts' column. See the document format and table description below in this chapter.

#### 15.13.2.1. WS-Addressing (WSA)

WS-Addressing is transparently handled via WSDL description and request of the partner(s). If the partner has WSA headers exposed then the corresponding operation will be invoked with WSA headers. If the partner uses WSA to call the BPEL service then the service will respond to the partner with WSA headers included.

The benefit of using WSA consists in transparently handled message correlation via "MessageID" and "RelatesTo" headers. Thus no explicit message correlation needs to be specified when the partner is WSA capable (see LoanFlow demo in tutorials to see how this works). Also when the reply is asynchronous the return path can be handled via the "ReplyTo" WSA headers.

As WSA has different revisions that are supported by different implementations (partners), the version of the protocol is configurable via wsOptions/addressing element (see below).

The 'wsa' partner link option can be used in API functions to set or retrieve the value of the wsOptions/addressing.

#### 15.13.2.2. WS-Security (WSS)

There are several cases where privacy and confidentiality must be observed , this is especially true when business processes involve payment systems, personal information etc. In those cases a partner may, depending on Web Service policy, require secure messages (signed, encrypted or both). Such partners usually do not expose (for many reasons) in WSDL the WSS headers, hence this must be configured by the BPEL administrator per partner.

In order for the BPEL server to be able to sign and encrypt messages keys have to be uploaded into the BPEL user repository. This can be done with the USER_KEY_LOAD() function or using the BPEL GUI (Partner Link properties).

It is important to know the following basics:

- The private key is needed in order to decrypt or sign messages.
- The partner public key is needed to encrypt messages or verify signatures.

These keys have to be described in wsOptions/security/key and wsOptions/security/pubkey in the 'Partner link options' XML document. Note that in the options document are stored only the names of the keys, as the keys themselves are registered in the BPEL user key repository.

Note: Use the 'wss-priv-key' and 'wss-pub-key' partner link option in API functions to set or change the value of them.

The encryption and signing is independently configurable for outbound or inbound messages. This is settable via the following options:

- wsOptions/security/in/encrypt - 'Optional': inbound message MAY be encrypted, 'Mandatory': inbound message MUST be encrypted ('wss-in-encrypt' option in API)
- wsOptions/security/in/signature - same as encryption but for XML signature ('wss-in-signature' option in API)
- wsOptions/security/in/keys - this is a list of keys (key names) that are trusted; only SOAP messages signed with one of these keys will be accepted. If this list is empty, all parties will be accepted unless signature is invalid or message can not be decrypted. ('wss-in-signers' option in API)
- wsOptions/security/out/encrypt - type of the session key for encryption 3DES, AES128, AES192 or AES256. ('wss-out-encrypt-key' option in API)
- wsOptions/security/out/signature - 'Default': the WSS default template (see WS-Security chapter for details), 'Custom': in this case 'function' attribute must refer to a PL procedure returning XML Signature template. ('wss-out-signature-type' and 'wss-out-signature-function' options in API)

#### 15.13.2.3. WS-Reliable Messaging (WSRM)

The WSRM is applicable for those parters which can be invoked asynchronously. For both inbound or outbound (from the point of view of the process) WSRM can be enabled. The options are settable in wsOptions/delivery/in or wsOptions/delivery/out ('wsrm-in-type' and 'wsrm-out-type' options in API) respectively.

- ExactlyOnce - message will be delivered only once to the destination.
- InOrder - messages will be delivered in the same order as they are sent from the script.

#### 15.13.2.4. HTTP security

Some partner services may require HTTPS or/and HTTP authentication instead of using WS-Security protocol to ensure SOAP message privacy.

When a partner's endpoint URL contains HTTPS scheme (like https://) the request and response operations will be made with HTTP over SSL (HTTPS protocol). In this case no additional options to the partner links are needed.

In case when a partner service needs a HTTP authentication, the user name and password (for that service) needs to be configured for the given partner link. These are settable via wsOptions/security/http-auth ('http-auth-uid' and 'http-auth-pwd' options in API) element in partner link options. Note that only basic HTTP authentication is supported.

Partner link options format

    <wsOptions>
        <!-- WSA revision namespace -->
        <addressing version="http://schemas.xmlsoap.org/ws/2003/03/addressing|http://schemas.xmlsoap.org/ws/2004/03/addressing"/|http://schemas.xmlsoap.org/ws/2004/08/addressing>
      <!-- WSS options -->
      <security>
          <!-- basic HTTP Authentication -->
          <http-auth username="" password=""/>
          <!-- WSS keys -->
          <key name="[Private Key]"/>
          <pubkey name="[Partner public key]"/>
        <in>
          <encrypt type="NONE|Optional|Mandatory"/>
          <signature type="NONE|Optional|Mandatory" />
          <keys>
    	  <!-- trusties -->
    	  <key name="[Trusted Public Key]"/>
    	  ...
          </keys>
        </in>
        <out>
    	<encrypt type="NONE|3DES|AES128|AES192|AES256"/>
    	<signature type="NONE|Default|Custom" function="[PL procedure name]"/>
        </out>
      </security>
      <!-- WSRM options -->
      <delivery>
        <in  type="NONE|ExactlyOnce|InOrder"/>
        <out type="NONE|ExactlyOnce|InOrder" />
      </delivery>
    </wsOptions>

#### 15.13.2.5. Configuring the Partner link options

The partner link options can be configured vi BPEL UI (http://host:port/BPELGUI) or programatically using plink_get_option() and plink_set_option() functions. It is possible to update the partner link options with SQL update statement using the configuration (described above), but use of the BPEL UI or API functions is recommended.

#### 15.13.2.6. Dynamic Partner Links

The 'assign' activity allows partner links to be assigned values at run time. This means that partner links can be dynamic and that a process may call partners that were not known at the time of defining the process. Partner links can be defined at run time using the 'EndpointReference' element from the WS-Addressing specification :

      <xs:element name="EndpointReference" type="wsa:EndpointReferenceType"/>
      <xs:complexType name="EndpointReferenceType">
        <xs:sequence>
          <xs:element name="Address" type="wsa:AttributedURI"/>
          <xs:element name="ReferenceProperties" type="wsa:ReferencePropertiesType" minOccurs="0"/>
          <xs:element name="PortType" type="wsa:AttributedQName" minOccurs="0"/>
          <xs:element name="ServiceName" type="wsa:ServiceNameType" minOccurs="0"/>
          <xs:any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded" />
        </xs:sequence>
        <xs:anyAttribute namespace="##other" processContents="lax"/>
      </xs:complexType>

Thus it may keep endpoint URL, Port type, Service name and any number of implementation specific options under 'ReferenceProperties'. Also it may keep any other extensible elements and attributes.

The Virtuoso BPEL implementation extends the EndpointReferenceType with element 'wsOptions' under WSA element 'ReferenceProperties' (see previous section for 'wsOptions' element description). Thus it is possible to decide at run time to send a secure reply (WSS) or to use reliable messaging (WSRM). The following excerpt shows BPEL source that assigns WS Security options to a partner link:

          ...
          <assign>
    	  <copy>
    	      <from>
    		  <EndpointReference xmlns="http://schemas.xmlsoap.org/ws/2003/03/addressing">
    		      <Address>http://securehost/myService</Address>
    		      <ReferenceProperties>
    			  <wsOptions xmlns="">
    			      <addressing version="http://schemas.xmlsoap.org/ws/2003/03/addressing"/>
    			      <security>
    				  <http-auth username="" password=""/>
    				  <key name="myKey"/>
    				  <pubkey name="serverKey"/>
    				  <in>
    				      <encrypt type="Optional"/>
    				      <signature type="Optional" />
    				      <keys/>
    				  </in>
    				  <out>
    				      <encrypt type="AES128"/>
    				      <signature type="Default"/>
    				  </out>
    			      </security>
    			  </wsOptions>
    		      </ReferenceProperties>
    		  </EndpointReference>
    	      </from>
    	      <to partnerLink="service"/>
    	  </copy>
          </assign>
          ...

To manipulate the partner link options and endpoint URL we can also use variables declared as element EndpointReference from WS-Addressing schema.

### 15.13.3. Process lifecycle

A BPEL process may have more than one version during development or maintenance in production environment. This means the process may have a more than one copy on the server where one of these copies is current all others are either obsolete or in the process of being defined . We will call these states further in this section as 'current', 'obsolete' or 'edit' (versions). The link between these versions is the process name which remains the same during process life-cycle.

When a process is compiled for the first time it becomes 'current'. The current version of a process is the one that was most recently compiled without errors. Only a current version of a process can make new instances in response to receiving messages. For a single process name only one version can be current at any one time. The other compiled versions of the process are always obsolote, meaning that new instances cannot be created but that old instances may proceed and complete.

The 'obsolete' version can not crate new process instances, it may only receive messages for its instances which are still running or suspended. In other words the old process instances will continue and any new instances will be instances of the current version.

The 'edit' state means that a new copy of the process is created but it is still not compiled. After successful compilation, a process in the edit state is set into the current state and the formerly current process is set to the the obsolete state.

All process versions may have only one endpoint corresponding to the process. The BPEL administrator MUST take care about endpoints to make sure that clients using the process are compatible with different process versions. This means that if changes in new versions are for example in the logic but not in the process' WSDL then new endpoint is not needed in most cases; furthermore in this case clients will be compatible with new input and output message structure; except in the case where the same messages are used with logically different meaning. So when a new process version involves significant change to messages then the new process should have a new endpoint and WSDL description.

### 15.13.4. Using virtual directories

To allow a process to make new instances or to receive messages from remote services in asynchronous way it needs an endpoint. Endpoint means an URL that allows to accept and process known SOAP messages.

Every process has a default endpoint which is accessible via the 'http://[host:port]/BPELGUI/bpel.vsp?script=[process_name]' URL. Also it has a default WSDL document describing the process at URL http://[host:port]/BPELGUI/bpel.vsp?script=[process_name]&wsdl. Upon compilation a different virtual directory can be specified for the process. For example if '/Service' is specified the 'http://[host:port]/Service' would be the endpoint URL also in this case the WSDL will be available on 'http://[host:port]/Service?wsdl'.

It is important to note that changing the virtual directory when a process is redefined will force all clients to update their configuration. This is the case when a major changes are made to the process and clients need to be re-linked against new WSDL. So when changes are small there will be no need of a new virtual directory. (See section 'Process life-cycle' above for process versions).

### 15.13.5. Process archiving

When an instance of a BPEL process is completed it will be archived and purged from system after a configurable time interval. The interval is settable via 'InstanceExpiryDelay' configuration option (see below how to change). The default interval for archiving is one day.

The archive file contains status of the instance which is archived, execution path of the activities when execution is completed, value of the variables and partner links.

The format of the archive file is as follows:

    <instances>
      <instance id="[instance id]">
        <status code="[2 - success |3 - error]" error="[error description]"/>
        <execution>
    	<node id="[activity id]" type="[activity type]"/>
    	... more nodes may follow ...
        </execution>
        <variables>
    	<variable name="[name of the variable]">... variable value ...</variable>
    	... more variables may follow ...
        </variables>
        <partnerLinks>
          <partnerLink name="[name of the partner link]">
            <EndpointReference>
    	    <Address>... partner link endpoint ...</Address>
            </EndpointReference>
          </partnerLink>
          ... more partner links may follow ...
        </partnerLinks>
      </instance>
    </instances>

### 15.13.6. Configuration parameters

The BPEL engine has global configuration parameters settable via the configuration settings page of its web user interface. These are global and are kept in the BPEL..configuration table as name/value pairs.

- EngineMailAddress - e-mail address to whom will be sent error alerts and reports.
- ErrorAlertSkeleton - e-mail template for error alerts
- ErrorReportSkeleton - e-mail template for error reports
- AlertSubject - Subject for error alert e-mail
- CommonEmailHeader - Header for all BPEL e-mail notifications
- ErrorSubject - Subject for error report e-mail
- InstanceExpiryDelay - how long (hours a completed instance will be kept in the database before purging.
- MailServer - if specified this will be used to send the error alerts and reports. If this is not specified the default (from INI file) mail server will be used.
- Statistics - process statistics flag, if 0 (default) the statistics collection is disabled. When this is 1 the engine will start collecting statistics for new process instances .

### 15.13.7. Process Statistics

The BPEL process can be set to collect statistics, this can be enabled by turning on the statistics flag (see Configuration section). If the statistics flag is on the following data is available:

- count of instance creations per instance creating partner link
- count/duration/data volume of invokes per invoked syncronous partner link
- count/data volume per asynchronous partner link
- waiting time/count/data volume at non-instance creating receives
- average time to complete for process
- Errors per partner link
- count of created instances
- count of completed instances
- count of instances that could not terminate successfully

### 15.13.8. Deployment file suitcase format

The relation between a BPEL process and different partner links can be stored in a deployment file. This file contains a description for every partner link mention in the process. The descriptor file simplifies deployment. Entering the URL of this file through the web administration interface will download and register all sources needed for the process compilation.

The format of the deployment file is as follows:

        <BPELSuitcase>
            <BPELProcess id="[process id]" src="[URI of the file containing BPEL script]">
    		<partnerLinkBindings>
    			<partnerLinkBinding name="[name of the partner]">
    			    <property name="wsdlLocation">[URI of the WSDL for the partner]</property>
    			</partnerLinkBinding>
    			... more partnerLinkBinding may follow ...
    		</partnerLinkBindings>
    	</BPELProcess>
        </BPELSuitcase>

### 15.13.9. SQL API

The following API functions are available:

BPEL.BPEL.compile_script (in scp_id int, in vdir varchar (default null), in opts any (default null), in no_check int (default 0));

Compile a BPEL script source

BPEL.BPEL.copy_script (in scp_id int);

Makes a copy of an existing script

BPEL.BPEL.get_partner_links (in scp_id int);

Retrurns a list of partner links used in the BPEL script

BPEL.BPEL.instance_delete (in id int);

delete a BPEL process instance

BPEL.BPEL.purge_instance (in completed_before datetime, in make_archive int (default 1));

removes old BPEL process instances

BPEL.BPEL.script_delete (in script varchar, in delete_instances int);

Remove a BPEL process

BPEL.BPEL.script_obsolete (in script varchar);

mark a BPEL script as obsoleted

BPEL.BPEL.script_source_update (in scp_id int, in url varchar, in content any);

Updates an existing script in BPEL repository

BPEL.BPEL.script_upload (in name varchar, in url varchar, in content any);

Upload a new BPEL script source

BPEL.BPEL.wsdl_upload (in scp_id int, in url varchar, in content any, in pl varchar default 'wsdl');

Uploads a WSDL description for a given BPEL script

BPEL.BPEL.plink_get_option (in script varchar, in plink varchar, in opt varchar);

retrieving a partner link option

BPEL.BPEL.plink_set_option (in script varchar, in plink varchar, in opt varchar, in val any);

set value of a partner link option

BPEL.BPEL.import_script (in base_uri varchar, in base_name varchar, in scp_id int);

Import a new BPEL process

### 15.13.10. BPEL XPath Functions

BPEL.BPEL.getVariableData (in var_name varchar, in part varchar, in query varchar);

gets BPEL variable data within <bpelv:exec binding="SQL"> activity

BPEL.BPEL.setVariableData (in var_name varchar, in value any, in part varchar, in query varchar);

sets BPEL variable data within code invoked from <bpelv:exec binding="SQL"> activity

any processXQuery ( module_uri string, [context entity], [index integer], [param1_name string], [param1_value any], ... [paramN_name string], [paramN_value any]);

Calls an XQuery module from XPath expression, e.g. from some XSLT or BPEL code.

entity processXSLT ( stylesheet_uri string, [source entity], [param1_name string], [param1_value any], ... [paramN_name string], [paramN_value any]);

Applies stylesheet to given XML entity and returns the result.

entity processXSQL ( xsql_page_uri string);

Executes XSQL page and returns the result.

### 15.13.11. Tables

BPEL Engine Tables

    -- Scripts table, keeps one record per version
    create table BPEL.BPEL.script (
    	bs_id integer identity, 	-- unique id identifying the process
    	bs_uri varchar,			-- obsoleted: script source URI
    	bs_name varchar,		-- process name, all versions have same name
    	bs_state int, 			-- 0 on, current version, 1 obsolete, 2 edit mode
    	bs_date	datetime,		-- date of registration
    	bs_audit int default 0, 	-- audit flag : 1 on, 0 off
    	bs_debug int default 0,		-- debug flag
    	bs_version int default 0,	-- process version
    	bs_parent_id int default null,	-- fk to bs_id of previous process version
    	bs_first_node_id int,  		-- the first node id in the graph
    	bs_pickup_bf varbinary default '\x0',	-- bitmask for resume nodes
    	bs_act_num	int, 		-- stores the total number of activities
    	bs_lpath	varchar default null, -- virtual directory

    	-- process statistics
    	bs_n_completed int default 0,
    	bs_n_errors int default 0,
    	bs_n_create int default 0,
    	bs_cum_wait int default 0,
    	primary key (bs_id));

    -- BPEL and WSDL sources
    create table BPEL..script_source
    	(
    	 bsrc_script_id int, -- script id, fk to bs_id of scripts table.
    	 bsrc_role varchar,  -- one of bpel, bpel-ext, wsdl, deploy, partner-1... partner-n
    	 bsrc_text long xml, -- source text
    	 bsrc_url varchar,   -- if this comes from an uri
    	 bsrc_temp varchar,  -- contains the namespaces info
    	 primary key (bsrc_script_id, bsrc_role)
    )
    ;

    -- Process instances
    create table BPEL.BPEL.instance (
    	bi_id int identity,   		-- global immutable id of instance
    	bi_script int,  		-- fk to bs_id from BPEL.BPEL.script
    	bi_scope_no int default 0,  	-- sequence counter for scope numbers in instance
    	bi_state int default 0,
    		-- 0, started
    		-- 1, suspended (wait for signal)
    		-- 2, finished
    		-- 3, aborted
    	bi_error any,			-- error
    	bi_lerror_handled int,
    	bi_last_act	datetime,	-- last activity execution
    	bi_started	datetime,	-- start time
    	bi_init_oper	varchar,	-- operation that made the instance
    	bi_wsa		long xml,	-- WS-Addressing headers
    	bi_activities_bf varbinary default '\x0\x0', -- bitmask for each activity is completed or not
    	bi_link_status_bf varbinary default '\x0\x0', -- bitmask for link status
    	bi_prefix_info varchar default '', -- xpath prefix string
    	primary key (bi_id));

    -- Initial values (URL etc.) for partner links
    create table BPEL.BPEL.partner_link_init (
    	bpl_script int, 	-- script instance id
    	bpl_name varchar,	-- partner link name
    	bpl_partner any,  	-- url, end point etc serialized
    	bpl_role varchar,
    	bpl_myrole varchar,
    	bpl_type varchar,
    	bpl_endpoint varchar,	-- partner service endpoint URL
    	bpl_backup_endpoint varchar,
    	bpl_wsdl_uri varchar,
    	bpl_debug int default 0,-- debug flag
    	bpl_opts long xml,	-- partner link options (WS-Security, WS-RM etc.)
    	primary key (bpl_script,bpl_name));

    -- Runtime values for partner links (run time copy of partner_link_init table)
    create table BPEL..partner_link (
    	pl_inst int, 		-- instance id
    	pl_name varchar, 	-- partner link name
    	pl_scope_inst int, 	-- scope instance id
    	pl_role int, 		-- flag 0 - myRole, 1 - partnerRole
    	pl_endpoint varchar, 	-- current URL to the partner service
    	pl_backup_endpoint varchar, -- second URL to the service for connection error
    	pl_debug int default 0,	-- debug flag
    	pl_opts long xml,	-- partner link options (WS-Security, WS-RM etc.)
    	primary key (pl_inst, pl_name, pl_scope_inst, pl_role));

    -- Script compilation
    create table BPEL.BPEL.graph (
    	bg_script_id int,  	-- FK to bs_id of BPEL.BPEL.script
    	bg_node_id int , 	-- running id in the script, referenced from BPEL.BPEL.waits etc.
    	bg_activity BPEL.BPEL.activity, -- UDT representing activity
    	bg_childs any,
    	bg_parent int,
            bg_src_id varchar,	-- internal use
    	primary key (bg_script_id, bg_node_id));

    -- Receive activities waiting for incoming message
    create table BPEL.BPEL.wait (
    	bw_uid varchar,
    	bw_instance integer,  -- instance id
    	bw_script varchar,    -- FK reference to bs_name of script table
    	bw_script_id int,     -- FK reference to bs_id of script table
    	bw_node int,	      -- FK reference to bg_node_id of the graph table
    	bw_scope  int,
    	bw_partner_link varchar, -- the party from which instance waiting a message
    	bw_port varchar,  	 -- the name of the operation which instance wait to receive
    	bw_deadline datetime,
    	bw_message long varchar default null, -- if instance is occupied and message is already arrived
    	bw_state int default 0,		      -- flag that bw_message is not null (0 or 1)
    	bw_correlation_exp varchar, 	      -- XPath expression for computing the correlation value from message
    	bw_expected_value long varbinary,     -- value of the expected correlation
    	bw_message_type int default 0,	      -- where to expect the data : 0 - SOAP:Body 1 - SOAP:Header
    	bw_start_date datetime,
    	primary key (bw_instance, bw_node));

    -- Messages which have been arrived but not correlated yet
    create table BPEL.BPEL.queue (
    	bq_id int identity,	-- unique id
    	bq_script int,		-- FK references bs_id from the script table
    	bq_ts timestamp,
    	bq_state int,		-- state of the Queue item; 0 - not processed
    	bq_endpoint varchar,	-- not used
    	bq_op varchar,		-- Operation name
    	bq_mid varchar,		-- mot used
    	bq_message long varchar, -- The incoming message text
    	bq_header long varchar,  -- SOAP:Header
    	primary key (bq_op, bq_ts)
    	);

    -- Initial values for SOAP Messages and XMLSchema types
    create table BPEL..types_init (
    	vi_script int,	   -- FK reference to bs_id to the script table
    	vi_name   varchar, -- message name, element name etc.
    	vi_type   int, 	   -- 0 - message, 1 - element, 2 - XMLSchema type
    	vi_value  long xml,-- Initial value
    	primary key (vi_script, vi_name, vi_type)
    )
    ;

    -- Matching XPath expressions for the SOAP message parts
    create table BPEL.BPEL.message_parts
    	(
    	mp_script int,	    -- FK reference to bs_id to the script table
    	mp_message varchar, -- message name
    	mp_part varchar,    -- part name
    	mp_xp   varchar,    -- location XPath expression
    	primary key (mp_script, mp_message, mp_part)
    	)
    ;

    -- Operations which are invoked by process (used in invoke activities)
    create table BPEL.BPEL.remote_operation (
    	ro_script int,		-- FK reference to bs_id to the script table
    	ro_partner_link varchar,-- name of the partner link
    	ro_role varchar,	-- not used
    	ro_operation varchar,	-- operation name
    	ro_port_type varchar,	-- port type
    	ro_input varchar,	-- input message name
    	ro_output varchar,	-- output message name
    	ro_endpoint_uri varchar,-- not used
    	ro_style int,		-- messages encoding style : 1 - literal, 0 - RPC like
    	ro_action varchar default '', -- SOAP Action value
    	ro_target_namespace varchar,  -- for RPC encoding the namespace to be used for wrapper elements
    	ro_use_wsa int default 0, -- WS-Addressing capabilities flag
    	ro_reply_service varchar, -- for one-way operations: reply service name
    	ro_reply_port varchar,    -- for one-way operations: reply port type
    	primary key (ro_script, ro_partner_link, ro_operation)
    )
    ;

    -- Operations which process defines (can receive and reply)
    create table BPEL.BPEL.operation (
    	bo_script int,		-- FK reference to bs_id to the script table
    	bo_name	varchar,	-- operation name
    	bo_action varchar,	-- SOAP Action value
    	bo_port_type	varchar,-- port type
    	bo_partner_link varchar,-- name of the partner link
    	bo_input	varchar,-- input message name
    	bo_input_xp	varchar,-- XPath expression to match the input message
    	bo_small_input	varchar,-- not used
    	bo_output	varchar,-- output message name
    	bo_style	int default 0,-- messages encoding style : 1 - literal, 0 - RPC like
    	bo_init		int,	-- process instantiation flag: 1 - can make new instances
    	primary key (bo_script, bo_name, bo_partner_link)
    );

    -- Predefined endpoint URLs for partner links
    create table BPEL.BPEL.partner_link_conf (
    	plc_name	varchar,
    	plc_endpoint	varchar,
    	primary key (plc_name)
    )
    ;

    -- Properties
    create table BPEL.BPEL.property
    (
      bpr_script int, 	-- FK reference to bs_id to the script table
      bpr_name varchar,	-- property name
      bpr_type varchar,	-- property type
      primary key (bpr_script, bpr_name)
    )
    ;

    -- Aliases
    create table BPEL.BPEL.property_alias (
    	pa_script	int,		-- FK reference to bs_id to the script table
    	pa_prop_id	int identity,
    	pa_prop_name	varchar,	-- property name
    	pa_message	varchar,	-- message name
    	pa_part		varchar,	-- part name
    	pa_query	varchar,	-- XPath query to set the property value
    	pa_type		varchar,
    	primary key (pa_script, pa_prop_name, pa_message))
    ;

    -- Correlation properties
    create table BPEL.BPEL.correlation_props (
    	cpp_id 		int identity (start with 1),
    	cpp_script	int,		-- FK reference to bs_id to the script table
    	cpp_corr	varchar,	-- correlation name
    	cpp_prop_name	varchar,	-- property name
    	primary key (cpp_id, cpp_script, cpp_corr, cpp_prop_name))
    ;

    -- Variables
    create table BPEL..variables (
    	v_inst 		int,		-- instance id, FK reference bi_id of the instance table
    	v_scope_inst   	int,		-- scope instance id; different than 0 for compensation scope
    	v_name 		varchar,	-- variable name
    	v_type 		varchar,	-- variable type
    	v_s1_value	any, 		-- string, numeric
    	v_s2_value	varchar, 	-- XML entities
    	v_b1_value	long varchar,	-- long strings
    	v_b2_value	long varchar, 	-- XML entities
    	primary key (v_inst, v_scope_inst, v_name))
    ;

    -- Links
    create table BPEL..links
    	(
    	  bl_script int,	-- FK reference to bs_id to the script table
    	  bl_name   varchar,	-- link name
    	  bl_act_id int,	-- corresponding link activity bit number
    	  primary key (bl_act_id, bl_script)
    	)
    ;

    -- Compensation scopes
    create table BPEL..compensation_scope
    	(tc_inst int,
    	 tc_seq	 int identity (start with 1),
    	 tc_scopes long varbinary,
    	 tc_head_node int,
    	 tc_head_node_bit int,
    	 tc_compensating_from int default null,
    	 primary key (tc_inst, tc_seq)
    	)
    ;

    -- Messages are correlated via WS-Addressing
    create table BPEL..wsa_messages
    	(
    	wa_inst int,
    	wa_pl	varchar,
    	wa_mid  varchar,
    	primary key (wa_inst, wa_pl, wa_mid)
    	)
    ;

    create table BPEL..lock
    	(
    	lck int primary key
    	)
    ;

    -- Accepted connections which are waiting for reply
    create table BPEL..reply_wait
    	(
    	rw_inst int,
    	rw_id int, -- identity (start with 1),
    	rw_partner varchar,
    	rw_port varchar,
    	rw_operation varchar,
    	rw_query varchar,
    	rw_expect varchar,
    	rw_started datetime,
    	primary key (rw_inst, rw_id)
    	)
    ;

    -- Registered alarm events
    create table BPEL..time_wait
    	(
    	  tw_inst 	int,
    	  tw_node 	int,
    	  tw_scope_inst int,
    	  tw_script	varchar,
    	  tw_script_id	int,
    	  tw_sec  	int,
    	  tw_until 	datetime,
    	  primary key (tw_inst, tw_node)
    	)
    ;

    -- BPEL message debugging queue
    create table BPEL..dbg_message (
    	bdm_text long varchar,		-- message text
    	bdm_id int identity (start with 1),
    	bdm_ts datetime,
    	bdm_inout int, 			-- 1 for in, 0 for out
    	bdm_sender_inst int, 		-- instance id of sender if outbound message
    	bdm_receiver int, 		-- if inbound, inst id of receiving inst
    	bdm_plink varchar, 		-- name of partner link in the script in question
    	bdm_recipient varchar, 		-- partner link value for outbound message, URL.
    	bdm_activity int, 		-- activity id of activity that either sent the message or would receive the message in the sender/receiver instance.
    	bdm_oper varchar,		-- operation name
    	bdm_script int,			-- process id, FK reference bs_id from script table
    	bdm_action varchar,		-- SOAP Action value
    	bdm_conn int,			-- client connection id
    	primary key (bdm_id)
    )
    ;

    -- BPEL engine configuration
    create table BPEL..configuration (
    	conf_name	varchar not null,
    	conf_desc 	varchar,
    	conf_value	any, -- not blob
    	conf_long_value	long varchar,
    	primary key (conf_name)
    )
    ;

    create table BPEL.BPEL.op_stat
    	(
    	 bos_process int,
    	 bos_plink varchar,
    	 bos_op varchar,
    	 bos_n_invokes int default 0,
    	 bos_n_receives int default 0,
    	 bos_cum_wait numeric default 0, -- miliseconds total time wait at the partner link/operation
    	 bos_data_in numeric default 0,
    	 bos_data_out numeric default 0,
    	 bos_n_errors int default 0,
    	 primary key (bos_process, bos_plink, bos_op)
    )
    ;

    create table BPEL.BPEL.error_log
    	(
    	 bel_ts timestamp,
    	 bel_seq int identity,
    	 bel_level int, -- bel_level is 1. fatal 2. network, 3 instance.
    	 bel_notice_sent datetime,  -- time the email was sent, null if none
    	 bel_text varchar,
    	 primary key (bel_ts, bel_seq)
    )
    ;

    create table BPEL.BPEL.hosted_classes
    	(
    	 hc_script	int,
    	 hc_type	varchar default 'java',
    	 hc_name	varchar,
    	 hc_text	long varbinary, -- compiled class
    	 hc_path	varchar, -- path to class if it is stored in file system
    	 hc_load_method	varchar,
    	 primary key (hc_script, hc_type,  hc_name)
    )
    ;

### 15.13.12. Errors

During the BPEL process execution we may consider following types of errors:

- Server failure - This means that the server as a whole has stopped operations and requires manual intervention. This is the case for: out of disk or database corruption.
- Network - This category applies to possibly transient conditions of not being able to contact partners. The server remains in operation for unaffected partners.
- Process Instance - This category applies to process instances getting an unhandled error condition. The process instance is out of service until the condition is resolved. This may indicate a bug in the process itself or a component used by it.

These errors will be logged in the file system (bpel_audit/server_log.txt) . If logging fails, an email is sent to the operator. The errors are also logged in the 'BPEL.BPEL.error_log' table so as to avoid repeatedly sending the same message.

During uploading the BPEL process we may consider following types of errors:

- bpel.xml file contains non-absolute paths and must be changed to absolute in order the uploading to be succesfull. This is in case user uses import_script api.
- wsdl file contains non-absolute paths at importing other wsdl file or xsd and must be changed to absolute in order the uploading to be succesfull. This is in case user uses upload process by choosing url/file for bpel and wsdl.
- process name already exists. This means there is already uploaded a process with the given name.
- at least one activity "receive" or "pick" must be declared at script source. Otherwise will be reported error this condition to be accomplished.

#### 15.13.12.1. Connection Errors

The communication error can be caught by explicit fault handler in the script. In this case the <catch> handler must catch the fault "bpws:communicationFault":

      <catch faultName="bpws:communicationFault" faultVariable="error">
       ...
      </catch>

The error variable "error" will contain the following fault structure:

     <comFault sqlState="xxxxx" message="text-of-message"
       partnerLink="plinkname" activity="name of activity" partnerURI="uri of
    partner">
       <message>-- copy of the message being sent when fault occurred -- </message>
     </comFault>

which can be used for reporting, recovery etc... The "sqlState" attribute contains SQL error state and the "message" stores the first line of SQL error message.

If the script does not handle this fault, the script will be frozen until explicit or implicit restart.

Here is an example of explicit communication handling:

    <process xmlns:tns="urn:echo:echoService" xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/" name="faultHTCLI" targetNamespace="urn:echo:echoService"  xmlns:bpelv="http://www.openlinksw.com/virtuoso/bpel">
      <partnerLinks>
        <partnerLink name="caller" partnerLinkType="tns:echoSLT"/>
        <partnerLink name="test" partnerLinkType="tns:testSLT" partnerRole="service"/>
      </partnerLinks>
      <variables>
        <variable name="request" messageType="tns:StringMessageType"/>
        <variable name="res" messageType="tns:StringMessageType"/>
        <variable name="n_tries" messageType="tns:IntMessageType"/>
      </variables>
      <sequence name="EchoSequence">
        <assign>
          <copy>
            <from expression="3"/>
    	<to variable="n_tries" part="value" query="/value"/>
          </copy>
        </assign>
        <receive partnerLink="caller" portType="tns:echoPT" operation="echo" variable="request" createInstance="yes" name="EchoReceive"/>
        <while condition="getVariableData ('n_tries', 'value', '/value')
    	   &gt; 0">
          <sequence>
    	<scope>
    	  <faultHandlers>
    	    <catch faultName="bpws:communicationFault" faultVariable="error">
    	      <sequence>
    		<bpelv:exec binding="SQL">
    		  dbg_obj_print (BPEL.BPEL.getVariableData ('error'));
    		  dbg_obj_print (BPEL.BPEL.getVariableData ('n_tries'));
    		</bpelv:exec>
    		<assign>
    		  <copy>
    		    <from variable="error" query="/comFault/@sqlState"/>
    		    <to variable="res" part="echoString" query="/echoString"/>
    		  </copy>
    		  <copy>
    		    <from expression="getVariableData ('n_tries',
    			  'value', '/value') - 1"/>
    		    <to variable="n_tries" part="value" query="/value"/>
    		  </copy>
    		</assign>
    		<wait for="PT10S"/>
    	      </sequence>
    	    </catch>
    	    <catchAll>
    	      <empty/>
    	    </catchAll>
    	  </faultHandlers>
    	  <sequence>
    	    <invoke partnerLink="test" portType="tns:SOAPPortType" operation="test" inputVariable="request" outputVariable="res"/>
    	    <assign>
    	      <copy>
    		<from expression="0"/>
    		<to variable="n_tries" part="value" query="/value"/>
    	      </copy>
    	    </assign>
    	  </sequence>
    	</scope>
          </sequence>
        </while>
        <reply partnerLink="caller" portType="tns:echoPT" operation="echo" variable="res" name="EchoReply"/>
      </sequence>
    </process>

In this example the process in a case of communication exception makes 3 reconnection retries to the remote service. Each reconnection is made after waiting 10 seconds.

#### 15.13.12.2. Deadlock Errors

During concurrent execution of several BPEL scripts deadlock conditions can be signaled. That is why Virtuoso BPEL engine contains implicit deadlock detection and retry capability. When the deadlock is detected, the engine tries to wait some time, and retry the transaction. If the number of retries exceeds some maximum number the script execution will be aborted and mail will be sent to the operator with an appropriate message.

The time to wait before retry and the maximum number of retries can be configured on the configuration page of the administration UI.

### 15.13.13. Samples

Simple echo script

    <process name="echo" targetNamespace="http://temp.uri" xmlns:tns="http://temp.uri"
        xmlns="http://schemas.xmlsoap.org/ws/2003/03/business-process/">

        <partnerLinks>
    	<partnerLink name="caller" partnerLinkType="tns:echoService"/>
        </partnerLinks>

        <variables>
    	<variable name="request" messageType="tns:StringMessageType"/>
        </variables>

        <sequence name="EchoSequence">
    	<receive partnerLink="caller" portType="tns:echoPort"
    	    operation="echo" variable="request"
    	    createInstance="yes" name="EchoReceive"/>
    	<reply partnerLink="caller" portType="tns:echoPort"
    	    operation="echo" variable="request" name="EchoReply"/>
        </sequence>

    </process>

... and corresponding WSDL

    <definitions targetNamespace="http://temp.uri" xmlns:tns="http://temp.uri"
                 xmlns:pl="http://schemas.xmlsoap.org/ws/2003/05/partner-link/"
    	     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    	     xmlns="http://schemas.xmlsoap.org/wsdl/">

       <message name="StringMessageType">
          <part name="echoString" type="xsd:string"/>
       </message>

       <portType name="echoPort">
          <operation name="echo">
             <input message="tns:StringMessageType"/>
             <output message="tns:StringMessageType"/>
          </operation>
       </portType>

       <pl:partnerLinkType name="echoService">
         <pl:role name="svc">
           <pl:portType name="tns:echoPort"/>
         </pl:role>
       </pl:partnerLinkType>

    </definitions>

Invoking Echo Service

        SQL>select xpath_eval ('/echoResponse/echoString/text()',
    	xml_tree_doc (
    		DB.DBA.soap_client (
    		url=>sprintf ('http://localhost:%s/BPELGUI/bpel.vsp?script=file://echo/echo.bpel',server_http_port()),
    		operation=>'echo',
    		soap_action=>'echo',
    		parameters=> vector ('par', xtree_doc ('hello world')))
    		));
            callret
            VARCHAR
             _______________________________________________________________________________

             hello world

             1 Rows. -- 330 msec.

#### 15.13.13.1. BPEL Functions

getVariableData

          ...
          <assign name="assignResult">
            <copy>
              <from expression="concat( 'Hello ', bpws:getVariableData('input', 'payload', '/tns:echovirtRequest/tns:name'), ' ', bpws:getVariableData('input', 'payload', '/tns:echovirtRequest/tns:fname'))"/>
              <to variable="output" part="payload" query="/tns:echovirtResponse/tns:result"/>
            </copy>
          </assign>
          ...

count

          ...
          <assign name="assignResult">
            <copy>
              <from part="payload" variable="input" query="count(//lines/line)"/>
              <to variable="count"/>
            </copy>
          </assign>
          ...

See Also: Reference Material in the Tutorial:

BP-S-1 Loan Flow demo

See Also: Reference Material in the BPELDemo tutorials:

BPEL4WS VAD package must be installed in order to view these tutorials.

BPELDemo

### 15.13.14. References

BPEL4WS specification

WS-Addressing

WSDL specification

SOAP specification

XPath specification

### 15.13.15. BPEL4WS VAD Package installation

#### 15.13.15.1. Using Conductor

- Step 1. Download BPEL4WS VAD and copy it to a local directory.
- Step 2. Go to Conductor UI: http://host:port/conductor/
- Step 3. Login into the Virtuoso Conductor using the admin account.
- Step 4. Select Systems Admin->Packages Tab.
- Step 5. Under the Install Packaged, section of the UI is a list of VAD packages. If this is the first time you have installed a VAD package you will only see the Virtuoso Conductor. Directly under this list is the option Install a Package. You can either enter or browse to the location of the directory of the BPEL4WS package or enter a DAV location.
- Step 6. Once you have provided the location, select Proceed to upload the package.

#### 15.13.15.2. Using ISQL

           SQL>VAD_INSTALL('bpel4ws.vad',0);
            SQL_STATE  SQL_MESSAGE
            VARCHAR  VARCHAR
            _______________________________________________________________________________

            00000    GUI is accessible via http://host:port/BPELGUI
            00000    Quick Start is available from http://host:port/BPELGUI/start.vsp
            00000    No errors detected, installation complete.
            00000    Now making a final checkpoint.
            00000    Final checkpoint is made.
            00000    SUCCESS

            7 Rows. -- 5438 msec.

Previous Testing Web Published Web Services | Chapter Contents | Next XSQL