You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ode.apache.org by ka...@apache.org on 2009/04/03 20:06:39 UTC

svn commit: r761744 [1/2] - in /ode/branches/APACHE_ODE_1.X: ./ agents/ agents/src/ agents/src/main/ agents/src/main/java/ agents/src/main/java/org/ agents/src/main/java/org/apache/ agents/src/main/java/org/apache/ode/ agents/src/main/java/org/apache/o...

Author: karthick
Date: Fri Apr  3 18:06:37 2009
New Revision: 761744

URL: http://svn.apache.org/viewvc?rev=761744&view=rev
Log:
ODE-561 Improve Process Cache Design

Added:
    ode/branches/APACHE_ODE_1.X/agents/
    ode/branches/APACHE_ODE_1.X/agents/src/
    ode/branches/APACHE_ODE_1.X/agents/src/main/
    ode/branches/APACHE_ODE_1.X/agents/src/main/java/
    ode/branches/APACHE_ODE_1.X/agents/src/main/java/org/
    ode/branches/APACHE_ODE_1.X/agents/src/main/java/org/apache/
    ode/branches/APACHE_ODE_1.X/agents/src/main/java/org/apache/ode/
    ode/branches/APACHE_ODE_1.X/agents/src/main/java/org/apache/ode/agents/
    ode/branches/APACHE_ODE_1.X/agents/src/main/java/org/apache/ode/agents/memory/
    ode/branches/APACHE_ODE_1.X/agents/src/main/java/org/apache/ode/agents/memory/SizingAgent.java
    ode/branches/APACHE_ODE_1.X/agents/src/main/resources/
    ode/branches/APACHE_ODE_1.X/agents/src/main/resources/META-INF/
    ode/branches/APACHE_ODE_1.X/agents/src/main/resources/META-INF/MANIFEST.MF
    ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/hydration/
    ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/hydration/InstanceCountTest.java
    ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/hydration/ProcessCountTest.java
    ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/hydration/ProcessSizeTest.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/intercept/InstanceCountThrottler.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/intercept/ProcessCountThrottler.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/intercept/ProcessSizeThrottler.java
Removed:
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/intercept/ThrottlingInterceptor.java
Modified:
    ode/branches/APACHE_ODE_1.X/Rakefile
    ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/JettyWrapper.java
    ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/BindingContextImpl.java
    ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/ODEServer.java
    ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/ODEService.java
    ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/deploy/DeploymentPoller.java
    ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/util/SoapMessageConverter.java
    ode/branches/APACHE_ODE_1.X/bpel-api/src/main/java/org/apache/ode/bpel/iapi/BindingContext.java
    ode/branches/APACHE_ODE_1.X/bpel-api/src/main/java/org/apache/ode/bpel/iapi/BpelEngine.java
    ode/branches/APACHE_ODE_1.X/bpel-api/src/main/java/org/apache/ode/bpel/iapi/ProcessConf.java
    ode/branches/APACHE_ODE_1.X/bpel-compiler/src/main/java/org/apache/ode/bpel/compiler/BpelCompiler.java
    ode/branches/APACHE_ODE_1.X/bpel-epr/src/main/java/org/apache/ode/bpel/epr/EndpointFactory.java
    ode/branches/APACHE_ODE_1.X/bpel-epr/src/main/java/org/apache/ode/il/config/OdeConfigProperties.java
    ode/branches/APACHE_ODE_1.X/bpel-obj/src/main/java/org/apache/ode/bpel/o/OConstants.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/BpelEngineImpl.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/BpelProcess.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/BpelRuntimeContextImpl.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/BpelServerImpl.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/Contexts.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/InterceptorContextImpl.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/MessageExchangeImpl.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/MyRoleMessageExchangeImpl.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/NStateLatch.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/PartnerLinkMyRoleImpl.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/intercept/InterceptorInvoker.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/intercept/MessageExchangeInterceptor.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/intercept/NoOpInterceptor.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/runtime/InvalidProcessException.java
    ode/branches/APACHE_ODE_1.X/bpel-runtime/src/test/java/org/apache/ode/bpel/runtime/MockBpelServer.java
    ode/branches/APACHE_ODE_1.X/bpel-store/src/main/java/org/apache/ode/store/ProcessConfImpl.java
    ode/branches/APACHE_ODE_1.X/bpel-test/src/main/java/org/apache/ode/test/BindingContextImpl.java
    ode/branches/APACHE_ODE_1.X/bpel-test/src/main/java/org/apache/ode/test/MessageExchangeContextImpl.java
    ode/branches/APACHE_ODE_1.X/bpel-test/src/test/java/org/apache/ode/test/BasicActivities20Test.java
    ode/branches/APACHE_ODE_1.X/bpel-test/src/test/java/org/apache/ode/test/StructuredActivities20Test.java
    ode/branches/APACHE_ODE_1.X/dao-jpa/src/main/java/org/apache/ode/dao/jpa/ActivityRecoveryDAOImpl.java
    ode/branches/APACHE_ODE_1.X/dao-jpa/src/main/java/org/apache/ode/dao/jpa/ProcessDAOImpl.java
    ode/branches/APACHE_ODE_1.X/dao-jpa/src/main/java/org/apache/ode/dao/jpa/ProcessInstanceDAOImpl.java
    ode/branches/APACHE_ODE_1.X/jbi/src/main/java/org/apache/ode/jbi/BindingContextImpl.java
    ode/branches/APACHE_ODE_1.X/jbi/src/main/java/org/apache/ode/jbi/OdeContext.java

Modified: ode/branches/APACHE_ODE_1.X/Rakefile
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/Rakefile?rev=761744&r1=761743&r2=761744&view=diff
==============================================================================
--- ode/branches/APACHE_ODE_1.X/Rakefile (original)
+++ ode/branches/APACHE_ODE_1.X/Rakefile Fri Apr  3 18:06:37 2009
@@ -146,7 +146,7 @@
   desc "ODE Axis Integration Layer"
   define "axis2" do
     compile.with projects("bpel-api", "bpel-connector", "bpel-dao", "bpel-epr", "bpel-runtime",
-      "scheduler-simple", "bpel-schemas", "bpel-store", "utils"),
+      "scheduler-simple", "bpel-schemas", "bpel-store", "utils", "agents"),
       AXIOM, AXIS2_ALL, COMMONS.lang, COMMONS.logging, COMMONS.collections, COMMONS.httpclient, COMMONS.lang, 
       DERBY, GERONIMO.kernel, GERONIMO.transaction, JAVAX.activation, JAVAX.servlet, JAVAX.stream, 
       JAVAX.transaction, JENCKS, WSDL4J, WS_COMMONS, XMLBEANS, AXIS2_MODULES.libs
@@ -280,8 +280,8 @@
   desc "ODE Runtime Engine"
   define "bpel-runtime" do
     compile.from apt
-    compile.with projects("bpel-api", "bpel-compiler", "bpel-dao", "bpel-obj", "bpel-schemas",
-      "bpel-store", "jacob", "jacob-ap", "utils"),
+    compile.with projects("bpel-api", "bpel-compiler", "bpel-dao", "bpel-epr", "bpel-obj", "bpel-schemas",
+      "bpel-store", "jacob", "jacob-ap", "utils", "agents"),
       COMMONS.logging, COMMONS.collections, COMMONS.httpclient, JAXEN, JAVAX.persistence, JAVAX.stream, SAXON, WSDL4J, XMLBEANS
 
     test.with projects("scheduler-simple", "dao-jpa", "dao-hibernate", "bpel-epr"),
@@ -328,7 +328,7 @@
   desc "ODE BPEL Tests"
   define "bpel-test" do
     compile.with projects("bpel-api", "bpel-compiler", "bpel-dao", "bpel-runtime",
-      "bpel-store", "utils", "bpel-epr", "dao-jpa"),
+      "bpel-store", "utils", "bpel-epr", "dao-jpa", "agents"),
       DERBY, Java::JUnit::JUNIT_REQUIRES, JAVAX.persistence, OPENJPA, WSDL4J, COMMONS.httpclient,
     COMMONS.codec
 
@@ -451,7 +451,7 @@
   desc "ODE JBI Integration Layer"
   define "jbi" do
     compile.with projects("bpel-api", "bpel-connector", "bpel-dao", "bpel-epr", "bpel-obj",
-      "bpel-runtime", "scheduler-simple", "bpel-schemas", "bpel-store", "utils"),
+      "bpel-runtime", "scheduler-simple", "bpel-schemas", "bpel-store", "utils", "agents"),
       AXIOM, COMMONS.logging, COMMONS.pool, JAVAX.transaction, JBI, LOG4J, WSDL4J, XERCES
 
     package(:jar)
@@ -508,6 +508,12 @@
     test.exclude "*TestResources"
     package :jar
   end
+  
+  desc "ODE Agents"
+  define "agents" do
+     compile
+     package (:jar, :manifest=>_("target/classes/META-INF/MANIFEST.MF"))
+  end
 
 end
 
@@ -580,7 +586,7 @@
 
   package(:zip, :id=>"#{id}-sources").path("#{id}-sources-#{version}").tap do |zip|
     if File.exist?(".svn")
-      `svn status -v`.reject { |l| l[0] == ?? || l[0] == ?D }.
+      `svn status -v`.reject { |l| l[0] == ?? || l[0] == ?D || l.strip.empty? || l[0...3] == "---"}.
         map { |l| l.split.last }.reject { |f| File.directory?(f) }.
         each { |f| zip.include f, :as=>f }
     else

