Author: assaf
Date: Tue Sep  5 09:59:09 2006
New Revision: 440399

URL: http://svn.apache.org/viewvc?view=rev&rev=440399
Log:
Added ActivityRecovery support to Invoke activity

Added:
    
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/channels/ActivityRecovery.java
   (with props)
    
incubator/ode/trunk/bpel-runtime/src/test/java/org/apache/ode/bpel/runtime/MockBpelServer.java
   (with props)
Modified:
    incubator/ode/trunk/bpel-runtime/pom.xml
    
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/BpelRuntimeContextImpl.java
    
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/ActivityInfo.java
    
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/BpelRuntimeContext.java
    
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/INVOKE.java
    
incubator/ode/trunk/bpel-runtime/src/test/java/org/apache/ode/bpel/runtime/CoreBpelTest.java

Modified: incubator/ode/trunk/bpel-runtime/pom.xml
URL: 
http://svn.apache.org/viewvc/incubator/ode/trunk/bpel-runtime/pom.xml?view=diff&rev=440399&r1=440398&r2=440399
==============================================================================
--- incubator/ode/trunk/bpel-runtime/pom.xml (original)
+++ incubator/ode/trunk/bpel-runtime/pom.xml Tue Sep  5 09:59:09 2006
@@ -19,79 +19,138 @@
   -->
 
 <project>
-    <groupId>ode</groupId>
-    <artifactId>ode-bpel-runtime</artifactId>
-    <name>ODE :: BPEL Runtime</name>
+  <groupId>ode</groupId>
+  <artifactId>ode-bpel-runtime</artifactId>
+  <name>ODE :: BPEL Runtime</name>
 
-    <modelVersion>4.0.0</modelVersion>
-    <parent>
-        <groupId>ode</groupId>
-        <artifactId>ode</artifactId>
-        <version>2.0-SNAPSHOT</version>
-    </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>ode</groupId>
+    <artifactId>ode</artifactId>
     <version>2.0-SNAPSHOT</version>
-    <dependencies>
-        <dependency>
-            <groupId>ode</groupId>
-            <artifactId>ode-bpel-api</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>ode</groupId>
-            <artifactId>ode-bpel-dao</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>ode</groupId>
-            <artifactId>ode-bpel-compiler</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>ode</groupId>
-            <artifactId>ode-bpel-obj</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>ode</groupId>
-            <artifactId>ode-jacob</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>ode</groupId>
-            <artifactId>ode-utils</artifactId>
-        </dependency>
+  </parent>
+  <version>2.0-SNAPSHOT</version>
+  <dependencies>
+    <dependency>
+      <groupId>ode</groupId>
+      <artifactId>ode-bpel-api</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>ode</groupId>
+      <artifactId>ode-bpel-dao</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>ode</groupId>
+      <artifactId>ode-bpel-compiler</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>ode</groupId>
+      <artifactId>ode-bpel-obj</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>ode</groupId>
+      <artifactId>ode-jacob</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>ode</groupId>
+      <artifactId>ode-utils</artifactId>
+    </dependency>
 
-        <dependency>
-          <groupId>stax</groupId>
-          <artifactId>stax-api</artifactId>
-        </dependency>
+    <dependency>
+      <groupId>stax</groupId>
+      <artifactId>stax-api</artifactId>
+    </dependency>
 
-        <dependency>
-          <groupId>commons-collections</groupId>
-          <artifactId>commons-collections</artifactId>
-          <version>${commonsCollectionsVersion}</version>
-        </dependency>
+    <dependency>
+      <groupId>commons-collections</groupId>
+      <artifactId>commons-collections</artifactId>
+      <version>${commonsCollectionsVersion}</version>
+    </dependency>
 
-    </dependencies>
-    <build>
-        <plugins>
+    <dependency>
+      <groupId>jotm</groupId>
+      <artifactId>jotm</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.geronimo.specs</groupId>
+      <artifactId>geronimo-j2ee-connector_1.5_spec</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.geronimo.specs</groupId>
+      <artifactId>geronimo-jta_1.0.1B_spec</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.derby</groupId>
+      <artifactId>derby</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>ode</groupId>
+      <artifactId>ode-bpel-scheduler-quartz</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>ode</groupId>
+      <artifactId>ode-dao-hibernate</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>ode</groupId>
+      <artifactId>ode-naming</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>ode</groupId>
+      <artifactId>ode-bpel-schemas</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>ode</groupId>
+      <artifactId>ode-minerva</artifactId>
+      <scope>test</scope>
+    </dependency>
 