Added: ode/branches/APACHE_ODE_1.X/agents/src/main/java/org/apache/ode/agents/memory/SizingAgent.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/agents/src/main/java/org/apache/ode/agents/memory/SizingAgent.java?rev=761744&view=auto
==============================================================================
--- ode/branches/APACHE_ODE_1.X/agents/src/main/java/org/apache/ode/agents/memory/SizingAgent.java (added)
+++ ode/branches/APACHE_ODE_1.X/agents/src/main/java/org/apache/ode/agents/memory/SizingAgent.java Fri Apr  3 18:06:37 2009
@@ -0,0 +1,186 @@
+package org.apache.ode.agents.memory;
+
+import java.lang.instrument.Instrumentation;
+import java.lang.reflect.Array;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.Calendar;
+import java.util.IdentityHashMap;
+import java.util.Map;
+import java.util.Stack;
+
+
+/**
+ * Class 
+ *
+ * @author $author$
+ * @version $Revision$
+  */
+public class SizingAgent {
+    private static Instrumentation instrumentation;
+
+    /**
+     * $method$
+     *
+     * @param options options 
+     * @param instrumentation instrumentation 
+     */
+    public static void premain(String options, Instrumentation instrumentation) {
+        SizingAgent.instrumentation = instrumentation;
+        Class[] loaded = instrumentation.getAllLoadedClasses();
+    }
+    
+    /**
+     * $method$
+     *
+     * @param args args 
+     */
+    public static void main(String[] args) {
+        System.out.println("Size of Object: " + sizeOf(new Object()));
+        System.out.println("Size of direct subclass: " + sizeOf(new SizingAgent()));
+        System.out.println("Size of Calendar: " +
+            sizeOf(Calendar.getInstance()));
+    }
+
+    /**
+     * Returns object size.
+     */
+    public static long sizeOf(Object obj) {
+        if (instrumentation == null) {
+        	return 0;
+        }
+
+        if (isSharedFlyweight(obj)) {
+            return 0;
+        }
+
+        return instrumentation.getObjectSize(obj);
+    }
+
+    /**
+     * Returns deep size of object, recursively iterating over its
+     * fields and superclasses.
+     */
+    public static long deepSizeOf(Object obj) {
+        if (instrumentation == null) {
+        	return 0;
+        }
+        
+        Map visited = new IdentityHashMap();
+        Stack stack = new Stack();
+        stack.push(obj);
+
+        long result = 0;
+
+        do {
+            result += internalSizeOf(stack.pop(), stack, visited);
+        } while (!stack.isEmpty());
+
+        return result;
+    }
+
+    /**
+     * Returns true if this is a well-known shared flyweight. For
+     * example, interned Strings, Booleans and Number objects
+     */
+    private static boolean isSharedFlyweight(Object obj) {
+        // optimization - all of our flyweights are Comparable
+        if (obj instanceof Comparable) {
+            if (obj instanceof Enum) {
+                return true;
+            } else if (obj instanceof String) {
+                return (obj == ((String) obj).intern());
+            } else if (obj instanceof Boolean) {
+                return ((obj == Boolean.TRUE) || (obj == Boolean.FALSE));
+            } else if (obj instanceof Integer) {
+                return (obj == Integer.valueOf((Integer) obj));
+            } else if (obj instanceof Short) {
+                return (obj == Short.valueOf((Short) obj));
+            } else if (obj instanceof Byte) {
+                return (obj == Byte.valueOf((Byte) obj));
+            } else if (obj instanceof Long) {
+                return (obj == Long.valueOf((Long) obj));
+            } else if (obj instanceof Character) {
+                return (obj == Character.valueOf((Character) obj));
+            }
+        }
+
+        return false;
+    }
+
+    /**
+     * $method$
+     *
+     * @param obj obj 
+     * @param visited visited 
+     *
+     * @return type
+     */
+    private static boolean skipObject(Object obj, Map visited) {
+        return (obj == null) || visited.containsKey(obj) ||
+        isSharedFlyweight(obj);
+    }
+
+    /**
+     * $method$
+     *
+     * @param obj obj 
+     * @param stack stack 
+     * @param visited visited 
+     *
+     * @return type
+     */
+    private static long internalSizeOf(Object obj, Stack stack, Map visited) {
+        if (skipObject(obj, visited)) {
+            return 0;
+        }
+
+        Class clazz = obj.getClass();
+
+        if (clazz.isArray()) {
+            addArrayElementsToStack(clazz, obj, stack);
+        } else {
+            // add all non-primitive fields to the stack
+            while (clazz != null) {
+                Field[] fields = clazz.getDeclaredFields();
+
+                for (Field field : fields) {
+                    if (!Modifier.isStatic(field.getModifiers()) &&
+                            !field.getType().isPrimitive()) {
+                        field.setAccessible(true);
+
+                        try {
+                            stack.add(field.get(obj));
+                        } catch (IllegalAccessException ex) {
+                            throw new RuntimeException(ex);
+                        }
+                    }
+                }
+
+                clazz = clazz.getSuperclass();
+            }
+        }
+
+        visited.put(obj, null);
+
+        return sizeOf(obj);
+    }
+
+    /**
+     * $method$
+     *
+     * @param clazz clazz 
+     * @param obj obj 
+     * @param stack stack 
+     */
+    private static void addArrayElementsToStack(Class clazz, Object obj,
+        Stack stack) {
+        if (!clazz.getComponentType().isPrimitive()) {
+            int length = Array.getLength(obj);
+
+            for (int i = 0; i < length; i++) {
+                stack.add(Array.get(obj, i));
+            }
+        }
+    }
+}

Added: ode/branches/APACHE_ODE_1.X/agents/src/main/resources/META-INF/MANIFEST.MF
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/agents/src/main/resources/META-INF/MANIFEST.MF?rev=761744&view=auto
==============================================================================
--- ode/branches/APACHE_ODE_1.X/agents/src/main/resources/META-INF/MANIFEST.MF (added)
+++ ode/branches/APACHE_ODE_1.X/agents/src/main/resources/META-INF/MANIFEST.MF Fri Apr  3 18:06:37 2009
@@ -0,0 +1,2 @@
+Manifest-Version: 1.0
+Premain-Class: org.apache.ode.agents.memory.SizingAgent
\ No newline at end of file

Modified: ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/JettyWrapper.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/JettyWrapper.java?rev=761744&r1=761743&r2=761744&view=diff
==============================================================================
--- ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/JettyWrapper.java (original)
+++ ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/JettyWrapper.java Fri Apr  3 18:06:37 2009
@@ -84,7 +84,12 @@
     }
 
     public void start() throws Exception {
-        server.start();
+        try {
+        	server.start();
+        } catch (Exception e) {
+        	server.stop();
+        	server.start();
+        }
     }
 
     public void stop() throws Exception {

Added: ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/hydration/InstanceCountTest.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/hydration/InstanceCountTest.java?rev=761744&view=auto
==============================================================================
--- ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/hydration/InstanceCountTest.java (added)
+++ ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/hydration/InstanceCountTest.java Fri Apr  3 18:06:37 2009
@@ -0,0 +1,163 @@
+package org.apache.ode.axis2.hydration;
+
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.OMNamespace;
+import org.apache.axiom.om.OMText;
+import org.apache.axiom.om.util.Base64;
+
+import org.apache.ode.axis2.Axis2TestBase;
+import org.apache.ode.axis2.DummyService;
+import org.apache.ode.axis2.service.ServiceClientUtil;
+import org.apache.ode.tools.sendsoap.cline.HttpSoapSender;
+import org.apache.ode.utils.Namespaces;
+
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+
+import java.net.URL;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+
+import javax.xml.namespace.QName;
+
+
+/**
+ * Test the limit on the number of process instances. 
+ *
+ * @author $author$
+ * @version $Revision$
+  */
+public class InstanceCountTest extends Axis2TestBase {
+    private OMFactory _factory;
+    private DateFormat xsdDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
+    private ServiceClientUtil _client;
+    private String _deployedName;
+
+    /**
+     * test case set up
+     *
+     * @throws Exception Exception 
+     */
+    @BeforeMethod
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        // Create a factory
+        _factory = OMAbstractFactory.getOMFactory();
+        _client = new ServiceClientUtil();
+
+        // Just making sure the instance starts
+        Thread.sleep(1000);
+    }
+
+    /**
+     * test case tear down
+     *
+     * @throws Exception Exception 
+     */
+    @AfterMethod
+    protected void tearDown() throws Exception {
+        super.tearDown();
+    }
+    
+    /**
+     * Tests rendezvous
+     * 
+     * @throws Exception
+     */
+    String firstResponse, secondResponse;
+    boolean secondStarted;
+    
+    @Test(dataProvider="configs")
+    public void testCorrelationJoin() throws Exception {
+        final String bundleName = "TestCorrelationJoin";
+        
+        firstResponse = secondResponse = null;
+        secondStarted = true;
+        
+        server.getODEServer().getBpelServer().setInstanceThrottledMaximumCount(1);
+        // deploy the required service
+        server.deployService(DummyService.class.getCanonicalName());
+        if (server.isDeployed(bundleName)) server.undeployProcess(bundleName);
+        server.deployProcess(bundleName);
+
+        new Thread() {
+            public void run() {
+                try {
+                    Thread.sleep(3000);
+                    server.sendRequestFile("http://localhost:8888/processes/correlationMultiTest",
+                            bundleName, "testRequest2.soap");
+                } catch( Exception e ) {
+                    fail(e.getMessage());
+                }
+            }
+        }.start();        
+        
+        Thread processOne = new Thread() {
+        	public void run() {
+                try {
+                    firstResponse = server.sendRequestFile("http://localhost:8888/processes/correlationMultiTest",
+                            bundleName, "testRequest.soap");
+                    System.out.println("=>\n" + firstResponse);
+                } catch (Exception e) {
+                    fail(e.getMessage());
+                }
+        	}
+        };
+        processOne.start();
+        
+        Thread processTwo = new Thread() {
+            public void run() {
+                try {
+                    Thread.sleep(3000);
+                    secondResponse = server.sendRequestFile("http://localhost:8888/processes/correlationMultiTest",
+                            bundleName, "testRequest.soap");
+                } catch( Exception e ) {
+                    fail(e.getMessage());
+                }
+            }
+        };
+        processTwo.start();
+        processTwo.join();
+
+        try {
+	        assertTrue(secondResponse.contains("tooManyInstances"));
+        } catch (Exception e) {
+            server.undeployProcess(bundleName);
+			fail("The second instance was allowed to start");
+        }
+		
+        new Thread() {
+            public void run() {
+                try {
+                    Thread.sleep(6000);
+                    server.sendRequestFile("http://localhost:8888/processes/correlationMultiTest",
+                            bundleName, "testRequest3.soap");
+                } catch( Exception e ) {
+                    fail(e.getMessage());
+                }
+            }
+        }.start();
+
+        try {
+	        processOne.join();        
+	        assertTrue(firstResponse.contains(">1;2;3;<"));
+        } finally {
+	        server.undeployProcess(bundleName);
+        }
+    }
+
+    public String getODEConfigDir() {
+        return getClass().getClassLoader().getResource("webapp").getFile() + "/WEB-INF/conf.jpa-derby"; 
+    }    
+}

Added: ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/hydration/ProcessCountTest.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/hydration/ProcessCountTest.java?rev=761744&view=auto
==============================================================================
--- ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/hydration/ProcessCountTest.java (added)
+++ ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/hydration/ProcessCountTest.java Fri Apr  3 18:06:37 2009
@@ -0,0 +1,125 @@
+package org.apache.ode.axis2.hydration;
+
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+import static org.testng.AssertJUnit.assertTrue;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.OMNamespace;
+import org.apache.axiom.om.OMText;
+import org.apache.axiom.om.util.Base64;
+
+import org.apache.ode.axis2.Axis2TestBase;
+import org.apache.ode.axis2.DummyService;
+import org.apache.ode.axis2.service.ServiceClientUtil;
+import org.apache.ode.tools.sendsoap.cline.HttpSoapSender;
+import org.apache.ode.utils.DOMUtils;
+import org.apache.ode.utils.Namespaces;
+
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.w3c.dom.Element;
+
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+
+import java.net.URL;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+
+import javax.xml.namespace.QName;
+
+
+/**
+ * Test the limit on the number of process instances. 
+ *
+ * @author $author$
+ * @version $Revision$
+  */
+public class ProcessCountTest extends Axis2TestBase {
+    private OMFactory _factory;
+    private DateFormat xsdDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
+    private ServiceClientUtil _client;
+    private String _deployedName;
+
+    /**
+     * test case set up
+     *
+     * @throws Exception Exception 
+     */
+    @BeforeMethod
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        // Create a factory
+        _factory = OMAbstractFactory.getOMFactory();
+        _client = new ServiceClientUtil();
+
+        // Just making sure the instance starts
+        Thread.sleep(1000);
+    }
+
+    /**
+     * test case tear down
+     *
+     * @throws Exception Exception 
+     */
+    @AfterMethod
+    protected void tearDown() throws Exception {
+        super.tearDown();
+    }
+    
+    /**
+     * Tests rendezvous
+     * 
+     * @throws Exception
+     */
+    String firstResponse, secondResponse;
+    boolean secondStarted;
+    String nsAttr;
+    
+    @Test(dataProvider="configs")
+    public void testCorrelationJoin() throws Exception {
+        final String bundleOne = "TestCorrelationJoin", bundleTwo = "TestAttributeNamespaces";
+        
+        firstResponse = secondResponse = null;
+        secondStarted = true;
+        
+        server.getODEServer().getBpelServer().setProcessThrottledMaximumCount(0);
+
+        // deploy the first service
+        server.deployService(DummyService.class.getCanonicalName());
+        if (server.isDeployed(bundleOne)) server.undeployProcess(bundleOne);
+        server.deployProcess(bundleOne);
+
+        Thread processOne = new Thread() {
+        	public void run() {
+                try {
+                    firstResponse = server.sendRequestFile("http://localhost:8888/processes/correlationMultiTest",
+                            bundleOne, "testRequest.soap");
+                    System.out.println("=>\n" + firstResponse);
+                } catch (Exception e) {
+                    fail(e.getMessage());
+                }
+        	}
+        };
+        processOne.start();
+        processOne.join();
+        
+        try {
+	        processOne.join();        
+	        assertTrue(firstResponse.contains("tooManyProcesses"), firstResponse);
+        } finally {
+	        server.undeployProcess(bundleOne);
+        }
+        
+    }
+
+    public String getODEConfigDir() {
+        return getClass().getClassLoader().getResource("webapp").getFile() + "/WEB-INF/conf.jpa-derby"; 
+    }    
+}

Added: ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/hydration/ProcessSizeTest.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/hydration/ProcessSizeTest.java?rev=761744&view=auto
==============================================================================
--- ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/hydration/ProcessSizeTest.java (added)
+++ ode/branches/APACHE_ODE_1.X/axis2-war/src/test/java/org/apache/ode/axis2/hydration/ProcessSizeTest.java Fri Apr  3 18:06:37 2009
@@ -0,0 +1,125 @@
+package org.apache.ode.axis2.hydration;
+
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+import static org.testng.AssertJUnit.assertTrue;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.OMNamespace;
+import org.apache.axiom.om.OMText;
+import org.apache.axiom.om.util.Base64;
+
+import org.apache.ode.axis2.Axis2TestBase;
+import org.apache.ode.axis2.DummyService;
+import org.apache.ode.axis2.service.ServiceClientUtil;
+import org.apache.ode.tools.sendsoap.cline.HttpSoapSender;
+import org.apache.ode.utils.DOMUtils;
+import org.apache.ode.utils.Namespaces;
+
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.w3c.dom.Element;
+
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+
+import java.net.URL;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+
+import javax.xml.namespace.QName;
+
+
+/**
+ * Test the limit on the number of process instances. 
+ *
+ * @author $author$
+ * @version $Revision$
+  */
+public class ProcessSizeTest extends Axis2TestBase {
+    private OMFactory _factory;
+    private DateFormat xsdDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
+    private ServiceClientUtil _client;
+    private String _deployedName;
+
+    /**
+     * test case set up
+     *
+     * @throws Exception Exception 
+     */
+    @BeforeMethod
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        // Create a factory
+        _factory = OMAbstractFactory.getOMFactory();
+        _client = new ServiceClientUtil();
+
+        // Just making sure the instance starts
+        Thread.sleep(1000);
+    }
+
+    /**
+     * test case tear down
+     *
+     * @throws Exception Exception 
+     */
+    @AfterMethod
+    protected void tearDown() throws Exception {
+        super.tearDown();
+    }
+    
+    /**
+     * Tests rendezvous
+     * 
+     * @throws Exception
+     */
+    String firstResponse, secondResponse;
+    boolean secondStarted;
+    String nsAttr;
+    
+    @Test(dataProvider="configs")
+    public void testCorrelationJoin() throws Exception {
+        final String bundleOne = "TestCorrelationJoin", bundleTwo = "TestAttributeNamespaces";
+        
+        firstResponse = secondResponse = null;
+        secondStarted = true;
+        
+        server.getODEServer().getBpelServer().setProcessThrottledMaximumSize(0);
+
+        // deploy the first service
+        server.deployService(DummyService.class.getCanonicalName());
+        if (server.isDeployed(bundleOne)) server.undeployProcess(bundleOne);
+        server.deployProcess(bundleOne);
+
+        Thread processOne = new Thread() {
+        	public void run() {
+                try {
+                    firstResponse = server.sendRequestFile("http://localhost:8888/processes/correlationMultiTest",
+                            bundleOne, "testRequest.soap");
+                    System.out.println("=>\n" + firstResponse);
+                } catch (Exception e) {
+                    fail(e.getMessage());
+                }
+        	}
+        };
+        processOne.start();
+        processOne.join();
+        
+        try {
+	        processOne.join();        
+	        assertTrue(firstResponse.contains("tooHugeProcesses"), firstResponse);
+        } finally {
+	        server.undeployProcess(bundleOne);
+        }
+        
+    }
+
+    public String getODEConfigDir() {
+        return getClass().getClassLoader().getResource("webapp").getFile() + "/WEB-INF/conf.jpa-derby"; 
+    }    
+}

Modified: ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/BindingContextImpl.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/BindingContextImpl.java?rev=761744&r1=761743&r2=761744&view=diff
==============================================================================
--- ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/BindingContextImpl.java (original)
+++ ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/BindingContextImpl.java Fri Apr  3 18:06:37 2009
@@ -20,6 +20,15 @@
 
 package org.apache.ode.axis2;
 
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import javax.wsdl.Definition;
+import javax.wsdl.PortType;
+import javax.xml.namespace.QName;
+
 import org.apache.axis2.AxisFault;
 import org.apache.axis2.description.AxisOperation;
 import org.apache.axis2.description.AxisService;
@@ -27,18 +36,18 @@
 import org.apache.commons.collections.map.MultiKeyMap;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
+import org.apache.ode.agents.memory.SizingAgent;
 import org.apache.ode.axis2.hooks.ODEAxisService;
 import org.apache.ode.axis2.hooks.ODEMessageReceiver;
 import org.apache.ode.axis2.httpbinding.HttpExternalService;
-import org.apache.ode.bpel.iapi.*;
+import org.apache.ode.bpel.iapi.BindingContext;
+import org.apache.ode.bpel.iapi.ContextException;
+import org.apache.ode.bpel.iapi.Endpoint;
+import org.apache.ode.bpel.iapi.EndpointReference;
+import org.apache.ode.bpel.iapi.PartnerRoleChannel;
+import org.apache.ode.bpel.iapi.ProcessConf;
 import org.apache.ode.utils.wsdl.WsdlUtils;
 