-            <plugin>
-                <groupId>org.codehaus.mojo</groupId>
-                <artifactId>xdoclet-maven-plugin</artifactId>
-                <executions>
-                    <execution>
-                        <phase>generate-sources</phase>
-                        <goals>
-                            <goal>xdoclet</goal>
-                        </goals>
-                        <configuration>
-                            <tasks>
-                                <doclet 
destDir="${project.build.directory}/generated-sources/xdoclet" verbose="true">
-                                    <fileset dir="${basedir}/src/main/java" 
includes="**/*.java"/>
-                                    <template havingClassTag="jacob.kind" 
destinationFile="{0}ChannelListener.java" 
templateFile="${basedir}/../jacob/src/xdt/org/apache/ode/jacob/ChannelListener.xdt"/>
-                                    <template havingClassTag="jacob.kind" 
destinationFile="{0}Channel.java" 
templateFile="${basedir}/../jacob/src/xdt/org/apache/ode/jacob/channel.xdt"/>
-                                </doclet>
-                            </tasks>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin>
-        </plugins>
-    </build>
+  </dependencies>
+    <build>
+      <plugins>
+        <plugin>
+          <groupId>org.codehaus.mojo</groupId>
+          <artifactId>xdoclet-maven-plugin</artifactId>
+          <executions>
+            <execution>
+              <phase>generate-sources</phase>
+              <goals>
+                <goal>xdoclet</goal>
+              </goals>
+              <configuration>
+                <tasks>
+                  <doclet 
destDir="${project.build.directory}/generated-sources/xdoclet" verbose="true">
+                    <fileset dir="${basedir}/src/main/java" 
includes="**/*.java"/>
+                    <template havingClassTag="jacob.kind" 
destinationFile="{0}ChannelListener.java" 
templateFile="${basedir}/../jacob/src/xdt/org/apache/ode/jacob/ChannelListener.xdt"/>
+                    <template havingClassTag="jacob.kind" 
destinationFile="{0}Channel.java" 
templateFile="${basedir}/../jacob/src/xdt/org/apache/ode/jacob/channel.xdt"/>
+                  </doclet>
+                </tasks>
+              </configuration>
+            </execution>
+          </executions>
+        </plugin>
+        <plugin>
+          <artifactId>maven-antrun-plugin</artifactId>
+          <executions>
+            <execution>
+              <phase>process-resources</phase>
+              <goals><goal>run</goal></goals>
+              <configuration>
+                <tasks>
+                  <ant antfile="build.xml" target="test-db" 
inheritRefs="true"/>
+                </tasks>
+              </configuration>
+            </execution>
+          </executions>
+        </plugin>
+      </plugins>
+  </build>
 </project>

Modified: 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/BpelRuntimeContextImpl.java
URL: 
http://svn.apache.org/viewvc/incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/BpelRuntimeContextImpl.java?view=diff&rev=440399&r1=440398&r2=440399
==============================================================================
--- 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/BpelRuntimeContextImpl.java
 (original)
+++ 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/BpelRuntimeContextImpl.java
 Tue Sep  5 09:59:09 2006
@@ -62,6 +62,7 @@
 import org.apache.ode.bpel.runtime.channels.InvokeResponseChannel;
 import org.apache.ode.bpel.runtime.channels.PickResponseChannel;
 import org.apache.ode.bpel.runtime.channels.TimerResponseChannel;
+import org.apache.ode.bpel.runtime.channels.ActivityRecoveryChannel;
 import org.apache.ode.jacob.JacobRunnable;
 import org.apache.ode.jacob.vpu.ExecutionQueueImpl;
 import org.apache.ode.jacob.vpu.JacobVPU;