-import javax.wsdl.Definition;
-import javax.wsdl.PortType;
-import javax.xml.namespace.QName;
-import java.util.ArrayList;
-import java.util.Iterator;
-
 /**
  * AXIS2 implementation of the {@link org.apache.ode.bpel.iapi.BindingContext}
  * interface. Deals with the activation of endpoints.
@@ -51,6 +60,7 @@
 
     private ODEServer _server;
     private MultiKeyMap _services = new MultiKeyMap();
+    private Map<ODEService, EndpointReference> _serviceEprMap = new HashMap<ODEService, EndpointReference>();
 
     public BindingContextImpl(ODEServer server) {
         _server = server;
@@ -64,7 +74,9 @@
                 throw new ContextException("Unable to access WSDL definition to activate MyRole endpoint for service " + myRoleEndpoint.serviceName
                         + " and port " + myRoleEndpoint.portName);
             ODEService svc = createService(pconf, myRoleEndpoint.serviceName, myRoleEndpoint.portName);
-            return svc.getMyServiceRef();
+            EndpointReference epr = svc.getMyServiceRef();
+            _serviceEprMap.put(svc, epr);
+            return epr;
         } catch (AxisFault axisFault) {
             throw new ContextException("Could not activate endpoint for service " + myRoleEndpoint.serviceName
                     + " and port " + myRoleEndpoint.portName, axisFault);
@@ -72,7 +84,10 @@
     }
 
     public void deactivateMyRoleEndpoint(Endpoint myRoleEndpoint) {
-        destroyService(myRoleEndpoint.serviceName, myRoleEndpoint.portName);
+        ODEService service = destroyService(myRoleEndpoint.serviceName, myRoleEndpoint.portName);
+        if (service != null) {
+	        _serviceEprMap.remove(service);
+        }
     }
 
     public PartnerRoleChannel createPartnerRoleChannel(QName processId, PortType portType,
@@ -83,11 +98,22 @@
         Definition wsdl = pconf.getDefinitionForService(initialPartnerEndpoint.serviceName);
         if (wsdl == null) {
             throw new ContextException("Cannot find definition for service " + initialPartnerEndpoint.serviceName
-                    + " in the context of process " + processId);
+                                       + " in the context of process "+processId);
         }
         return createExternalService(pconf, initialPartnerEndpoint.serviceName, initialPartnerEndpoint.portName);
     }
 
+	public long calculateSizeofService(EndpointReference epr) {
+		if (_server._odeConfig.isProcessSizeThrottled()) {
+			for (ODEService service : _serviceEprMap.keySet()) {
+				if (epr.equals(_serviceEprMap.get(epr))) {
+					return SizingAgent.deepSizeOf(service);
+				}
+			}
+		}
+		return 0;
+	}
+	
     protected ODEService createService(ProcessConf pconf, QName serviceName, String portName) throws AxisFault {
         AxisService axisService = ODEAxisService.createService(_server._axisConfig, pconf, serviceName, portName);
         ODEService odeService = new ODEService(axisService, pconf, serviceName, portName, _server._bpelServer, _server._txMgr);
@@ -111,8 +137,7 @@
         return odeService;
     }
 
-
-    protected void destroyService(QName serviceName, String portName) {
+    protected ODEService destroyService(QName serviceName, String portName) {
         __log.debug("Destroying service " + serviceName + " port " + portName);
         ODEService service = (ODEService) _services.remove(serviceName, portName);
         if (service != null) {
@@ -140,6 +165,7 @@
         } else {
             __log.debug("Couldn't find service " + serviceName + " port " + portName + " to destroy.");
         }
+        return service;
     }
 
     protected ExternalService createExternalService(ProcessConf pconf, QName serviceName, String portName) throws ContextException {

Modified: ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/ODEServer.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/ODEServer.java?rev=761744&r1=761743&r2=761744&view=diff
==============================================================================
--- ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/ODEServer.java (original)
+++ ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/ODEServer.java Fri Apr  3 18:06:37 2009
@@ -19,12 +19,33 @@
 
 package org.apache.ode.axis2;
 
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.StringTokenizer;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.sql.DataSource;
+import javax.transaction.HeuristicMixedException;
+import javax.transaction.HeuristicRollbackException;
+import javax.transaction.InvalidTransactionException;
+import javax.transaction.NotSupportedException;
+import javax.transaction.RollbackException;
+import javax.transaction.Synchronization;
+import javax.transaction.SystemException;
+import javax.transaction.Transaction;
+import javax.transaction.TransactionManager;
+import javax.transaction.xa.XAResource;
+
 import org.apache.axis2.AxisFault;
 import org.apache.axis2.engine.AxisConfiguration;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
 import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
 import org.apache.ode.axis2.deploy.DeploymentPoller;
 import org.apache.ode.axis2.service.DeploymentWebService;
 import org.apache.ode.axis2.service.ManagementService;
@@ -34,11 +55,11 @@
 import org.apache.ode.bpel.engine.CountLRUDehydrationPolicy;
 import org.apache.ode.bpel.extvar.jdbc.JdbcExternalVariableModule;
 import org.apache.ode.bpel.iapi.BpelEventListener;
+import org.apache.ode.bpel.iapi.EndpointReferenceContext;
 import org.apache.ode.bpel.iapi.ProcessConf;
 import org.apache.ode.bpel.iapi.ProcessStoreEvent;
 import org.apache.ode.bpel.iapi.ProcessStoreListener;
 import org.apache.ode.bpel.iapi.Scheduler;
-import org.apache.ode.bpel.iapi.EndpointReferenceContext;
 import org.apache.ode.bpel.intercept.MessageExchangeInterceptor;
 import org.apache.ode.bpel.memdao.BpelDAOConnectionFactoryImpl;
 import org.apache.ode.bpel.pmapi.InstanceManagement;
@@ -50,27 +71,6 @@
 import org.apache.ode.utils.GUID;
 import org.apache.ode.utils.fs.TempFileManager;
 
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletException;
-import javax.sql.DataSource;
-import javax.transaction.HeuristicMixedException;
-import javax.transaction.HeuristicRollbackException;
-import javax.transaction.InvalidTransactionException;
-import javax.transaction.NotSupportedException;
-import javax.transaction.RollbackException;
-import javax.transaction.Synchronization;
-import javax.transaction.SystemException;
-import javax.transaction.Transaction;
-import javax.transaction.TransactionManager;
-import javax.transaction.xa.XAResource;
-import javax.wsdl.WSDLException;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.util.StringTokenizer;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
-
 /**
  * Server class called by our Axis hooks to handle all ODE lifecycle management.
  *
@@ -121,72 +121,72 @@
     }
 
     public void init(String contextPath, AxisConfiguration axisConf) throws ServletException {
-        _axisConfig = axisConf;
-        String rootDir = System.getProperty("org.apache.ode.rootDir");
-        if (rootDir != null) _appRoot = new File(rootDir);
-        else _appRoot = new File(contextPath);
+            _axisConfig = axisConf;
+            String rootDir = System.getProperty("org.apache.ode.rootDir");
+            if (rootDir != null) _appRoot = new File(rootDir);
+            else _appRoot = new File(contextPath);
 
         if (!_appRoot.isDirectory())
             throw new IllegalArgumentException(_appRoot + " does not exist or is not a directory");
-        TempFileManager.setWorkingDirectory(_appRoot);
+            TempFileManager.setWorkingDirectory(_appRoot);
 
-        __log.debug("Loading properties");
-        String confDir = System.getProperty("org.apache.ode.configDir");
-        _configRoot = confDir == null ? new File(_appRoot, "conf") : new File(confDir);
+            __log.debug("Loading properties");
+            String confDir = System.getProperty("org.apache.ode.configDir");
+            _configRoot = confDir == null ? new File(_appRoot, "conf") : new File(confDir);
         if (!_configRoot.isDirectory())
             throw new IllegalArgumentException(_configRoot + " does not exist or is not a directory");
 
-        _odeConfig = new ODEConfigProperties(_configRoot);
+            _odeConfig = new ODEConfigProperties(_configRoot);
 
-        try {
-            _odeConfig.load();
-        } catch (FileNotFoundException fnf) {
-            String errmsg = __msgs.msgOdeInstallErrorCfgNotFound(_odeConfig.getFile());
-            __log.warn(errmsg);
-        } catch (Exception ex) {
-            String errmsg = __msgs.msgOdeInstallErrorCfgReadError(_odeConfig.getFile());
-            __log.error(errmsg, ex);
-            throw new ServletException(errmsg, ex);
-        }
+            try {
+                _odeConfig.load();
+            } catch (FileNotFoundException fnf) {
+                String errmsg = __msgs.msgOdeInstallErrorCfgNotFound(_odeConfig.getFile());
+                __log.warn(errmsg);
+            } catch (Exception ex) {
+                String errmsg = __msgs.msgOdeInstallErrorCfgReadError(_odeConfig.getFile());
+                __log.error(errmsg, ex);
+                throw new ServletException(errmsg, ex);
+            }
 
-        String wdir = _odeConfig.getWorkingDir();
-        if (wdir == null) _workRoot = _appRoot;
-        else _workRoot = new File(wdir.trim());
+            String wdir = _odeConfig.getWorkingDir();
+            if (wdir == null) _workRoot = _appRoot;
+            else _workRoot = new File(wdir.trim());
         if (!_workRoot.isDirectory())
             throw new IllegalArgumentException(_workRoot + " does not exist or is not a directory");
 
-        __log.debug("Initializing transaction manager");
-        initTxMgr();
-        __log.debug("Creating data source.");
-        initDataSource();
-        __log.debug("Starting DAO.");
-        initDAO();
-        EndpointReferenceContextImpl eprContext = new EndpointReferenceContextImpl(this);
-        __log.debug("Initializing BPEL process store.");
-        initProcessStore(eprContext);
-        __log.debug("Initializing BPEL server.");
-        initBpelServer(eprContext);
-        __log.debug("Initializing HTTP connection manager");
-        initHttpConnectionManager();
-
-        // Register BPEL event listeners configured in axis2.properties file.
-        registerEventListeners();
-        registerMexInterceptors();
-        registerExternalVariableModules();
+            __log.debug("Initializing transaction manager");
+            initTxMgr();
+            __log.debug("Creating data source.");
+            initDataSource();
+            __log.debug("Starting DAO.");
+            initDAO();
+            EndpointReferenceContextImpl eprContext = new EndpointReferenceContextImpl(this);            
+            __log.debug("Initializing BPEL process store.");
+            initProcessStore(eprContext);
+            __log.debug("Initializing BPEL server.");
+            initBpelServer(eprContext);
+            __log.debug("Initializing HTTP connection manager");
+            initHttpConnectionManager();
+
+            // Register BPEL event listeners configured in axis2.properties file.
+            registerEventListeners();
+            registerMexInterceptors();
+            registerExternalVariableModules();
 
-        _store.loadAll();
+            _store.loadAll();
 
-        try {
+            try {
             _bpelServer.start();
-        } catch (Exception ex) {
-            String errmsg = __msgs.msgOdeBpelServerStartFailure();
-            __log.error(errmsg, ex);
-            throw new ServletException(errmsg, ex);
-        }
+            } catch (Exception ex) {
+                String errmsg = __msgs.msgOdeBpelServerStartFailure();
+                __log.error(errmsg, ex);
+                throw new ServletException(errmsg, ex);
+            }
 
-        _poller = new DeploymentPoller(_store.getDeployDir(), this);
+            _poller = new DeploymentPoller(_store.getDeployDir(), this);
 
-        _mgtService = new ManagementService();
+            _mgtService = new ManagementService();
         _mgtService.enableService(_axisConfig, _bpelServer, _store, _appRoot.getAbsolutePath());
 
         try {
@@ -196,16 +196,16 @@
             throw new ServletException(e);
         }
 
-        __log.debug("Starting scheduler");
-        _scheduler.start();
+            __log.debug("Starting scheduler");
+            _scheduler.start();
 
-        __log.debug("Initializing JCA adapter.");
-        initConnector();
+            __log.debug("Initializing JCA adapter.");
+            initConnector();
 
-        _poller.start();
-        __log.info(__msgs.msgPollingStarted(_store.getDeployDir().getAbsolutePath()));
-        __log.info(__msgs.msgOdeStarted());
-    }
+            _poller.start();
+            __log.info(__msgs.msgPollingStarted(_store.getDeployDir().getAbsolutePath()));
+            __log.info(__msgs.msgOdeStarted());
+                }
 
     private void initDataSource() throws ServletException {
         _db = new Database(_odeConfig);
@@ -426,9 +426,13 @@
             dehy.setProcessMaxCount(_odeConfig.getDehydrationMaximumCount());
             _bpelServer.setDehydrationPolicy(dehy);
         }
-        _bpelServer.setHydrationLazy(_odeConfig.isHydrationLazy());
         _bpelServer.setConfigProperties(_odeConfig.getProperties());
         _bpelServer.init();
+        _bpelServer.setInstanceThrottledMaximumCount(_odeConfig.getInstanceThrottledMaximumCount());
+        _bpelServer.setProcessThrottledMaximumCount(_odeConfig.getProcessThrottledMaximumCount());
+        _bpelServer.setProcessThrottledMaximumSize(_odeConfig.getProcessThrottledMaximumSize());
+        _bpelServer.setHydrationLazy(_odeConfig.isHydrationLazy());
+        _bpelServer.setHydrationLazyMinimumSize(_odeConfig.getHydrationLazyMinimumSize());
     }
 
     private void initHttpConnectionManager() throws ServletException {
@@ -660,5 +664,4 @@
             _tx.setRollbackOnly();
         }
     }
-
 }

Modified: ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/ODEService.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/ODEService.java?rev=761744&r1=761743&r2=761744&view=diff
==============================================================================
--- ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/ODEService.java (original)
+++ ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/ODEService.java Fri Apr  3 18:06:37 2009
@@ -19,12 +19,25 @@
 
 package org.apache.ode.axis2;
 
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import javax.transaction.TransactionManager;
+import javax.wsdl.Definition;
+import javax.wsdl.Port;
+import javax.wsdl.Service;
+import javax.wsdl.extensions.UnknownExtensibilityElement;
+import javax.wsdl.extensions.http.HTTPAddress;
+import javax.wsdl.extensions.soap.SOAPAddress;
+import javax.xml.namespace.QName;
+
 import org.apache.axiom.soap.SOAPEnvelope;
 import org.apache.axiom.soap.SOAPFactory;
 import org.apache.axiom.soap.SOAPFault;
 import org.apache.axis2.AxisFault;
 import org.apache.axis2.context.MessageContext;
 import org.apache.axis2.description.AxisService;
+import org.apache.axis2.description.TwoChannelAxisOperation;
 import org.apache.axis2.transport.jms.JMSConstants;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
@@ -45,18 +58,6 @@
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-import javax.transaction.TransactionManager;
-import javax.wsdl.Definition;
-import javax.wsdl.Port;
-import javax.wsdl.Service;
-import javax.wsdl.extensions.UnknownExtensibilityElement;
-import javax.wsdl.extensions.http.HTTPAddress;
-import javax.wsdl.extensions.soap.SOAPAddress;
-import javax.xml.namespace.QName;
-
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-
 /**
  * A running service, encapsulates the Axis service, its receivers and our
  * receivers as well.
@@ -88,7 +89,11 @@
         _converter = new SoapMessageConverter(_wsdlDef, serviceName, portName);
 
     }
-
+    
+    public String getName() {
+    	return _axisService.getName();
+    }
+    
     public void onAxisMessageExchange(MessageContext msgContext, MessageContext outMsgContext, SOAPFactory soapFactory)
             throws AxisFault {
         boolean success = true;
@@ -103,7 +108,7 @@
             odeMex = _server.getEngine().createMessageExchange("" + messageId, _serviceName,
                     msgContext.getAxisOperation().getName().getLocalPart());
             __log.debug("ODE routed to operation " + odeMex.getOperation() + " from service " + _serviceName);
-            
+            odeMex.setProperty("isTwoWay", Boolean.toString(msgContext.getAxisOperation() instanceof TwoChannelAxisOperation));
             if (odeMex.getOperation() != null) {
                 // Preparing message to send to ODE
                 Message odeRequest = odeMex.createMessage(odeMex.getOperation().getInput().getMessage().getQName());
@@ -132,7 +137,11 @@
         } catch (Exception e) {
             __log.error("Exception occured while invoking ODE", e);
             success = false;
-            throw new OdeFault("An exception occured while invoking ODE.", e);
+            String message = e.getMessage();
+            if (message == null) {
+            	message = "An exception occured while invoking ODE.";
+            }
+            throw new OdeFault(message, e);
         } finally {
             if (!success) {
                 if (odeMex != null) odeMex.release(success);

Modified: ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/deploy/DeploymentPoller.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/deploy/DeploymentPoller.java?rev=761744&r1=761743&r2=761744&view=diff
==============================================================================
--- ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/deploy/DeploymentPoller.java (original)
+++ ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/deploy/DeploymentPoller.java Fri Apr  3 18:06:37 2009
@@ -114,38 +114,40 @@
         File[] files = _deployDir.listFiles(_fileFilter);
 
         // Checking for new deployment directories
-        for (File file : files) {
-            File deployXml = new File(file, "deploy.xml");
-            File deployedMarker = new File(_deployDir, file.getName() + ".deployed");
-
-            if (!deployXml.exists()) {
-                // Skip if deploy.xml is abset
-                __log.debug("Not deploying " + file + " (missing deploy.xml)");
-            }
-
-            if (deployedMarker.exists()) {
-                continue;
-            }
-
-            try {
-                deployedMarker.createNewFile();
-            } catch (IOException e1) {
-                __log.error("Error creating deployed marker file, " + file + " will not be deployed");
-                continue;
-            }
-
-            try {
-                _odeServer.getProcessStore().undeploy(file);
-            } catch (Exception ex) {
-                __log.error("Error undeploying " + file.getName());
-            }
-
-            try {
-                Collection<QName> deployed = _odeServer.getProcessStore().deploy(file);
-                __log.info("Deployment of artifact " + file.getName() + " successful: " + deployed );
-            } catch (Exception e) {
-                __log.error("Deployment of " + file.getName() + " failed, aborting for now.", e);
-            }
+        if (files != null) {
+	        for (File file : files) {
+	            File deployXml = new File(file, "deploy.xml");
+	            File deployedMarker = new File(_deployDir, file.getName() + ".deployed");
+	
+	            if (!deployXml.exists()) {
+	                // Skip if deploy.xml is abset
+	                __log.debug("Not deploying " + file + " (missing deploy.xml)");
+	            }
+	
+	            if (deployedMarker.exists()) {
+	                continue;
+	            }
+	
+	            try {
+	                deployedMarker.createNewFile();
+	            } catch (IOException e1) {
+	                __log.error("Error creating deployed marker file, " + file + " will not be deployed");
+	                continue;
+	            }
+	
+	            try {
+	                _odeServer.getProcessStore().undeploy(file);
+	            } catch (Exception ex) {
+	                __log.error("Error undeploying " + file.getName());
+	            }
+	
+	            try {
+	                Collection<QName> deployed = _odeServer.getProcessStore().deploy(file);
+	                __log.info("Deployment of artifact " + file.getName() + " successful: " + deployed );
+	            } catch (Exception e) {
+	                __log.error("Deployment of " + file.getName() + " failed, aborting for now.", e);
+	            }
+	        }
         }
 
         // Removing deployments that disappeared

Modified: ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/util/SoapMessageConverter.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/util/SoapMessageConverter.java?rev=761744&r1=761743&r2=761744&view=diff
==============================================================================
--- ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/util/SoapMessageConverter.java (original)
+++ ode/branches/APACHE_ODE_1.X/axis2/src/main/java/org/apache/ode/axis2/util/SoapMessageConverter.java Fri Apr  3 18:06:37 2009
@@ -273,6 +273,9 @@
     private OMElement buildSoapDetail(Element message, QName faultName, Operation op) throws AxisFault {
         if (faultName.getNamespaceURI() == null)
             return toFaultDetail(faultName, message);
+        if (op == null) {
+            return toFaultDetail(faultName, message);
+        }
         Fault f = op.getFault(faultName.getLocalPart());
         if (f == null)
             return toFaultDetail(faultName, message);

Modified: ode/branches/APACHE_ODE_1.X/bpel-api/src/main/java/org/apache/ode/bpel/iapi/BindingContext.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/bpel-api/src/main/java/org/apache/ode/bpel/iapi/BindingContext.java?rev=761744&r1=761743&r2=761744&view=diff
==============================================================================
--- ode/branches/APACHE_ODE_1.X/bpel-api/src/main/java/org/apache/ode/bpel/iapi/BindingContext.java (original)
+++ ode/branches/APACHE_ODE_1.X/bpel-api/src/main/java/org/apache/ode/bpel/iapi/BindingContext.java Fri Apr  3 18:06:37 2009
@@ -82,6 +82,12 @@
     PartnerRoleChannel createPartnerRoleChannel(QName processId, PortType portType,
             Endpoint initialPartnerEndpoint);
     
+    /**
+     * Calculate the size of the service that this endpoint references.
+     * @param epr the endpoint reference for the service
+     * @returns the size of the service
+     */
+    long calculateSizeofService(EndpointReference epr);
     
     
 }

Modified: ode/branches/APACHE_ODE_1.X/bpel-api/src/main/java/org/apache/ode/bpel/iapi/BpelEngine.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/bpel-api/src/main/java/org/apache/ode/bpel/iapi/BpelEngine.java?rev=761744&r1=761743&r2=761744&view=diff
==============================================================================
--- ode/branches/APACHE_ODE_1.X/bpel-api/src/main/java/org/apache/ode/bpel/iapi/BpelEngine.java (original)
+++ ode/branches/APACHE_ODE_1.X/bpel-api/src/main/java/org/apache/ode/bpel/iapi/BpelEngine.java Fri Apr  3 18:06:37 2009
@@ -41,6 +41,8 @@
      *            the service id of the process being called, if known
      * @param operation
      *            name of the operation
+     * @param style
+     * 			  style of the operation
      * 
      * @return {@link MyRoleMessageExchange} the newly created message exchange
      */
@@ -56,4 +58,14 @@
      */
     MessageExchange getMessageExchange(String mexId);
 
+	int getProcessThrottledMaximumCount();
+	
+	long getProcessThrottledMaximumSize();
+	
+	int getHydratedProcessCount(QName processName);
+
+	long getHydratedProcessSize(QName processName);
+
+	boolean dehydrateLastUnusedProcess();
+
 }