@@ -934,7 +935,6 @@
     }
 
     void invocationResponse(final String mexid, final String 
responseChannelId) {
-
         vpu.inject(new BpelJacobRunnable() {
             private static final long serialVersionUID = -1095444335740879981L;
 
@@ -1200,6 +1200,12 @@
         return 
dao.getProperty(MessageExchange.PROPERTY_SEP_PARTNERROLE_SESSIONID);
     }
 
+    public void registerForRecovery(ActivityRecoveryChannel channel) {
+    }
+
+    public void unregisterForRecovery(ActivityRecoveryChannel channel) {
+    }
+
     /**
      * Fetch the session-identifier for the partner link from the database. 
      */
@@ -1219,5 +1225,4 @@
         fetchPartnerLinkDAO(pLink).setPartnerSessionId(session);
         
     }
-
 }

Modified: 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/ActivityInfo.java
URL: 
http://svn.apache.org/viewvc/incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/ActivityInfo.java?view=diff&rev=440399&r1=440398&r2=440399
==============================================================================
--- 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/ActivityInfo.java
 (original)
+++ 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/ActivityInfo.java
 Tue Sep  5 09:59:09 2006
@@ -19,6 +19,7 @@
 package org.apache.ode.bpel.runtime;
 
 import org.apache.ode.bpel.o.OActivity;
+import org.apache.ode.bpel.o.FailureHandling;
 import org.apache.ode.bpel.runtime.channels.ParentScopeChannel;
 import org.apache.ode.bpel.runtime.channels.TerminationChannel;
 
@@ -59,5 +60,19 @@
   
   public int hashCode() {
     return (int)aId;
+  }
+
+  public FailureHandling getFailureHandling() {
+    FailureHandling failure = o.failureHandling;
+    // TODO: Need inheritance mechanism.
+    if (failure == null)
+      failure = new FailureHandling();
+    if (failure.retryFor == null)
+      failure.retryFor = new Integer(0);
+    if (failure.retryDelay == null)
+      failure.retryDelay = new Integer(0);
+    if (failure.faultOnFailure == null)
+      failure.faultOnFailure = Boolean.FALSE;
+    return failure;
   }
 }

Modified: 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/BpelRuntimeContext.java
URL: 
http://svn.apache.org/viewvc/incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/BpelRuntimeContext.java?view=diff&rev=440399&r1=440398&r2=440399
==============================================================================
--- 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/BpelRuntimeContext.java
 (original)
+++ 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/BpelRuntimeContext.java
 Tue Sep  5 09:59:09 2006
@@ -30,6 +30,7 @@
 import org.apache.ode.bpel.runtime.channels.InvokeResponseChannel;
 import org.apache.ode.bpel.runtime.channels.PickResponseChannel;
 import org.apache.ode.bpel.runtime.channels.TimerResponseChannel;
+import org.apache.ode.bpel.runtime.channels.ActivityRecoveryChannel;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
@@ -241,6 +242,10 @@
   Node getPartData(Element message, Part part);
 
   Element getSourceEPR(String mexId);
+
+  void registerForRecovery(ActivityRecoveryChannel channel);
+
+  void unregisterForRecovery(ActivityRecoveryChannel channel);
 
   String getSourceSessionId(String mexId);
 }

Modified: 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/INVOKE.java
URL: 
http://svn.apache.org/viewvc/incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/INVOKE.java?view=diff&rev=440399&r1=440398&r2=440399
==============================================================================
--- 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/INVOKE.java
 (original)
+++ 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/INVOKE.java
 Tue Sep  5 09:59:09 2006
@@ -20,10 +20,16 @@
 
 import org.apache.ode.bpel.common.FaultException;
 import org.apache.ode.bpel.o.OInvoke;
+import org.apache.ode.bpel.o.FailureHandling;
 import org.apache.ode.bpel.o.OScope;
 import org.apache.ode.bpel.runtime.channels.FaultData;
 import org.apache.ode.bpel.runtime.channels.InvokeResponseChannel;
 import org.apache.ode.bpel.runtime.channels.InvokeResponseChannelListener;
+import org.apache.ode.bpel.runtime.channels.TimerResponseChannel;
+import org.apache.ode.bpel.runtime.channels.TimerResponseChannelListener;
+import org.apache.ode.bpel.runtime.channels.TerminationChannelListener;
+import org.apache.ode.bpel.runtime.channels.ActivityRecoveryChannel;
+import org.apache.ode.bpel.runtime.channels.ActivityRecoveryChannelListener;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
@@ -31,6 +37,7 @@
 
 import javax.xml.namespace.QName;
 import java.util.Collection;