Modified: ode/branches/APACHE_ODE_1.X/bpel-api/src/main/java/org/apache/ode/bpel/iapi/ProcessConf.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/bpel-api/src/main/java/org/apache/ode/bpel/iapi/ProcessConf.java?rev=761744&r1=761743&r2=761744&view=diff
==============================================================================
--- ode/branches/APACHE_ODE_1.X/bpel-api/src/main/java/org/apache/ode/bpel/iapi/ProcessConf.java (original)
+++ ode/branches/APACHE_ODE_1.X/bpel-api/src/main/java/org/apache/ode/bpel/iapi/ProcessConf.java Fri Apr  3 18:06:37 2009
@@ -73,6 +73,12 @@
     InputStream getCBPInputStream();
    
     /**
+     * Get the CBP file size. 
+     * @return size of the CBP file.
+     */
+    long getCBPFileSize();
+    
+    /**
      * Get the path of the BPEL document, relative to its deployment unit 
      * @return Relative path of BPEL document
      */

Modified: ode/branches/APACHE_ODE_1.X/bpel-compiler/src/main/java/org/apache/ode/bpel/compiler/BpelCompiler.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/bpel-compiler/src/main/java/org/apache/ode/bpel/compiler/BpelCompiler.java?rev=761744&r1=761743&r2=761744&view=diff
==============================================================================
--- ode/branches/APACHE_ODE_1.X/bpel-compiler/src/main/java/org/apache/ode/bpel/compiler/BpelCompiler.java (original)
+++ ode/branches/APACHE_ODE_1.X/bpel-compiler/src/main/java/org/apache/ode/bpel/compiler/BpelCompiler.java Fri Apr  3 18:06:37 2009
@@ -111,15 +111,16 @@
 import org.apache.ode.bpel.o.OXslSheet;
 import org.apache.ode.utils.GUID;
 import org.apache.ode.utils.NSContext;
+import org.apache.ode.utils.Namespaces;
 import org.apache.ode.utils.StreamUtils;
 import org.apache.ode.utils.fs.FileUtils;
 import org.apache.ode.utils.msg.MessageBundle;
 import org.apache.ode.utils.stl.CollectionsX;
 import org.apache.ode.utils.stl.MemberOfFunction;
 import org.apache.ode.utils.stl.UnaryFunction;
+import org.apache.ode.utils.xsd.SchemaModel;
 import org.apache.ode.utils.xsd.XSUtils;
 import org.apache.ode.utils.xsd.XsdException;
-import org.apache.ode.utils.xsd.SchemaModel;
 import org.apache.xerces.xni.parser.XMLEntityResolver;
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
@@ -767,8 +768,18 @@
         constants.qnForEachCounterError = new QName(getBpwsNamespace(), "forEachCounterError");
         constants.qnInvalidBranchCondition = new QName(getBpwsNamespace(), "invalidBranchCondition");
         constants.qnInvalidExpressionValue = new QName(getBpwsNamespace(), "invalidExpressionValue");
+
+        constants.qnRetiredProcess = new QName(getOdeNamespace(), "retiredProcess");
+        constants.qnTooManyInstances = new QName(getOdeNamespace(), "tooManyInstances");
+        constants.qnUnknownFault = new QName(getOdeNamespace(), "unknownFault");
+        constants.qnTooManyProcesses = new QName(getOdeNamespace(), "tooManyProcesses");
+        constants.qnTooHugeProcesses = new QName(getOdeNamespace(), "tooHugeProcesses");
         return constants;
     }
+    
+    private String getOdeNamespace() {
+    	return Namespaces.ODE_EXTENSION_NS;
+    }
 
     // TODO unused?
     // private String getBpelPartnerLinkUri(){

Modified: ode/branches/APACHE_ODE_1.X/bpel-epr/src/main/java/org/apache/ode/bpel/epr/EndpointFactory.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/bpel-epr/src/main/java/org/apache/ode/bpel/epr/EndpointFactory.java?rev=761744&r1=761743&r2=761744&view=diff
==============================================================================
--- ode/branches/APACHE_ODE_1.X/bpel-epr/src/main/java/org/apache/ode/bpel/epr/EndpointFactory.java (original)
+++ ode/branches/APACHE_ODE_1.X/bpel-epr/src/main/java/org/apache/ode/bpel/epr/EndpointFactory.java Fri Apr  3 18:06:37 2009
@@ -19,6 +19,7 @@
 
 package org.apache.ode.bpel.epr;
 
+import java.util.List;
 import java.util.Map;
 
 import javax.xml.namespace.QName;
@@ -123,5 +124,4 @@
         
         return new WSAEndpoint(source.toMap());
     }
-
 }