+import java.util.Date;
 
 /**
  * JacobRunnable that performs the work of the <code>invoke</code> activity.
@@ -39,10 +46,17 @@
   private static final long serialVersionUID = 992248281026821783L;
 
   private OInvoke _oinvoke;
+  // Records number of invocations on the activity.
+  private int     _invoked;
+  // Date/time of last failure.
+  private Date    _lastFailure;
+  // Reason for last failure.
+  private String  _failureReason;
 
   public INVOKE(ActivityInfo self, ScopeFrame scopeFrame, LinkFrame linkFrame) 
{
     super(self, scopeFrame, linkFrame);
     _oinvoke = (OInvoke) _self.o;
+    _invoked = 0;
   }
 
   public final void run() {
@@ -54,6 +68,7 @@
       _self.parent.completed(fault, CompensationHandler.emptySet());
       return;
     }
+    ++_invoked;
 
     // if there is no output variable, then this is a one-way invoke
     boolean isTwoWay = _oinvoke.outputVar != null;
@@ -141,10 +156,9 @@
           public void onFailure() {
             // This indicates a communication failure. We don't throw a fault,
             // because there is no fault, instead we'll re-incarnate the invoke
-            // and ask the runtime to terminate us: this will allow the sys
+            // and either retry or indicate failure condition.
             // admin to resume the process.
-            instance(INVOKE.this);
-            getBpelRuntimeContext().terminate();
+            INVOKE.this.retryOrFailure(null);
           }
         });
       }
@@ -172,6 +186,71 @@
     assert outboundMsg instanceof Element;
 
     return (Element) outboundMsg;
+  }
+
+  private void retryOrFailure(String reason) {
+    _lastFailure = new Date();
+    _failureReason = reason;
+
+    if (_self.getFailureHandling().faultOnFailure) {
+      // No attempt to retry or enter activity recovery state, simply fault.
+      FaultData faultData = createFault(FailureHandling.FAILURE_FAULT_NAME, 
_oinvoke, reason);
+      _self.parent.completed(faultData, CompensationHandler.emptySet());
+      return;
+    }
+
+    // If maximum number of retries, enter activity recovery state.  
+    if (_invoked > _self.getFailureHandling().retryFor + 1) {
+      requireRecovery();
+      return;
+    }
+    
+    Date future = new Date(new Date().getTime() + 
(_self.getFailureHandling().retryDelay * 1000));
+    final TimerResponseChannel timerChannel = 
newChannel(TimerResponseChannel.class);
+    getBpelRuntimeContext().registerTimer(timerChannel, future);
+    object(false, new TimerResponseChannelListener(timerChannel) {
+      public void onTimeout() {
+        instance(INVOKE.this);
+      }
+      public void onCancel() {
+        INVOKE.this.requireRecovery();
+      }
+    }.or(new TerminationChannelListener(_self.self) {
+      public void terminate() {
+        _self.parent.completed(null, CompensationHandler.emptySet());
+        object(new TimerResponseChannelListener(timerChannel) {
+          public void onTimeout() { }
+          public void onCancel() { }
+        });
+      }
+    }));
+  }
+
+  private void requireRecovery() {
+    final ActivityRecoveryChannel recoveryChannel = 
newChannel(ActivityRecoveryChannel.class);
+    getBpelRuntimeContext().registerForRecovery(recoveryChannel);
+    object(false, new ActivityRecoveryChannelListener(recoveryChannel) {
+      public void retry() {
+        getBpelRuntimeContext().unregisterForRecovery(recoveryChannel);
+        instance(INVOKE.this);
+      }
+      public void cancel() {
+        getBpelRuntimeContext().unregisterForRecovery(recoveryChannel);
+        _self.parent.completed(null, CompensationHandler.emptySet());
+      }
+      public void fault(FaultData faultData) {
+        getBpelRuntimeContext().unregisterForRecovery(recoveryChannel);
+        // TODO: real fault name.
+        if (faultData == null)
+          faultData = createFault(FailureHandling.FAILURE_FAULT_NAME, _self.o, 
_failureReason);
+        _self.parent.completed(faultData, CompensationHandler.emptySet());
+      }
+    }.or(new TerminationChannelListener(_self.self) {
+      public void terminate() {
+        getBpelRuntimeContext().unregisterForRecovery(recoveryChannel);
+        _self.parent.completed(null, CompensationHandler.emptySet());
+      }
+    }));
   }
 
 }

Added: 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/channels/ActivityRecovery.java
URL: 
http://svn.apache.org/viewvc/incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/channels/ActivityRecovery.java?view=auto&rev=440399
==============================================================================
--- 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/channels/ActivityRecovery.java
 (added)
+++ 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/channels/ActivityRecovery.java
 Tue Sep  5 09:59:09 2006
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.ode.bpel.runtime.channels;
+
+
+/**
+ * @jacob.kind
+ */
+public interface ActivityRecovery  {
+
+  /**
+   * Retry the activity.
+   */
+  void retry();
+
+  /**
+   * Cancel (skip) the activity.
+   */
+  void cancel();
+
+  /**
+   * Fault the activity.
+   */
+  void fault(FaultData faultData);
+
+}