Modified: ode/branches/APACHE_ODE_1.X/bpel-epr/src/main/java/org/apache/ode/il/config/OdeConfigProperties.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/bpel-epr/src/main/java/org/apache/ode/il/config/OdeConfigProperties.java?rev=761744&r1=761743&r2=761744&view=diff
==============================================================================
--- ode/branches/APACHE_ODE_1.X/bpel-epr/src/main/java/org/apache/ode/il/config/OdeConfigProperties.java (original)
+++ ode/branches/APACHE_ODE_1.X/bpel-epr/src/main/java/org/apache/ode/il/config/OdeConfigProperties.java Fri Apr  3 18:06:37 2009
@@ -19,16 +19,16 @@
 
 package org.apache.ode.il.config;
 
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.ode.utils.SystemUtils;
-
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.util.Properties;
 
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ode.utils.SystemUtils;
+
 /**
  * Configuration object used for configuring the intergration layer. The propereties are those likely to be common to all layers.
  *
@@ -83,7 +83,15 @@
     
     public static final String PROP_PROCESS_DEHYDRATION_MAXIMUM_COUNT = "process.dehydration.maximum.count";
     
-    public static final String PROP_PROCESS_HYDRATION = "process.hydration";
+    public static final String PROP_PROCESS_HYDRATION_LAZY = "process.hydration.lazy";
+    
+    public static final String PROP_PROCESS_HYDRATION_LAZY_MINIMUM_SIZE = "process.hydration.lazy.minimum.size";
+    
+    public static final String PROP_PROCESS_HYDRATION_THROTTLED_MAXIMUM_COUNT = "process.hydration.throttled.maximum.count";
+    
+    public static final String PROP_PROCESS_HYDRATION_THROTTLED_MAXIMUM_SIZE = "process.hydration.throttled.maximum.size";
+    
+    public static final String PROP_PROCESS_INSTANCE_THROTTLED_MAXIMUM_COUNT = "process.instance.throttled.maximum.count";
     
     public static final String PROP_DAOCF = "dao.factory";
     
@@ -258,7 +266,27 @@
     }
     
     public boolean isHydrationLazy() {
-        return "lazy".equals(getProperty(OdeConfigProperties.PROP_PROCESS_HYDRATION, "eager"));
+        return Boolean.valueOf(getProperty(OdeConfigProperties.PROP_PROCESS_HYDRATION_LAZY, "true"));
+    }
+    
+    public int getHydrationLazyMinimumSize() {
+        return Integer.valueOf(getProperty(OdeConfigProperties.PROP_PROCESS_HYDRATION_LAZY_MINIMUM_SIZE, String.valueOf(0)));
+    }
+    
+    public int getProcessThrottledMaximumCount() {
+        return Integer.valueOf(getProperty(OdeConfigProperties.PROP_PROCESS_HYDRATION_THROTTLED_MAXIMUM_COUNT, String.valueOf(Integer.MAX_VALUE)));
+    }
+    
+    public int getInstanceThrottledMaximumCount() {
+        return Integer.valueOf(getProperty(OdeConfigProperties.PROP_PROCESS_INSTANCE_THROTTLED_MAXIMUM_COUNT, String.valueOf(Integer.MAX_VALUE)));
+    }
+    
+    public long getProcessThrottledMaximumSize() {
+        return Long.valueOf(getProperty(OdeConfigProperties.PROP_PROCESS_HYDRATION_THROTTLED_MAXIMUM_SIZE, String.valueOf(Long.MAX_VALUE)));
+    }
+    
+    public boolean isProcessSizeThrottled() {
+        return getProcessThrottledMaximumSize() == Long.MAX_VALUE;
     }
     
     public boolean isDbLoggingEnabled() {

Modified: ode/branches/APACHE_ODE_1.X/bpel-obj/src/main/java/org/apache/ode/bpel/o/OConstants.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/bpel-obj/src/main/java/org/apache/ode/bpel/o/OConstants.java?rev=761744&r1=761743&r2=761744&view=diff
==============================================================================
--- ode/branches/APACHE_ODE_1.X/bpel-obj/src/main/java/org/apache/ode/bpel/o/OConstants.java (original)
+++ ode/branches/APACHE_ODE_1.X/bpel-obj/src/main/java/org/apache/ode/bpel/o/OConstants.java Fri Apr  3 18:06:37 2009
@@ -43,6 +43,12 @@
     public QName qnInvalidBranchCondition;
     public QName qnInvalidExpressionValue;
 
+    // non-standard fault names
+    public QName qnRetiredProcess;
+    public QName qnTooManyInstances;
+    public QName qnTooManyProcesses;
+    public QName qnTooHugeProcesses;
+    public QName qnUnknownFault;
 
     public OConstants(OProcess owner) {
         super(owner);

Modified: ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/BpelEngineImpl.java
URL: http://svn.apache.org/viewvc/ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/BpelEngineImpl.java?rev=761744&r1=761743&r2=761744&view=diff
==============================================================================
--- ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/BpelEngineImpl.java (original)
+++ ode/branches/APACHE_ODE_1.X/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/BpelEngineImpl.java Fri Apr  3 18:06:37 2009
@@ -47,14 +47,24 @@
 import org.apache.ode.bpel.iapi.MyRoleMessageExchange;
 import org.apache.ode.bpel.iapi.PartnerRoleMessageExchange;
 import org.apache.ode.bpel.iapi.Scheduler;
+import org.apache.ode.bpel.iapi.MessageExchange.FailureType;
 import org.apache.ode.bpel.iapi.MessageExchange.MessageExchangePattern;
 import org.apache.ode.bpel.iapi.MessageExchange.Status;
 import org.apache.ode.bpel.iapi.MyRoleMessageExchange.CorrelationStatus;
 import org.apache.ode.bpel.iapi.Scheduler.JobInfo;
+import org.apache.ode.bpel.intercept.InterceptorInvoker;
 import org.apache.ode.bpel.intercept.MessageExchangeInterceptor;
+import org.apache.ode.bpel.intercept.ProcessCountThrottler;
+import org.apache.ode.bpel.intercept.ProcessSizeThrottler;
+import org.apache.ode.bpel.o.OConstants;
 import org.apache.ode.bpel.o.OPartnerLink;
 import org.apache.ode.bpel.o.OProcess;
+import org.apache.ode.bpel.runtime.InvalidProcessException;
+import org.apache.ode.utils.DOMUtils;
+import org.apache.ode.utils.Namespaces;
 import org.apache.ode.utils.msg.MessageBundle;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
 
 /**
  * Implementation of the {@link BpelEngine} interface: provides the server methods that should be invoked in the context of a
@@ -89,6 +99,8 @@
 
     private static final Messages __msgs = MessageBundle.getMessages(Messages.class);
 
+	private static final double PROCESS_OVERHEAD_MEMORY_FACTOR = 1.2;
+
     /** Active processes, keyed by process id. */
     final HashMap<QName, BpelProcess> _activeProcesses = new HashMap<QName, BpelProcess>();
 
@@ -103,6 +115,9 @@
 
     final Contexts _contexts;
 
+    private final Map<QName, Long> _hydratedSizes = new HashMap<QName, Long>();
+    private final Map<QName, Long> _unhydratedSizes = new HashMap<QName, Long>();
+    
     public BpelEngineImpl(Contexts contexts) {
         _contexts = contexts;
         _sharedEps = new SharedEndpoints();
@@ -181,7 +196,14 @@
         return createMessageExchange(clientKey, targetService, operation, null);        
     }
 
-    public MessageExchange getMessageExchange(String mexId) throws BpelEngineException {
+    private void setMessageExchangeProcess(String mexId, ProcessDAO processDao) {
+        MessageExchangeDAO mexdao = _contexts.inMemDao.getConnection().getMessageExchange(mexId);
+        if (mexdao == null) mexdao = _contexts.dao.getConnection().getMessageExchange(mexId);
+        if (mexdao != null)
+	        mexdao.setProcess(processDao);
+    }
+    
+    public MessageExchange getMessageExchange(String mexId) {
         MessageExchangeDAO mexdao = _contexts.inMemDao.getConnection().getMessageExchange(mexId);
         if (mexdao == null) mexdao = _contexts.dao.getConnection().getMessageExchange(mexId);
         if (mexdao == null)
@@ -212,9 +234,12 @@
             mex = new MyRoleMessageExchangeImpl(process, this, mexdao);
             if (process != null) {
                 OPartnerLink plink = (OPartnerLink) process.getOProcess().getChild(mexdao.getPartnerLinkModelId());
-                PortType ptype = plink.myRolePortType;
-                Operation op = plink.getMyRoleOperation(mexdao.getOperation());
-                mex.setPortOp(ptype, op);
+                // the partner link might not be hydrated
+                if (plink != null) {
+	                PortType ptype = plink.myRolePortType;
+	                Operation op = plink.getMyRoleOperation(mexdao.getOperation());
+	                mex.setPortOp(ptype, op);
+                }
             }
             break;
         default:
@@ -256,6 +281,8 @@
             p.deactivate();            
             // release the resources held by this process
             p.dehydrate();
+            // update the process footprints list
+        	_hydratedSizes.remove(p.getPID());
         }
         return p;
     }
@@ -264,7 +291,7 @@
         return _activeProcesses.containsKey(pid);
     }
     
-    BpelProcess getProcess(QName pid) {
+    public BpelProcess getProcess(QName pid) {
     	return _activeProcesses.get(pid);
     }
 
@@ -295,7 +322,7 @@
         }
         process.activate(this);
     }
-
+    
     /**
      * Route to a process using the service id. Note, that we do not need the endpoint name here, we are assuming that two processes
      * would not be registered under the same service qname but different endpoint.
@@ -332,7 +359,7 @@
         final WorkEvent we = new WorkEvent(jobInfo.jobDetail);
 
     	if( __log.isTraceEnabled() ) __log.trace("[JOB] onScheduledJob " + jobInfo + "" + we.getIID());
-
+    	
     	// We lock the instance to prevent concurrent transactions and prevent unnecessary rollbacks,
         // Note that we don't want to wait too long here to get our lock, since we are likely holding
         // on to scheduler's locks of various sorts.
@@ -359,8 +386,8 @@
         // all types of failure here, the scheduler is not going to know how to handle our errors,
         // ALSO we have to release the lock obtained above (IMPORTANT), lest the whole system come
         // to a grinding halt.
+        BpelProcess process = null;
         try {
-            BpelProcess process;
             if (we.getProcessId() != null) {
                 process = _activeProcesses.get(we.getProcessId());
             } else {
@@ -384,16 +411,29 @@
                 return;
             }
 
+            
             if (we.getType().equals(WorkEvent.Type.INVOKE_CHECK)) {
                 if (__log.isDebugEnabled()) __log.debug("handleWorkEvent: InvokeCheck event for mexid " + we.getMexId());
+                
+                sendPartnerRoleFailure(we, MessageExchange.FailureType.COMMUNICATION_ERROR);
+                return;
+            } else if (we.getType().equals(WorkEvent.Type.INVOKE_INTERNAL)) {
+                if (__log.isDebugEnabled()) __log.debug("handleWorkEvent: InvokeInternal event for mexid " + we.getMexId());
 
-                PartnerRoleMessageExchange mex = (PartnerRoleMessageExchange) getMessageExchange(we.getMexId());
-                if (mex.getStatus() == MessageExchange.Status.ASYNC || mex.getStatus() == MessageExchange.Status.REQUEST) {
-                    String msg = "Dangling invocation (mexId=" + we.getMexId() + "), forcing it into a failed state.";
-                    if (__log.isDebugEnabled()) __log.debug(msg);
-                    mex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, msg, null);
+                setMessageExchangeProcess(we.getMexId(), process.getProcessDAO());
+                MyRoleMessageExchangeImpl mex = (MyRoleMessageExchangeImpl) getMessageExchange(we.getMexId());
+                if (!process.processInterceptors(mex, InterceptorInvoker.__onJobScheduled)) {
+                    boolean isTwoWay = Boolean.valueOf(mex.getProperty("isTwoWay"));
+                    if (isTwoWay) {
+                        String causeCodeValue = mex.getProperty("causeCode");
+                        mex.getDAO().setProcess(process.getProcessDAO());
+                    	sendMyRoleFault(process, we, causeCodeValue != null ? 
+                    			Integer.valueOf(causeCodeValue) : InvalidProcessException.DEFAULT_CAUSE_CODE);
+                    	return;
+                    } else {
+                        throw new Scheduler.JobProcessorException(checkRetry(jobInfo, null));
+                    }
                 }
-                return;
             }
 
             process.handleWorkEvent(jobInfo.jobDetail);
@@ -404,13 +444,15 @@
         } catch (ContextException ce) {
             __log.error(__msgs.msgScheduledJobFailed(we.getDetail()), ce);
             throw new Scheduler.JobProcessorException(ce, checkRetry(jobInfo, ce));
+        } catch (InvalidProcessException ipe) {
+            __log.error(__msgs.msgScheduledJobFailed(we.getDetail()), ipe);
+            sendMyRoleFault(process, we, ipe.getCauseCode());
         } catch (RuntimeException rte) {
             __log.error(__msgs.msgScheduledJobFailed(we.getDetail()), rte);
             throw new Scheduler.JobProcessorException(rte, checkRetry(jobInfo, rte));
         } catch (Throwable t) {
             __log.error(__msgs.msgScheduledJobFailed(we.getDetail()), t);
             throw new Scheduler.JobProcessorException(false);
-
         }
     }
 
@@ -458,7 +500,231 @@
      * @return list
      */
     List<MessageExchangeInterceptor> getGlobalInterceptors() {
-        return _contexts.globalIntereceptors;
+        return _contexts.globalInterceptors;
     }
 