Propchange: 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/channels/ActivityRecovery.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/channels/ActivityRecovery.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: 
incubator/ode/trunk/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/channels/ActivityRecovery.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Modified: 
incubator/ode/trunk/bpel-runtime/src/test/java/org/apache/ode/bpel/runtime/CoreBpelTest.java
URL: 
http://svn.apache.org/viewvc/incubator/ode/trunk/bpel-runtime/src/test/java/org/apache/ode/bpel/runtime/CoreBpelTest.java?view=diff&rev=440399&r1=440398&r2=440399
==============================================================================
--- 
incubator/ode/trunk/bpel-runtime/src/test/java/org/apache/ode/bpel/runtime/CoreBpelTest.java
 (original)
+++ 
incubator/ode/trunk/bpel-runtime/src/test/java/org/apache/ode/bpel/runtime/CoreBpelTest.java
 Tue Sep  5 09:59:09 2006
@@ -37,6 +37,7 @@
 import org.apache.ode.bpel.runtime.channels.InvokeResponseChannel;
 import org.apache.ode.bpel.runtime.channels.PickResponseChannel;
 import org.apache.ode.bpel.runtime.channels.TimerResponseChannel;
+import org.apache.ode.bpel.runtime.channels.ActivityRecoveryChannel;
 import org.apache.ode.jacob.vpu.ExecutionQueueImpl;
 import org.apache.ode.jacob.vpu.JacobVPU;
 import org.w3c.dom.Element;
@@ -388,4 +389,10 @@
         // TODO Auto-generated method stub
         return null;
     }
+
+  public void registerForRecovery(ActivityRecoveryChannel channel) {
+  }
+
+  public void unregisterForRecovery(ActivityRecoveryChannel channel) {
+  }
 }

Added: 
incubator/ode/trunk/bpel-runtime/src/test/java/org/apache/ode/bpel/runtime/MockBpelServer.java
URL: 
http://svn.apache.org/viewvc/incubator/ode/trunk/bpel-runtime/src/test/java/org/apache/ode/bpel/runtime/MockBpelServer.java?view=auto&rev=440399
==============================================================================
--- 
incubator/ode/trunk/bpel-runtime/src/test/java/org/apache/ode/bpel/runtime/MockBpelServer.java
 (added)
+++ 
incubator/ode/trunk/bpel-runtime/src/test/java/org/apache/ode/bpel/runtime/MockBpelServer.java
 Tue Sep  5 09:59:09 2006
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.ode.bpel.runtime;
+
+import com.fs.naming.mem.InMemoryContextFactory;
+import org.apache.ode.bpel.dao.BpelDAOConnectionFactory;
+import org.apache.ode.bpel.engine.*;
+import org.apache.ode.bpel.iapi.*;
+import org.apache.ode.bpel.o.OProcess;
+import org.apache.ode.bpel.pmapi.BpelManagementFacade;
+import org.apache.ode.bpel.scheduler.quartz.QuartzSchedulerImpl;
+import org.apache.ode.daohib.HibernateTransactionManagerLookup;
+import org.apache.ode.daohib.SessionManager;
+import org.apache.ode.daohib.bpel.BpelDAOConnectionFactoryImpl;
+import org.apache.ode.daohib.DataSourceConnectionProvider;
+import org.apache.ode.utils.DOMUtils;
+import org.apache.ode.utils.GUID;
+import org.objectweb.jotm.Jotm;
+import org.opentools.minerva.MinervaPool;
+import org.hibernate.cfg.Environment;
+
+import java.io.IOException;
+import java.io.File;
+import java.net.URI;
+import java.util.Properties;
+import java.util.Hashtable;
+import java.util.HashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.Collection;
+
+import javax.xml.namespace.QName;
+import javax.wsdl.PortType;
+import javax.transaction.TransactionManager;
+import javax.sql.DataSource;
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.Reference;
+import javax.naming.Name;
+import javax.naming.spi.ObjectFactory;
+import junit.framework.TestCase;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+
+class MockBpelServer {
+
+  BpelServerImpl            _server;
+  TransactionManager        _txManager;
+  Jotm                      _jotm;
+  MinervaPool               _minervaPool;
+  DataSource                _dataSource;
+  ExecutorService           _executorService;
+  QuartzSchedulerImpl       _scheduler;
+  BpelDAOConnectionFactory  _daoCF;
+  EndpointReferenceContext  _eprContext;
+  MessageExchangeContext    _mexContext;
+  BindingContext            _bindContext;
+  HashMap                   _activated = new HashMap();
+  HashMap                   _endpoints = new HashMap();
+
+
+  public MockBpelServer() {
+    try {
+      _server = new BpelServerImpl();
+      createTransactionManager();
+      createDataSource();
+      createDAOConnection();
+      createScheduler();
+
+      if (_daoCF == null)
+        throw new RuntimeException("No DAO");
+      _server.setDaoConnectionFactory(_daoCF);
+      if (_scheduler == null)
+        throw new RuntimeException("No scheduler");
+      _server.setScheduler(_scheduler);
+      _server.setEndpointReferenceContext(createEndpointReferenceContext());
+      _server.setMessageExchangeContext(createMessageExchangeContext());
+      _server.setBindingContext(createBindingContext());
+      _server.init();
+      _server.start();
+    } catch (Exception except) {
+      System.err.println(except.getMessage());
+      except.printStackTrace(System.err);
+      throw new RuntimeException(except);
+    }
+  }
+
+  public Collection<QName> deploy(File deploymentUnitDirectory) {
+    Collection<QName> pids = _server.deploy(deploymentUnitDirectory);
+    for (QName pid: pids)
+      _server.activate(pid, true);
+    return pids;
+  }
+
+  public void invoke(QName serviceName, String opName, Element body) throws 
Exception {
+    try {
+      String messageId = new GUID().toString();
+      MyRoleMessageExchange mex;
+
+      _txManager.begin();
+      mex = _server.getEngine().createMessageExchange("" + messageId, 
serviceName, opName);
+      if (mex.getOperation() == null)
+        throw new Exception("Did not find operation " + opName + " on service 
" + serviceName);
+      Message request = 
mex.createMessage(mex.getOperation().getInput().getMessage().getQName());
+      request.setMessage(body);
+      mex.invoke(request);
+      mex.complete();
+    } catch (Exception except) {
+      if (_txManager != null) {
+        _txManager.rollback();
+        _txManager = null;
+      }
+      throw except;
+    } finally {
+      if (_txManager != null) {
+        _txManager.commit();
+        _txManager = null;
+      }
+    }
+/*
+        // Preparing a callback just in case we would need one.
+        if (odeMex.getOperation().getOutput() != null) {
+          callback = new ResponseCallback();
+          _waitingCallbacks.put(odeMex.getClientId(), callback);
+        }
+
+        if (__log.isDebugEnabled()) {
+          __log.debug("Invoking ODE using MEX " + odeMex);
+          __log.debug("Message content:  " + 
DOMUtils.domToString(odeRequest.getMessage()));
+        }
+        // Invoking ODE
+        odeMex.invoke(odeRequest);
+      } else {
+        success = false;
+      }
+*/
+  }
+
+  public BpelManagementFacade getBpelManagementFacade() {
+    return _server.getBpelManagementFacade();
+  }
+
+  public void shutdown() throws Exception {
+    if (_server != null) {
+      _server.stop();
+      _server = null;
+    }
+    if (_scheduler != null) {
+      _scheduler.shutdown();
+      _scheduler = null;
+    }
+    if (_jotm != null) {
+      _jotm.stop();
+      _jotm = null;
+    }
+  }
+
+  protected TransactionManager createTransactionManager() throws Exception {
+    _jotm = new Jotm(true, false);
+    _txManager = _jotm.getTransactionManager();
+    _txManager.setTransactionTimeout(30);
+    Reference txm = new Reference("javax.transaction.TransactionManager",
+                                  
JotmTransactionManagerFactory.class.getName(), null);
+    System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
+                       InMemoryContextFactory.class.getName());
+    System.setProperty(Context.PROVIDER_URL, "pxe");
+    InitialContext ctx = new InitialContext();
+    ctx.rebind("TransactionManager", txm);
+    ctx.close();
+    return _txManager;
+  }
+
+  protected DataSource createDataSource() throws Exception {
+    if (_txManager == null)
+      throw new RuntimeException("No transaction manager");
+    String url = "jdbc:derby:target/test-classes/derby-db/data";
+    _minervaPool = new MinervaPool();
+    _minervaPool.setTransactionManager(_txManager);
+    _minervaPool.getConnectionFactory().setConnectionURL(url);
+    _minervaPool.getConnectionFactory().setUserName("sa");
+    
_minervaPool.getConnectionFactory().setDriver(org.apache.derby.jdbc.EmbeddedDriver.class.getName());
+    _minervaPool.getPoolParams().minSize = 0;
+    _minervaPool.getPoolParams().maxSize = 10;
+    _minervaPool.setType(MinervaPool.PoolType.MANAGED);
+    _minervaPool.start();
+    _dataSource = _minervaPool.createDataSource();
+    return _dataSource;
+  }
+
+  protected Scheduler createScheduler() throws Exception {
+    if (_server == null)
+      throw new RuntimeException("No BPEL server");
+    if (_txManager == null)
+      throw new RuntimeException("No transaction manager");
+    if (_dataSource == null)
+      throw new RuntimeException("No data source");
+    _executorService = Executors.newCachedThreadPool();
+    _scheduler = new QuartzSchedulerImpl();
+    _scheduler.setBpelServer(_server);
+    _scheduler.setExecutorService(_executorService, 20);
+    _scheduler.setTransactionManager(_txManager);
+    _scheduler.setDataSource(_dataSource);
+    _scheduler.init();
+    return _scheduler;
+  }
+
+  protected BpelDAOConnectionFactory createDAOConnection() throws Exception {
+    if (_txManager == null)
+      throw new RuntimeException("No transaction manager");
+    if (_dataSource == null)
+      throw new RuntimeException("No data source");
+    Properties properties = new Properties();
+    properties.put(Environment.CONNECTION_PROVIDER,
+                   DataSourceConnectionProvider.class.getName());
+    properties.put(Environment.TRANSACTION_MANAGER_STRATEGY,
+                   HibernateTransactionManagerLookup.class.getName());
+    properties.put(Environment.SESSION_FACTORY_NAME, "jta");
+    properties.put(Environment.DIALECT, "org.hibernate.dialect.DerbyDialect");
+    SessionManager sm = new SessionManager(properties, _dataSource, 
_txManager);
+    _daoCF = new BpelDAOConnectionFactoryImpl(sm);
+    Reference bpelSscfRef = new 
Reference(BpelDAOConnectionFactory.class.getName(),
+                                          
HibernateDaoObjectFactory.class.getName(), null);
+    InitialContext ctx = new InitialContext();
+    ctx.rebind("bpelSSCF", bpelSscfRef);
+    ctx.close();
+    return _daoCF;
+  }
+
+  protected EndpointReferenceContext createEndpointReferenceContext() {
+    _eprContext = new EndpointReferenceContext() {
+      public EndpointReference resolveEndpointReference(Element element) { 
+        String service = DOMUtils.getChildCharacterData(element);
+        return (EndpointReference)_endpoints.get(service);
+      }
+      public EndpointReference activateEndpoint(QName qName, QName qName1, 
Element element) { return null; }
+      public void deactivateEndpoint(EndpointReference endpointReference) { }
+      public EndpointReference convertEndpoint(QName qName, Element element) { 
return null; }
+    };
+    return _eprContext;
+  }
+
+  protected MessageExchangeContext createMessageExchangeContext() {
+   _mexContext =  new MessageExchangeContext() {
+      public void invokePartner(PartnerRoleMessageExchange mex) { }
+      public void onAsyncReply(MyRoleMessageExchange myRoleMex) { }
+    };
+    return _mexContext;
+  }
+
+  protected BindingContext createBindingContext() {
+    _bindContext = new BindingContext() {
+      public EndpointReference activateMyRoleEndpoint(QName processId, 
DeploymentUnit deploymentUnit, Endpoint myRoleEndpoint, PortType portType) {
+        final Document doc = DOMUtils.newDocument();
+        Element serviceRef = 
doc.createElementNS(EndpointReference.SERVICE_REF_QNAME.getNamespaceURI(),
+          EndpointReference.SERVICE_REF_QNAME.getLocalPart());
+        
serviceRef.appendChild(doc.createTextNode(myRoleEndpoint.serviceName.toString()));
+        doc.appendChild(serviceRef);
+        _activated.put(myRoleEndpoint.toString(), processId);
+        return new EndpointReference() {
+          public Document toXML() {
+            return doc;
+          }
+        };
+      }
+
+      public void deactivateMyRoleEndpoint(Endpoint myRoleEndpoint) {
+        _activated.remove(myRoleEndpoint);
+      }
+
+      public PartnerRoleChannel createPartnerRoleChannel(QName processId, 
DeploymentUnit deploymentUnit, PortType portType, 
+                                                         final Endpoint 
initialPartnerEndpoint) {
+        final EndpointReference epr = new EndpointReference() {
+          public Document toXML() {
+            Document doc = DOMUtils.newDocument();
+            Element serviceRef = 
doc.createElementNS(EndpointReference.SERVICE_REF_QNAME.getNamespaceURI(),
+              EndpointReference.SERVICE_REF_QNAME.getLocalPart());
+            
serviceRef.appendChild(doc.createTextNode(initialPartnerEndpoint.serviceName.toString()));
+            doc.appendChild(serviceRef);
+            return doc;
+          }
+        };
+        _endpoints.put(initialPartnerEndpoint.serviceName.toString(), epr);
+        return new PartnerRoleChannel() {
+          public EndpointReference getInitialEndpointReference() {
+            return epr;
+          }
+          public void close() { };
+        }; 
+      }
+    };
+    return _bindContext;
+  }
+
+  /**
+   * An [EMAIL PROTECTED] javax.naming.spi.ObjectFactory} implementation that 
can be used to bind the
+   * JOTM [EMAIL PROTECTED] javax.transaction.TransactionManager} 
implementation in JNDI.
+   */
+  private class JotmTransactionManagerFactory implements ObjectFactory {
+    public Object getObjectInstance(Object objref, Name name, Context ctx, 
Hashtable env) throws Exception {
+      Reference ref = (Reference) objref;
+      if (ref.getClassName().equals(TransactionManager.class.getName())) {
+        return _jotm.getTransactionManager();
+      }
+      throw new RuntimeException("The reference class name \"" + 
ref.getClassName() + "\" is unknown.");
+    }
+  }
+
+  /**
+   * JNDI [EMAIL PROTECTED] ObjectFactory} implementation for Hibernate-based
+   * connection factory objects.
+   */
+  private class HibernateDaoObjectFactory implements ObjectFactory {
+    public Object getObjectInstance(Object objref, Name name, Context ctx, 
Hashtable env) throws Exception {
+      Reference ref = (Reference) objref;
+      if (ref.getClassName().equals(BpelDAOConnectionFactory.class.getName())) 
{
+        return _daoCF;
+      }
+      throw new RuntimeException("The reference class name \"" + 
ref.getClassName() + "\" is unknown.");
+    }
+  }
+
+}

Propchange: 
incubator/ode/trunk/bpel-runtime/src/test/java/org/apache/ode/bpel/runtime/MockBpelServer.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: 
incubator/ode/trunk/bpel-runtime/src/test/java/org/apache/ode/bpel/runtime/MockBpelServer.java
------------------------------------------------------------------------------
    svn:keywords = Date Revision

Propchange: 
incubator/ode/trunk/bpel-runtime/src/test/java/org/apache/ode/bpel/runtime/MockBpelServer.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain


Reply via email to