+	
+    public void registerMessageExchangeInterceptor(MessageExchangeInterceptor interceptor) {
+    	_contexts.globalInterceptors.add(interceptor);
+    }
+    
+    public void unregisterMessageExchangeInterceptor(MessageExchangeInterceptor interceptor) {
+    	_contexts.globalInterceptors.remove(interceptor);
+    }
+    
+    public void unregisterMessageExchangeInterceptor(Class interceptorClass) {
+    	MessageExchangeInterceptor candidate = null;
+    	for (MessageExchangeInterceptor interceptor : _contexts.globalInterceptors) {
+    		if (interceptor.getClass().isAssignableFrom(interceptorClass)) {
+    			candidate = interceptor;
+    			break;
+    		}
+    	}
+    	if (candidate != null) {
+    		_contexts.globalInterceptors.remove(candidate);
+    	}
+    }
+    
+	public long getTotalBpelFootprint() {
+		long bpelFootprint = 0;
+		for (BpelProcess process : _activeProcesses.values()) {
+			Long size = _hydratedSizes.get(process.getPID());
+			if (size == null) {
+				size = _unhydratedSizes.get(process.getPID());
+			}
+			if (size != null && size.longValue() > 0) {
+				bpelFootprint += size;
+			}
+		}
+		return bpelFootprint;
+	}
+
+	public long getHydratedFootprint() {
+		long hydratedFootprint = 0;
+		for (BpelProcess process : _activeProcesses.values()) {
+			if (!process.hintIsHydrated()) {
+				continue;
+			}
+			Long size = _hydratedSizes.get(process.getPID());
+			if (size == null) {
+				size = _unhydratedSizes.get(process.getPID());
+			}
+			if (size != null && size.longValue() > 0) {
+				hydratedFootprint += size;
+			}
+		}
+		return hydratedFootprint;
+	}
+	
+	public long getHydratedProcessSize(QName processName) {
+		return getHydratedProcessSize(_activeProcesses.get(processName));
+	}
+	
+	private long getHydratedProcessSize(BpelProcess process) {		
+		long potentialGrowth = 0;
+		if (!process.hintIsHydrated()) {
+			Long mySize = _hydratedSizes.get(process.getPID());
+			if (mySize == null) {
+				mySize = _unhydratedSizes.get(process.getPID());
+			}
+			if (mySize != null && mySize.longValue() > 0) {
+				potentialGrowth = mySize.longValue();
+			}
+		}
+		return getHydratedProcessSize(potentialGrowth);
+	}
+	
+	private long getHydratedProcessSize(long potentialGrowth) {
+		long processMemory = (long) 
+			((getHydratedFootprint() + potentialGrowth) *
+					PROCESS_OVERHEAD_MEMORY_FACTOR);
+		return processMemory;	
+	}	
+
+	public int getHydratedProcessCount(QName processName) {
+		int processCount = 0;
+		for (BpelProcess process : _activeProcesses.values()) {
+			if (process.hintIsHydrated() || process.getPID().equals(processName)) {
+				processCount++;
+			}
+		}		
+		return processCount;
+	}	
+
+	private long _processThrottledMaximumSize = Long.MAX_VALUE;
+	private int _processThrottledMaximumCount = Integer.MAX_VALUE;
+	private int _instanceThrottledMaximumCount = Integer.MAX_VALUE;
+	private boolean _hydrationThrottled = false;
+
+	public void setInstanceThrottledMaximumCount(
+			int instanceThrottledMaximumCount) {
+		this._instanceThrottledMaximumCount = instanceThrottledMaximumCount;
+	}
+	
+	public int getInstanceThrottledMaximumCount() {
+		return _instanceThrottledMaximumCount;
+	}
+	
+	public void setProcessThrottledMaximumCount(
+			int hydrationThrottledMaximumCount) {
+		this._processThrottledMaximumCount = hydrationThrottledMaximumCount;
+        if (hydrationThrottledMaximumCount < Integer.MAX_VALUE) {
+	        registerMessageExchangeInterceptor(new ProcessCountThrottler());
+        } else {
+        	unregisterMessageExchangeInterceptor(ProcessCountThrottler.class);
+        }
+	}
+	
+	public int getProcessThrottledMaximumCount() {
+		return _processThrottledMaximumCount;
+	}
+
+	public void setProcessThrottledMaximumSize(
+			long hydrationThrottledMaximumSize) {
+		this._processThrottledMaximumSize = hydrationThrottledMaximumSize;
+        if (hydrationThrottledMaximumSize < Long.MAX_VALUE) {
+	        registerMessageExchangeInterceptor(new ProcessSizeThrottler());
+        } else {
+        	unregisterMessageExchangeInterceptor(ProcessSizeThrottler.class);
+        }
+	}
+
+	public long getProcessThrottledMaximumSize() {
+		return _processThrottledMaximumSize;
+	}
+	
+	public void setProcessSize(QName processId, boolean hydratedOnce) {
+		BpelProcess process = _activeProcesses.get(processId);
+		long processSize = process.sizeOf();
+		if (hydratedOnce) {
+            _hydratedSizes.put(process.getPID(), new Long(processSize));
+            _unhydratedSizes.remove(process.getPID());
+		} else {
+			_hydratedSizes.remove(process.getPID());
+            _unhydratedSizes.put(process.getPID(), new Long(processSize));			
+		}
+	}
+
+	/**
+	 * Returns true if the last used process was dehydrated because it was not in-use.
+	 */
+	public boolean dehydrateLastUnusedProcess() {
+		BpelProcess lastUnusedProcess = null;
+		long lastUsedMinimum = Long.MAX_VALUE;
+		for (BpelProcess process : _activeProcesses.values()) {
+			if (process.hintIsHydrated() 
+					&& process.getLastUsed() < lastUsedMinimum 
+					&& process.getInstanceInUseCount() == 0) {
+				lastUsedMinimum = process.getLastUsed();
+				lastUnusedProcess = process;
+			}
+		}
+		if (lastUnusedProcess != null) {
+			lastUnusedProcess.dehydrate();
+			return true;
+		}
+		return false;
+	}
+
+	public void sendMyRoleFault(BpelProcess process, WorkEvent we, int causeCode) {
+		MessageExchange mex = (MessageExchange) getMessageExchange(we.getMexId());
+        if (!(mex instanceof MyRoleMessageExchange)) {
+        	return;
+        }
+        QName faultQName = null;
+        OConstants constants = process.getOProcess().constants;
+        if (constants != null) {
+            Document document = DOMUtils.newDocument();
+            Element faultElement = document.createElementNS(Namespaces.SOAP_ENV_NS, "Fault");
+            Element faultDetail = document.createElementNS(Namespaces.ODE_EXTENSION_NS, "fault");
+            faultElement.appendChild(faultDetail);
+            switch (causeCode) {
+            case InvalidProcessException.TOO_MANY_PROCESSES_CAUSE_CODE:
+                faultQName = constants.qnTooManyProcesses;
+                faultDetail.setTextContent("The total number of processes in use is over the limit.");
+                break;
+            case InvalidProcessException.TOO_HUGE_PROCESSES_CAUSE_CODE:
+                faultQName = constants.qnTooHugeProcesses;
+                faultDetail.setTextContent("The total size of processes in use is over the limit");
+                break;
+            case InvalidProcessException.TOO_MANY_INSTANCES_CAUSE_CODE:
+                faultQName = constants.qnTooManyInstances;
+                faultDetail.setTextContent("No more instances of the process allowed at start at this time.");
+                break;
+            case InvalidProcessException.RETIRED_CAUSE_CODE:
+                // we're invoking a target process, trying to see if we can retarget the message
+                // to the current version (only applies when it's a new process creation)
+                for (BpelProcess activeProcess : _activeProcesses.values()) {
+                    if (activeProcess.getConf().getState().equals(org.apache.ode.bpel.iapi.ProcessState.ACTIVE)
+                            && activeProcess.getConf().getType().equals(process.getConf().getType())) {
+                        we.setProcessId(activeProcess._pid);
+                        ((MyRoleMessageExchangeImpl) mex)._process = activeProcess;
+                        process.handleWorkEvent(we.getDetail());
+                        return;
+                    }
+                }
+                faultQName = constants.qnRetiredProcess;
+                faultDetail.setTextContent("The process you're trying to instantiate has been retired.");
+                break;
+            case InvalidProcessException.DEFAULT_CAUSE_CODE:
+            default:
+                faultQName = constants.qnUnknownFault;
+                break;
+            }
+            MexDaoUtil.setFaulted((MessageExchangeImpl) mex, faultQName, faultElement);
+        }
+	}
+	
+	private void sendPartnerRoleFailure(WorkEvent we, FailureType failureType) {
+        MessageExchange mex = (MessageExchange) getMessageExchange(we.getMexId());
+		if (mex instanceof PartnerRoleMessageExchange) {
+	        if (mex.getStatus() == MessageExchange.Status.ASYNC || mex.getStatus() == MessageExchange.Status.REQUEST) {
+	            String msg = "Dangling invocation (mexId=" + we.getMexId() + "), forcing it into a failed state.";
+	            if (__log.isDebugEnabled()) __log.debug(msg);
+				MexDaoUtil.setFailure((PartnerRoleMessageExchangeImpl) mex, failureType, msg, null);
+	        }
+		}
+	}
+
 }
+