[jbpm-commits] JBoss JBPM SVN: r3664 - in jbpm3/trunk: modules/core/src/main/java/org/jbpm and 26 other directories.
do-not-reply at jboss.org
do-not-reply at jboss.org
Fri Jan 16 13:23:36 EST 2009
Author: alex.guizar at jboss.com
Date: 2009-01-16 13:23:36 -0500 (Fri, 16 Jan 2009)
New Revision: 3664
Added:
jbpm3/trunk/modules/core/src/main/java/org/jbpm/util/CollectionUtil.java
Modified:
jbpm3/trunk/modules/core/src/main/java/org/jbpm/JbpmConfiguration.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/JbpmContext.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/ant/JbpmSchemaTask.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/calendar/BusinessCalendar.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/command/AbstractBaseCommand.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/command/AbstractProcessInstanceBaseCommand.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/command/GetTaskListCommand.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/command/StartProcessInstanceCommand.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/context/exe/ContextInstance.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/context/exe/TokenVariableMap.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/context/exe/VariableContainer.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/GraphSession.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/JbpmSchema.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/JobSession.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/LoggingSession.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/TaskMgmtSession.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/compatibility/JbpmSchemaUpdate.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/action/ActionTypes.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/action/Script.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/Action.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/Event.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/ExceptionHandler.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/GraphElement.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/Node.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/NodeCollection.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/ProcessDefinition.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/SuperState.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/Transition.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/exe/Execution.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/exe/ExecutionContext.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/exe/ProcessInstance.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/exe/Token.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/Decision.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/Fork.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/InterleaveEnd.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/InterleaveStart.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/Join.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/Merge.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/NodeTypes.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/ProcessFactory.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/ProcessState.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/StartState.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/TaskNode.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/instantiation/BeanInstantiator.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/job/executor/JobExecutor.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/job/executor/JobExecutorServlet.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/job/executor/JobExecutorThread.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/job/executor/LockMonitorThread.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/jpdl/xml/JpdlXmlReader.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/svc/Services.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/taskmgmt/def/TaskMgmtDefinition.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/taskmgmt/exe/TaskMgmtInstance.java
jbpm3/trunk/modules/core/src/main/java/org/jbpm/util/ClassLoaderUtil.java
jbpm3/trunk/modules/core/src/main/resources/org/jbpm/db/hibernate.queries.hbm.xml
jbpm3/trunk/modules/core/src/test/java/org/jbpm/JbpmConfigurationTest.java
jbpm3/trunk/modules/core/src/test/java/org/jbpm/JbpmContextTest.java
jbpm3/trunk/modules/core/src/test/java/org/jbpm/SerializabilityTest.java
jbpm3/trunk/modules/core/src/test/java/org/jbpm/jbpm1778/JBPM1778Test.java
jbpm3/trunk/modules/db/src/main/resources/hibernate.extra.hbm.xml
jbpm3/trunk/modules/enterprise/src/main/java/org/jbpm/ejb/impl/TimerEntityBean.java
jbpm3/trunk/modules/examples/src/test/java/org/jbpm/examples/assignment/RulesAssignmentTest.java
jbpm3/trunk/modules/examples/src/test/java/org/jbpm/examples/rulesaction/RulesActionTest.java
jbpm3/trunk/modules/identity/src/main/java/org/jbpm/identity/Membership.java
jbpm3/trunk/modules/simulation/src/test/java/org/jbpm/sim/BusinessFiguresTest.java
jbpm3/trunk/pom.xml
Log:
JBPM-1975 generalize core module
many small fixes
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/JbpmConfiguration.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/JbpmConfiguration.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/JbpmConfiguration.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -24,10 +24,11 @@
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Serializable;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
-import java.util.Stack;
+import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -254,13 +255,20 @@
private static final long serialVersionUID = 1L;
static ObjectFactory defaultObjectFactory;
- static Map instances = new HashMap();
- static ThreadLocal jbpmConfigurationsStacks = new ThreadLocal();
+ static Map<String, JbpmConfiguration> instances = new HashMap<String, JbpmConfiguration>();
+ static ThreadLocal<List<JbpmConfiguration>> jbpmConfigurationsStacks = new ListThreadLocal<JbpmConfiguration>();
private ObjectFactory objectFactory;
- private ThreadLocal jbpmContextStacks = new ThreadLocal();
private JobExecutor jobExecutor;
+ private ThreadLocal<List<JbpmContext>> jbpmContextStacks = new ListThreadLocal<JbpmContext>();
+ static class ListThreadLocal<E> extends ThreadLocal<List<E>> {
+ @Override
+ protected List<E> initialValue() {
+ return new ArrayList<E>();
+ }
+ }
+
public JbpmConfiguration(ObjectFactory objectFactory)
{
this.objectFactory = objectFactory;
@@ -273,14 +281,14 @@
public static JbpmConfiguration getInstance(String resource)
{
+ if (resource == null)
+ {
+ resource = "jbpm.cfg.xml";
+ }
JbpmConfiguration instance = null;
synchronized (instances)
{
- if (resource == null)
- {
- resource = "jbpm.cfg.xml";
- }
- instance = (JbpmConfiguration) instances.get(resource);
+ instance = instances.get(resource);
if (instance == null)
{
if (defaultObjectFactory != null)
@@ -295,7 +303,7 @@
log.info("using jbpm configuration resource '" + resource + "'");
InputStream jbpmCfgXmlStream = ClassLoaderUtil.getJbpmConfigurationStream(resource);
/*
- * if a custom resource is to be used, but is not found in the classpath log a warning
+ * if a custom resource is specified, but not found in the classpath log a warning
* (otherwise, users who want to load custom stuff will be confused if the resource is
* not found and not loaded, without any notice)
*/
@@ -314,7 +322,6 @@
instances.put(resource, instance);
}
}
-
return instance;
}
@@ -462,9 +469,14 @@
/**
* gives the jbpm domain model access to configuration information via the current JbpmContext.
*/
- public abstract static class Configs
+ public static class Configs
{
+ private Configs()
+ {
+ // hide default constructor to prevent instantiation
+ }
+
public static ObjectFactory getObjectFactory()
{
ObjectFactory objectFactory = null;
@@ -589,70 +601,66 @@
public void close(String jbpmContextName)
{
+ // stop job executor
+ if (jobExecutor != null)
+ {
+ jobExecutor.stop();
+ }
+
JbpmContext jbpmContext = createJbpmContext(jbpmContextName);
try
{
-
- synchronized (instances)
+ // close service factories
+ Map<String, ServiceFactory> serviceFactories = jbpmContext.getServices().getServiceFactories();
+ if (serviceFactories != null)
{
- Iterator iter = instances.values().iterator();
- while (iter.hasNext())
- {
- if (this == iter.next())
- {
- iter.remove();
- break;
- }
+ for (ServiceFactory serviceFactory : serviceFactories.values()) {
+ serviceFactory.close();
}
}
+ }
+ finally
+ {
+ jbpmContext.close();
+ }
- if (jobExecutor != null)
- {
- jobExecutor.stop();
- }
+ // release context stack
+ jbpmContextStacks.remove();
- Map serviceFactories = jbpmContext.getServices().getServiceFactories();
- if (serviceFactories != null)
+ // remove from configurations map
+ synchronized (instances)
+ {
+ Iterator<JbpmConfiguration> iter = instances.values().iterator();
+ while (iter.hasNext())
{
- Iterator iter = serviceFactories.values().iterator();
- while (iter.hasNext())
+ if (this == iter.next())
{
- ServiceFactory serviceFactory = (ServiceFactory) iter.next();
- serviceFactory.close();
+ iter.remove();
+ break;
}
}
}
- finally
- {
- jbpmContext.close();
- }
}
static JbpmConfiguration getCurrentJbpmConfiguration()
{
JbpmConfiguration currentJbpmConfiguration = null;
- Stack stack = getJbpmConfigurationStack();
+ List<JbpmConfiguration> stack = getJbpmConfigurationStack();
if (!stack.isEmpty())
{
- currentJbpmConfiguration = (JbpmConfiguration) stack.peek();
+ currentJbpmConfiguration = stack.get(stack.size() - 1);
}
return currentJbpmConfiguration;
}
- static synchronized Stack getJbpmConfigurationStack()
+ static List<JbpmConfiguration> getJbpmConfigurationStack()
{
- Stack stack = (Stack) jbpmConfigurationsStacks.get();
- if (stack == null)
- {
- stack = new Stack();
- jbpmConfigurationsStacks.set(stack);
- }
- return stack;
+ return jbpmConfigurationsStacks.get();
}
synchronized void pushJbpmConfiguration()
{
- getJbpmConfigurationStack().push(this);
+ getJbpmConfigurationStack().add(this);
}
synchronized void popJbpmConfiguration()
@@ -663,40 +671,35 @@
public JbpmContext getCurrentJbpmContext()
{
JbpmContext currentJbpmContext = null;
- Stack stack = getJbpmContextStack();
+ List<JbpmContext> stack = getJbpmContextStack();
if (!stack.isEmpty())
{
- currentJbpmContext = (JbpmContext) stack.peek();
+ currentJbpmContext = stack.get(stack.size() - 1);
}
return currentJbpmContext;
}
- Stack getJbpmContextStack()
+ List<JbpmContext> getJbpmContextStack()
{
- Stack stack = (Stack) jbpmContextStacks.get();
- if (stack == null)
- {
- stack = new Stack();
- jbpmContextStacks.set(stack);
- }
- return stack;
+ return jbpmContextStacks.get();
}
void pushJbpmContext(JbpmContext jbpmContext)
{
- getJbpmContextStack().push(jbpmContext);
+ getJbpmContextStack().add(jbpmContext);
}
void popJbpmContext(JbpmContext jbpmContext)
{
- Stack stack = getJbpmContextStack();
+ List<JbpmContext> stack = getJbpmContextStack();
if (stack.isEmpty())
{
throw new JbpmException("closed JbpmContext more than once... check your try-finally's around JbpmContexts blocks");
}
- JbpmContext popped = (JbpmContext) stack.pop();
+ JbpmContext popped = stack.remove(stack.size() - 1);
if (jbpmContext != popped)
{
+ stack.remove(jbpmContext); // prevent context from remaining in the stack
throw new JbpmException("closed JbpmContext in some order that differs from creation... check your try-finally's around JbpmContexts blocks");
}
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/JbpmContext.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/JbpmContext.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/JbpmContext.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -24,7 +24,6 @@
import java.io.Serializable;
import java.sql.Connection;
import java.util.ArrayList;
-import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
@@ -100,11 +99,9 @@
public static final String DEFAULT_JBPM_CONTEXT_NAME = "default.jbpm.context";
- static ThreadLocal currentContextsStack = new ThreadLocal();
-
ObjectFactory objectFactory = null;
Services services = null;
- List autoSaveProcessInstances = null;
+ List<ProcessInstance> autoSaveProcessInstances = null;
JbpmConfiguration jbpmConfiguration = null;
/**
@@ -177,7 +174,7 @@
* fetches the tasklist for the current authenticated actor. With the default configured authentication service, you can set the authenticated user with
* {@link #setActorId(String)}, then all the subsequent operations will be performed on behalf of that actor.
*/
- public List getTaskList()
+ public List<TaskInstance> getTaskList()
{
String actorId = getActorId();
return getTaskMgmtSession().findTaskInstances(actorId);
@@ -186,7 +183,7 @@
/**
* fetches the tasklist for the given actor.
*/
- public List getTaskList(String actorId)
+ public List<TaskInstance> getTaskList(String actorId)
{
return getTaskMgmtSession().findTaskInstances(actorId);
}
@@ -197,7 +194,7 @@
* actor's personal task list (with {@link TaskInstance#setActorId(String)}). Only task instances that are assigned to the actor directly should be offered the
* possibility for performing the actual task.
*/
- public List getGroupTaskList(List actorIds)
+ public List<TaskInstance> getGroupTaskList(List<String> actorIds)
{
return getTaskMgmtSession().findPooledTaskInstances(actorIds);
}
@@ -663,14 +660,14 @@
*/
public void setActorId(String actorId)
{
- AuthenticationService authenticationService = (AuthenticationService)services.getAuthenticationService();
+ AuthenticationService authenticationService = services.getAuthenticationService();
authenticationService.setActorId(actorId);
}
public void addAutoSaveProcessInstance(ProcessInstance processInstance)
{
if (autoSaveProcessInstances == null)
- autoSaveProcessInstances = new ArrayList();
+ autoSaveProcessInstances = new ArrayList<ProcessInstance>();
autoSaveProcessInstances.add(processInstance);
}
@@ -690,13 +687,10 @@
{
if (autoSaveProcessInstances != null)
{
- Iterator iter = autoSaveProcessInstances.iterator();
- while (iter.hasNext())
- {
- ProcessInstance processInstance = (ProcessInstance)iter.next();
+ for (ProcessInstance processInstance : autoSaveProcessInstances) {
save(processInstance);
- iter.remove();
}
+ autoSaveProcessInstances.clear();
}
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/ant/JbpmSchemaTask.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/ant/JbpmSchemaTask.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/ant/JbpmSchemaTask.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -21,119 +21,93 @@
*/
package org.jbpm.ant;
-import java.io.FileOutputStream;
+import java.io.File;
+import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
-import java.io.PrintStream;
+import java.util.Collections;
import java.util.List;
import java.util.Properties;
import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
-import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.hibernate.util.ConfigHelper;
+import org.jbpm.db.compatibility.JbpmSchemaUpdate;
+import org.jbpm.util.CollectionUtil;
-public class JbpmSchemaTask extends Task
-{
+public class JbpmSchemaTask extends Task {
String config;
String properties;
String action;
String output;
String delimiter;
- public void execute() throws BuildException
- {
+ public void execute() throws BuildException {
if (action == null)
action = "create";
if (config == null)
config = "hibernate.cfg.xml";
- List<Exception> exceptions = null;
- try
- {
+ List<? extends Exception> exceptions;
+ try {
Configuration configuration = getConfiguration();
- if ("drop".equalsIgnoreCase(action))
- {
+ if ("drop".equalsIgnoreCase(action)) {
SchemaExport schemaExport = getSchemaExport(configuration);
- schemaExport.execute(false, false, true, false);
- exceptions = schemaExport.getExceptions();
+ schemaExport.drop(false, false);
+ exceptions = CollectionUtil.checkList(schemaExport.getExceptions(), Exception.class);
}
- else if ("create".equalsIgnoreCase(action))
- {
+ else if ("create".equalsIgnoreCase(action)) {
SchemaExport schemaExport = getSchemaExport(configuration);
schemaExport.execute(false, false, false, true);
- exceptions = schemaExport.getExceptions();
+ exceptions = CollectionUtil.checkList(schemaExport.getExceptions(), Exception.class);
}
- else if ("update".equalsIgnoreCase(action))
- {
- PrintStream fileOut = null;
- PrintStream systemOut = System.out;
- try
- {
- if (output != null)
- {
- fileOut = new PrintStream(new FileOutputStream(output));
- System.setOut(fileOut);
- }
- SchemaUpdate schemaUpdate = getSchemaUpdate(configuration);
- schemaUpdate.execute(true, false);
- exceptions = schemaUpdate.getExceptions();
- }
- finally
- {
- if (fileOut != null)
- {
- System.setOut(systemOut);
- fileOut.close();
- }
- }
+ else if ("update".equalsIgnoreCase(action)) {
+ JbpmSchemaUpdate schemaUpdate = getSchemaUpdate(configuration);
+ schemaUpdate.execute(false, false);
+ exceptions = schemaUpdate.getExceptions();
}
- else
- {
- throw new IllegalArgumentException("Unsupported action: " + action);
+ else {
+ throw new BuildException("Unsupported action: " + action);
}
}
- catch (IOException ex)
- {
- throw new BuildException(ex);
+ catch (IOException ex) {
+ exceptions = Collections.singletonList(ex);
}
// Print the exceptions if there are any
- for (Exception ex : exceptions)
- log(ex.toString());
+ for (Exception exception : exceptions) {
+ log(exception.getMessage(), Project.MSG_ERR);
+ }
}
- private Configuration getConfiguration() throws IOException
- {
- log("Action '" + action + "' using " + config + "," + properties);
+ private Configuration getConfiguration() throws IOException {
+ log("Action '" + action + "' using " + config + ", " + properties);
+
Configuration configuration = new Configuration();
configuration.configure(config);
- if (properties != null)
- {
+ if (properties != null) {
InputStream inStream = ConfigHelper.getResourceAsStream(properties);
- if (inStream == null)
- throw new IllegalArgumentException("Cannot read properties: " + properties);
-
- try
- {
+ if (inStream == null) {
+ throw new FileNotFoundException("Could not find properties: " + properties);
+ }
+ try {
Properties properties = new Properties();
properties.load(inStream);
- configuration.setProperties(properties);
+ configuration.addProperties(properties);
}
- finally
- {
+ finally {
inStream.close();
}
}
return configuration;
}
- private SchemaExport getSchemaExport(Configuration configuration)
- {
+ private SchemaExport getSchemaExport(Configuration configuration) {
SchemaExport schemaExport = new SchemaExport(configuration);
if (output != null)
@@ -146,34 +120,35 @@
return schemaExport;
}
- private SchemaUpdate getSchemaUpdate(Configuration configuration)
- {
- SchemaUpdate schemaUpdate = new SchemaUpdate(configuration);
+ private JbpmSchemaUpdate getSchemaUpdate(Configuration configuration) {
+ JbpmSchemaUpdate schemaUpdate = new JbpmSchemaUpdate(configuration);
+
+ if (output != null)
+ schemaUpdate.setOutputFile(new File(output));
+
+ if (delimiter != null)
+ schemaUpdate.setDelimiter(delimiter);
+
return schemaUpdate;
}
- public void setAction(String action)
- {
+ public void setAction(String action) {
this.action = action;
}
- public void setConfig(String config)
- {
+ public void setConfig(String config) {
this.config = config;
}
- public void setProperties(String properties)
- {
+ public void setProperties(String properties) {
this.properties = properties;
}
- public void setDelimiter(String delimiter)
- {
+ public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}
- public void setOutput(String output)
- {
+ public void setOutput(String output) {
this.output = output;
}
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/calendar/BusinessCalendar.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/calendar/BusinessCalendar.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/calendar/BusinessCalendar.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -86,8 +86,7 @@
Date end = null;
if (duration.isBusinessTime()) {
DayPart dayPart = findDayPart(date);
- boolean isInbusinessHours = (dayPart!=null);
- if (! isInbusinessHours) {
+ if (dayPart == null) {
Object[] result = new Object[2];
findDay(date).findNextDayPartStart(0, date, result);
date = (Date) result[0];
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/command/AbstractBaseCommand.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/command/AbstractBaseCommand.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/command/AbstractBaseCommand.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -10,6 +10,8 @@
*/
public abstract class AbstractBaseCommand implements Command
{
+ private static final long serialVersionUID = 1L;
+
public String toString() {
return this.getClass().getName()
+ " ["
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/command/AbstractProcessInstanceBaseCommand.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/command/AbstractProcessInstanceBaseCommand.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/command/AbstractProcessInstanceBaseCommand.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -27,6 +27,7 @@
*/
public abstract class AbstractProcessInstanceBaseCommand extends AbstractBaseCommand
{
+ private static final long serialVersionUID = 1L;
protected Log log = LogFactory.getLog(this.getClass());
private long[] processInstanceIds = null;
@@ -71,7 +72,7 @@
operateOnSingleObject = false;
GetProcessInstancesCommand cmd = new GetProcessInstancesCommand();
- cmd.setProcessName(processName);
+ cmd.setProcessDefinitionName(processName);
cmd.setOnlyRunning(onlyRunning);
if (processVersion>0)
cmd.setVersion(String.valueOf(processVersion));
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/command/GetTaskListCommand.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/command/GetTaskListCommand.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/command/GetTaskListCommand.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -19,7 +19,7 @@
*
* @author Bernd Ruecker (bernd.ruecker at camunda.com)
*/
-public class GetTaskListCommand extends AbstractGetObjectBaseCommand implements Command
+public class GetTaskListCommand extends AbstractGetObjectBaseCommand
{
private static final long serialVersionUID = -1627380259541998349L;
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/command/StartProcessInstanceCommand.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/command/StartProcessInstanceCommand.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/command/StartProcessInstanceCommand.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -11,7 +11,7 @@
*
* @author Jim Rigsbee, Tom Baeyens, Bernd Ruecker
*/
-public class StartProcessInstanceCommand extends NewProcessInstanceCommand implements Command
+public class StartProcessInstanceCommand extends NewProcessInstanceCommand
{
private static final long serialVersionUID = -2428234069404269048L;
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/context/exe/ContextInstance.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/context/exe/ContextInstance.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/context/exe/ContextInstance.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -22,7 +22,6 @@
package org.jbpm.context.exe;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -46,10 +45,10 @@
private static final long serialVersionUID = 1L;
// maps Token's to TokenVariableMap's
- protected Map tokenVariableMaps = null;
+ protected Map<Token, TokenVariableMap> tokenVariableMaps = null;
// maps variablenames (String) to values (Object)
- protected transient Map transientVariables = null;
- protected transient List updatedVariableContainers = null;
+ protected transient Map<String, Object> transientVariables = null;
+ protected transient List<VariableContainer> updatedVariableContainers = null;
public ContextInstance()
{
@@ -93,7 +92,7 @@
/*
* gets all the variableInstances on the root-token (= process-instance scope).
*/
- public Map getVariables()
+ public Map<String, Object> getVariables()
{
return getVariables(getRootToken());
}
@@ -101,9 +100,9 @@
/*
* retrieves all the variableInstances in scope of the given token.
*/
- public Map getVariables(Token token)
+ public Map<String, Object> getVariables(Token token)
{
- Map variables = null;
+ Map<String, Object> variables = null;
TokenVariableMap tokenVariableMap = getTokenVariableMap(token);
if (tokenVariableMap != null)
@@ -117,7 +116,7 @@
/*
* adds all the variableInstances on the root-token (= process-instance scope).
*/
- public void addVariables(Map variables)
+ public void addVariables(Map<String, Object> variables)
{
setVariables(variables, getRootToken());
}
@@ -125,7 +124,7 @@
/*
* The method setVariables is the same as the {@link #addVariables(Map, Token)}, but it was added for more consistency.
*/
- public void setVariables(Map variables)
+ public void setVariables(Map<String, Object> variables)
{
setVariables(variables, getRootToken());
}
@@ -134,7 +133,7 @@
* adds all the variableInstances to the scope of the given token. This method delegates to {@link #setVariables(Map, Token)}. The method setVariables was added for
* more consistency.
*/
- public void addVariables(Map variables, Token token)
+ public void addVariables(Map<String, Object> variables, Token token)
{
setVariables(variables, token);
}
@@ -143,17 +142,14 @@
* adds all the variableInstances to the scope of the given token. The method setVariables is the same as the {@link #addVariables(Map, Token)}, but it was added for
* more consistency.
*/
- public void setVariables(Map variables, Token token)
+ public void setVariables(Map<String, Object> variables, Token token)
{
// [JBPM-1778] Empty map variables on process creation is set as null
TokenVariableMap tokenVariableMap = getOrCreateTokenVariableMap(token);
- Iterator iter = variables.entrySet().iterator();
- while (iter.hasNext())
- {
- Map.Entry entry = (Map.Entry)iter.next();
- String name = (String)entry.getKey();
+ for (Map.Entry<String, Object> entry : variables.entrySet()) {
+ String name = entry.getKey();
Object value = entry.getValue();
- tokenVariableMap.setVariable(name, value);
+ tokenVariableMap.setVariable(name, value);
}
}
@@ -197,7 +193,7 @@
Object variable = null;
if (tokenVariableMaps != null && tokenVariableMaps.containsKey(token))
{
- TokenVariableMap tokenVariableMap = (TokenVariableMap)tokenVariableMaps.get(token);
+ TokenVariableMap tokenVariableMap = tokenVariableMaps.get(token);
if (tokenVariableMap != null)
{
variable = tokenVariableMap.getVariableLocally(name);
@@ -289,7 +285,7 @@
{
if (transientVariables == null)
{
- transientVariables = new HashMap();
+ transientVariables = new HashMap<String, Object>();
}
transientVariables.put(name, value);
}
@@ -310,7 +306,7 @@
* retrieves all the transient variableInstances map. note that no deep copy is performed, changing the map leads to changes in the transient variableInstances of
* this context instance.
*/
- public Map getTransientVariables()
+ public Map<String, Object> getTransientVariables()
{
return transientVariables;
}
@@ -318,7 +314,7 @@
/*
* replaces the transient variableInstances with the given map.
*/
- public void setTransientVariables(Map transientVariables)
+ public void setTransientVariables(Map<String, Object> transientVariables)
{
this.transientVariables = transientVariables;
}
@@ -352,7 +348,7 @@
TokenVariableMap tokenVariableMap = null;
if ((tokenVariableMaps != null) && (tokenVariableMaps.containsKey(token)))
{
- tokenVariableMap = (TokenVariableMap)tokenVariableMaps.get(token);
+ tokenVariableMap = tokenVariableMaps.get(token);
}
else if (!token.isRoot())
@@ -372,9 +368,9 @@
{
if (tokenVariableMaps == null)
{
- tokenVariableMaps = new HashMap();
+ tokenVariableMaps = new HashMap<Token, TokenVariableMap>();
}
- TokenVariableMap tokenVariableMap = (TokenVariableMap)tokenVariableMaps.get(token);
+ TokenVariableMap tokenVariableMap = tokenVariableMaps.get(token);
if (tokenVariableMap == null)
{
tokenVariableMap = new TokenVariableMap(token, this);
@@ -393,7 +389,7 @@
{
if (tokenVariableMaps.containsKey(token))
{
- tokenVariableMap = (TokenVariableMap)tokenVariableMaps.get(token);
+ tokenVariableMap = tokenVariableMaps.get(token);
}
else if (!token.isRoot())
{
@@ -414,7 +410,7 @@
return variableInstance;
}
- public Map getTokenVariableMaps()
+ public Map<Token, TokenVariableMap> getTokenVariableMaps()
{
return tokenVariableMaps;
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/context/exe/TokenVariableMap.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/context/exe/TokenVariableMap.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/context/exe/TokenVariableMap.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -21,7 +21,6 @@
*/
package org.jbpm.context.exe;
-import java.io.Serializable;
import java.util.Map;
import org.jbpm.graph.exe.Token;
@@ -31,7 +30,7 @@
* Each token has it's own map of variableInstances, thereby creating
* hierarchy and scoping of process variableInstances.
*/
-public class TokenVariableMap extends VariableContainer implements Serializable {
+public class TokenVariableMap extends VariableContainer {
private static final long serialVersionUID = 1L;
@@ -75,7 +74,7 @@
public Token getToken() {
return token;
}
- public Map getVariableInstances() {
+ public Map<String, VariableInstance> getVariableInstances() {
return variableInstances;
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/context/exe/VariableContainer.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/context/exe/VariableContainer.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/context/exe/VariableContainer.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -4,7 +4,6 @@
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.Map;
import org.apache.commons.logging.Log;
@@ -17,7 +16,7 @@
public abstract class VariableContainer implements Serializable {
private static final long serialVersionUID = 520258491083406913L;
- protected Map variableInstances = null;
+ protected Map<String, VariableInstance> variableInstances = null;
protected abstract VariableContainer getParentVariableContainer();
public abstract Token getToken();
@@ -82,7 +81,7 @@
* The method {@link #setVariables(Map)} is the same as this method, but
* it was added for naming consitency.
*/
- public void addVariables(Map variables) {
+ public void addVariables(Map<String, Object> variables) {
setVariables(variables);
}
@@ -93,38 +92,34 @@
* This method is the same as {@link #addVariables(Map)} and this method
* was added for naming consistency.
*/
- public void setVariables(Map variables) {
+ public void setVariables(Map<String, Object> variables) {
if (variables!=null) {
- Iterator iter = variables.entrySet().iterator();
- while (iter.hasNext()) {
- Map.Entry entry = (Map.Entry) iter.next();
- setVariable((String) entry.getKey(), entry.getValue());
+ for (Map.Entry<String, Object> entry : variables.entrySet()) {
+ setVariable(entry.getKey(), entry.getValue());
}
}
}
- public Map getVariables() {
- Map variables = getVariablesLocally();
+ public Map<String, Object> getVariables() {
+ Map<String, Object> variables = getVariablesLocally();
VariableContainer parent = getParentVariableContainer();
if (parent!=null) {
- Map parentVariables = parent.getVariablesLocally();
+ Map<String, Object> parentVariables = parent.getVariablesLocally();
parentVariables.putAll(variables);
variables = parentVariables;
}
return variables;
}
- public Map getVariablesLocally() {
- Map variables = new HashMap();
+ public Map<String, Object> getVariablesLocally() {
+ Map<String, Object> variables = new HashMap<String, Object>();
if (variableInstances!=null) {
- Iterator iter = variableInstances.entrySet().iterator();
- while (iter.hasNext()) {
- Map.Entry entry = (Map.Entry) iter.next();
- String name = (String) entry.getKey();
- VariableInstance variableInstance = (VariableInstance) entry.getValue();
+ for (Map.Entry<String, VariableInstance> entry : variableInstances.entrySet()) {
+ String name = entry.getKey();
+ VariableInstance variableInstance = entry.getValue();
if (!variables.containsKey(name)) {
variables.put(name, variableInstance.getValue());
- }
+ }
}
}
return variables;
@@ -185,13 +180,13 @@
return (variableInstances!=null ? (VariableInstance) variableInstances.get(name) : null);
}
- public Map getVariableInstances() {
+ public Map<String, VariableInstance> getVariableInstances() {
return variableInstances;
}
public void addVariableInstance(VariableInstance variableInstance) {
if (variableInstances==null) {
- variableInstances = new HashMap();
+ variableInstances = new HashMap<String, VariableInstance>();
}
variableInstances.put(variableInstance.getName(), variableInstance);
// only additions are registered in the updated variable containers
@@ -202,7 +197,7 @@
public void deleteVariableInstance(String name) {
if (variableInstances!=null) {
- VariableInstance variableInstance = (VariableInstance) variableInstances.remove(name);
+ VariableInstance variableInstance = variableInstances.remove(name);
if (variableInstance!=null) {
getToken().addLog(new VariableDeleteLog(variableInstance));
variableInstance.removeReferences();
@@ -214,7 +209,7 @@
ContextInstance contextInstance = getContextInstance();
if (contextInstance!=null) {
if (contextInstance.updatedVariableContainers==null) {
- contextInstance.updatedVariableContainers = new ArrayList();
+ contextInstance.updatedVariableContainers = new ArrayList<VariableContainer>();
}
contextInstance.updatedVariableContainers.add(this);
}
@@ -226,7 +221,7 @@
return (processInstance!=null ? processInstance.getContextInstance() : null);
}
- public static Collection getUpdatedVariableContainers(ProcessInstance processInstance) {
+ public static Collection<VariableContainer> getUpdatedVariableContainers(ProcessInstance processInstance) {
return processInstance.getContextInstance().updatedVariableContainers;
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/GraphSession.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/GraphSession.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/GraphSession.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -22,89 +22,80 @@
package org.jbpm.db;
import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
+import java.util.Collection;
+import java.util.Collections;
import java.util.List;
-import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
+import org.hibernate.exception.SQLGrammarException;
import org.jbpm.JbpmException;
+import org.jbpm.graph.def.Node;
import org.jbpm.graph.def.ProcessDefinition;
import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.graph.exe.Token;
import org.jbpm.graph.node.ProcessState;
import org.jbpm.logging.log.ProcessLog;
+import org.jbpm.util.CollectionUtil;
/**
* are the graph related database operations.
*/
-public class GraphSession
-{
+public class GraphSession {
JbpmSession jbpmSession = null;
Session session = null;
- public GraphSession(JbpmSession jbpmSession)
- {
+ public GraphSession(JbpmSession jbpmSession) {
this.jbpmSession = jbpmSession;
this.session = jbpmSession.getSession();
}
- public GraphSession(Session session)
- {
+ public GraphSession(Session session) {
this.session = session;
this.jbpmSession = new JbpmSession(session);
}
// process definitions //////////////////////////////////////////////////////
- public void deployProcessDefinition(ProcessDefinition processDefinition)
- {
+ public void deployProcessDefinition(ProcessDefinition processDefinition) {
String processDefinitionName = processDefinition.getName();
- // if the process definition has a name (process versioning only applies to named process definitions)
- if (processDefinitionName != null)
- {
+ // if the process definition has a name (versioning applies to named process definitions only)
+ if (processDefinitionName != null) {
// find the current latest process definition
ProcessDefinition previousLatestVersion = findLatestProcessDefinition(processDefinitionName);
// if there is a current latest process definition
- if (previousLatestVersion != null)
- {
+ if (previousLatestVersion != null) {
// take the next version number
processDefinition.setVersion(previousLatestVersion.getVersion() + 1);
}
- else
- {
+ else {
// start from 1
processDefinition.setVersion(1);
}
-
session.save(processDefinition);
-
}
- else
- {
+ else {
throw new JbpmException("process definition does not have a name");
}
}
/**
- * saves the process definitions. this method does not assign a version number. that is the responsibility of the
- * {@link #deployProcessDefinition(ProcessDefinition) deployProcessDefinition} method.
+ * saves the process definitions. this method does not assign a version number. that is the
+ * responsibility of the {@link #deployProcessDefinition(ProcessDefinition)
+ * deployProcessDefinition} method.
*/
- public void saveProcessDefinition(ProcessDefinition processDefinition)
- {
- try
- {
+ public void saveProcessDefinition(ProcessDefinition processDefinition) {
+ try {
session.save(processDefinition);
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
throw new JbpmException("couldn't save process definition '" + processDefinition + "'", e);
@@ -116,14 +107,11 @@
*
* @throws JbpmException in case the referenced process definition doesn't exist.
*/
- public ProcessDefinition loadProcessDefinition(long processDefinitionId)
- {
- try
- {
- return (ProcessDefinition)session.load(ProcessDefinition.class, new Long(processDefinitionId));
+ public ProcessDefinition loadProcessDefinition(long processDefinitionId) {
+ try {
+ return (ProcessDefinition) session.load(ProcessDefinition.class, new Long(processDefinitionId));
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
throw new JbpmException("couldn't load process definition '" + processDefinitionId + "'", e);
@@ -135,14 +123,11 @@
*
* @return the referenced process definition or null in case it doesn't exist.
*/
- public ProcessDefinition getProcessDefinition(long processDefinitionId)
- {
- try
- {
- return (ProcessDefinition)session.get(ProcessDefinition.class, new Long(processDefinitionId));
+ public ProcessDefinition getProcessDefinition(long processDefinitionId) {
+ try {
+ return (ProcessDefinition) session.get(ProcessDefinition.class, new Long(processDefinitionId));
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
throw new JbpmException("couldn't get process definition '" + processDefinitionId + "'", e);
@@ -152,21 +137,22 @@
/**
* queries the database for a process definition with the given name and version.
*/
- public ProcessDefinition findProcessDefinition(String name, int version)
- {
+ public ProcessDefinition findProcessDefinition(String name, int version) {
ProcessDefinition processDefinition = null;
- try
- {
+ try {
Query query = session.getNamedQuery("GraphSession.findProcessDefinitionByNameAndVersion");
query.setString("name", name);
query.setInteger("version", version);
- processDefinition = (ProcessDefinition)query.uniqueResult();
+ processDefinition = (ProcessDefinition) query.uniqueResult();
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't get process definition with name '" + name + "' and version '" + version + "'", e);
+ throw new JbpmException("couldn't get process definition with name '"
+ + name
+ + "' and version '"
+ + version
+ + "'", e);
}
return processDefinition;
}
@@ -174,18 +160,15 @@
/**
* queries the database for the latest version of a process definition with the given name.
*/
- public ProcessDefinition findLatestProcessDefinition(String name)
- {
+ public ProcessDefinition findLatestProcessDefinition(String name) {
ProcessDefinition processDefinition = null;
- try
- {
+ try {
Query query = session.getNamedQuery("GraphSession.findLatestProcessDefinitionQuery");
query.setString("name", name);
query.setMaxResults(1);
- processDefinition = (ProcessDefinition)query.uniqueResult();
+ processDefinition = (ProcessDefinition) query.uniqueResult();
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
throw new JbpmException("couldn't find process definition '" + name + "'", e);
@@ -194,49 +177,45 @@
}
/**
- * queries the database for the latest version of each process definition. Process definitions are distinct by name.
+ * queries the database for the latest version of each process definition. Process definitions are
+ * distinct by name.
*/
- public List findLatestProcessDefinitions()
- {
- List processDefinitions = new ArrayList();
- Map processDefinitionsByName = new HashMap();
- try
- {
- Query query = session.getNamedQuery("GraphSession.findAllProcessDefinitions");
- Iterator iter = query.list().iterator();
- while (iter.hasNext())
- {
- ProcessDefinition processDefinition = (ProcessDefinition)iter.next();
- String processDefinitionName = processDefinition.getName();
- ProcessDefinition previous = (ProcessDefinition)processDefinitionsByName.get(processDefinitionName);
- if ((previous == null) || (previous.getVersion() < processDefinition.getVersion()))
- {
- processDefinitionsByName.put(processDefinitionName, processDefinition);
- }
+ public List<ProcessDefinition> findLatestProcessDefinitions() {
+ try {
+ Query query = session.getNamedQuery("GraphSession.findLatestProcessDefinitions");
+ List<Object[]> tuples = CollectionUtil.checkList(query.list(), Object[].class);
+
+ List<ProcessDefinition> result = new ArrayList<ProcessDefinition>();
+ for (Object[] tuple : tuples) {
+ String name = (String) tuple[0];
+ Integer version = (Integer) tuple[1];
+ result.add(findProcessDefinition(name, version));
}
- processDefinitions = new ArrayList(processDefinitionsByName.values());
+ return result;
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
throw new JbpmException("couldn't find latest versions of process definitions", e);
}
- return processDefinitions;
}
+ public List<ProcessDefinition> findProcessDefinitions(Collection<Long> processDefinitionIds) {
+ Criteria criteria = session.createCriteria(ProcessDefinition.class)
+ .add(Restrictions.in("id", processDefinitionIds));
+ return CollectionUtil.checkList(criteria.list(), ProcessDefinition.class);
+ }
+
/**
- * queries the database for all process definitions, ordered by name (ascending), then by version (descending).
+ * queries the database for all process definitions, ordered by name (ascending), then by version
+ * (descending).
*/
- public List findAllProcessDefinitions()
- {
- try
- {
+ public List<ProcessDefinition> findAllProcessDefinitions() {
+ try {
Query query = session.getNamedQuery("GraphSession.findAllProcessDefinitions");
- return query.list();
+ return CollectionUtil.checkList(query.list(), ProcessDefinition.class);
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
throw new JbpmException("couldn't find all process definitions", e);
@@ -244,72 +223,63 @@
}
/**
- * queries the database for all versions of process definitions with the given name, ordered by version (descending).
+ * queries the database for all versions of process definitions with the given name, ordered by
+ * version (descending).
*/
- public List findAllProcessDefinitionVersions(String name)
- {
- try
- {
+ public List<ProcessDefinition> findAllProcessDefinitionVersions(String name) {
+ try {
Query query = session.getNamedQuery("GraphSession.findAllProcessDefinitionVersions");
query.setString("name", name);
- return query.list();
+ return CollectionUtil.checkList(query.list(), ProcessDefinition.class);
}
- catch (HibernateException e)
- {
+ catch (HibernateException e) {
log.error(e);
throw new JbpmException("couldn't find all versions of process definition '" + name + "'", e);
}
}
- public void deleteProcessDefinition(long processDefinitionId)
- {
+ public void deleteProcessDefinition(long processDefinitionId) {
deleteProcessDefinition(loadProcessDefinition(processDefinitionId));
}
- public void deleteProcessDefinition(ProcessDefinition processDefinition)
- {
- if (processDefinition == null)
- {
+ public void deleteProcessDefinition(ProcessDefinition processDefinition) {
+ if (processDefinition == null) {
throw new JbpmException("processDefinition is null");
}
- try
- {
+ try {
// delete all the process instances of this definition
- for (ProcessInstance processInstance; ((processInstance = findNextProcessInstance(processDefinition)) != null);)
- {
+ for (ProcessInstance processInstance; ((processInstance = findNextProcessInstance(processDefinition)) != null);) {
deleteProcessInstance(processInstance);
}
- List referencingProcessStates = findReferencingProcessStates(processDefinition);
- for (Iterator iter = referencingProcessStates.iterator(); iter.hasNext();)
- {
- ProcessState processState = (ProcessState)iter.next();
+ List<ProcessState> referencingProcessStates = findReferencingProcessStates(processDefinition);
+ for (ProcessState processState : referencingProcessStates) {
processState.setSubProcessDefinition(null);
}
// then delete the process definition
session.delete(processDefinition);
-
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't delete process definition '" + processDefinition.getId() + "'", e);
+ throw new JbpmException("couldn't delete process definition '"
+ + processDefinition.getId()
+ + "'", e);
}
}
- protected ProcessInstance findNextProcessInstance(ProcessDefinition processDefinition)
- {
- return (ProcessInstance)session.createCriteria(ProcessInstance.class).add(Restrictions.eq("processDefinition", processDefinition)).setMaxResults(1)
+ protected ProcessInstance findNextProcessInstance(ProcessDefinition processDefinition) {
+ return (ProcessInstance) session.createCriteria(ProcessInstance.class)
+ .add(Restrictions.eq("processDefinition", processDefinition))
+ .setMaxResults(1)
.uniqueResult();
}
- protected List findReferencingProcessStates(ProcessDefinition subProcessDefinition)
- {
+ protected List<ProcessState> findReferencingProcessStates(ProcessDefinition subProcessDefinition) {
Query query = session.getNamedQuery("GraphSession.findReferencingProcessStates");
query.setEntity("subProcessDefinition", subProcessDefinition);
- return query.list();
+ return CollectionUtil.checkList(query.list(), ProcessState.class);
}
// process instances ////////////////////////////////////////////////////////
@@ -318,27 +288,24 @@
* @deprecated use {@link org.jbpm.JbpmContext#save(ProcessInstance)} instead.
* @throws UnsupportedOperationException
*/
- public void saveProcessInstance(ProcessInstance processInstance)
- {
+ public void saveProcessInstance(ProcessInstance processInstance) {
throw new UnsupportedOperationException("use JbpmContext.save(ProcessInstance) instead");
}
/**
- * loads a process instance from the database by the identifier. This throws an exception in case the process instance
- * doesn't exist.
+ * loads a process instance from the database by the identifier. This throws an exception in case
+ * the process instance doesn't exist.
*
* @see #getProcessInstance(long)
* @throws JbpmException in case the process instance doesn't exist.
*/
- public ProcessInstance loadProcessInstance(long processInstanceId)
- {
- try
- {
- ProcessInstance processInstance = (ProcessInstance)session.load(ProcessInstance.class, new Long(processInstanceId));
+ public ProcessInstance loadProcessInstance(long processInstanceId) {
+ try {
+ ProcessInstance processInstance = (ProcessInstance) session.load(ProcessInstance.class, new Long(
+ processInstanceId));
return processInstance;
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
throw new JbpmException("couldn't load process instance '" + processInstanceId + "'", e);
@@ -346,18 +313,16 @@
}
/**
- * gets a process instance from the database by the identifier. This method returns null in case the given process
- * instance doesn't exist.
+ * gets a process instance from the database by the identifier. This method returns null in case
+ * the given process instance doesn't exist.
*/
- public ProcessInstance getProcessInstance(long processInstanceId)
- {
- try
- {
- ProcessInstance processInstance = (ProcessInstance)session.get(ProcessInstance.class, new Long(processInstanceId));
+ public ProcessInstance getProcessInstance(long processInstanceId) {
+ try {
+ ProcessInstance processInstance = (ProcessInstance) session.get(ProcessInstance.class, new Long(
+ processInstanceId));
return processInstance;
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
throw new JbpmException("couldn't get process instance '" + processInstanceId + "'", e);
@@ -370,15 +335,12 @@
* @return the token.
* @throws JbpmException in case the referenced token doesn't exist.
*/
- public Token loadToken(long tokenId)
- {
- try
- {
- Token token = (Token)session.load(Token.class, new Long(tokenId));
+ public Token loadToken(long tokenId) {
+ try {
+ Token token = (Token) session.load(Token.class, new Long(tokenId));
return token;
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
throw new JbpmException("couldn't load token '" + tokenId + "'", e);
@@ -390,15 +352,12 @@
*
* @return the token or null in case the token doesn't exist.
*/
- public Token getToken(long tokenId)
- {
- try
- {
- Token token = (Token)session.get(Token.class, new Long(tokenId));
+ public Token getToken(long tokenId) {
+ try {
+ Token token = (Token) session.get(Token.class, new Long(tokenId));
return token;
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
throw new JbpmException("couldn't get token '" + tokenId + "'", e);
@@ -408,22 +367,18 @@
/**
* locks a process instance in the database.
*/
- public void lockProcessInstance(long processInstanceId)
- {
+ public void lockProcessInstance(long processInstanceId) {
lockProcessInstance(loadProcessInstance(processInstanceId));
}
/**
* locks a process instance in the database.
*/
- public void lockProcessInstance(ProcessInstance processInstance)
- {
- try
- {
+ public void lockProcessInstance(ProcessInstance processInstance) {
+ try {
session.lock(processInstance, LockMode.UPGRADE);
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
throw new JbpmException("couldn't lock process instance '" + processInstance.getId() + "'", e);
@@ -431,49 +386,41 @@
}
/**
- * fetches all processInstances for the given process definition from the database. The returned list of process
- * instances is sorted start date, youngest first.
+ * fetches all processInstances for the given process definition from the database. The returned
+ * list of process instances is sorted start date, youngest first.
*/
- public List findProcessInstances(long processDefinitionId)
- {
- List processInstances = null;
- try
- {
+ public List<ProcessInstance> findProcessInstances(long processDefinitionId) {
+ try {
Query query = session.getNamedQuery("GraphSession.findAllProcessInstancesForADefinition");
query.setLong("processDefinitionId", processDefinitionId);
- processInstances = query.list();
-
+ return CollectionUtil.checkList(query.list(), ProcessInstance.class);
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't load process instances for process definition '" + processDefinitionId + "'", e);
+ throw new JbpmException("couldn't load process instances for process definition '"
+ + processDefinitionId
+ + "'", e);
}
- return processInstances;
}
- public void deleteProcessInstance(long processInstanceId)
- {
+ public void deleteProcessInstance(long processInstanceId) {
deleteProcessInstance(loadProcessInstance(processInstanceId));
}
- public void deleteProcessInstance(ProcessInstance processInstance)
- {
+ public void deleteProcessInstance(ProcessInstance processInstance) {
deleteProcessInstance(processInstance, true, true);
}
- public void deleteProcessInstance(ProcessInstance processInstance, boolean includeTasks, boolean includeJobs)
- {
+ public void deleteProcessInstance(ProcessInstance processInstance, boolean includeTasks,
+ boolean includeJobs) {
if (processInstance == null)
throw new JbpmException("processInstance is null in JbpmSession.deleteProcessInstance()");
log.debug("deleting process instance " + processInstance.getId());
- try
- {
+ try {
// jobs
- if (includeJobs)
- {
+ if (includeJobs) {
log.debug("deleting jobs for process instance " + processInstance.getId());
Query query = session.getNamedQuery("GraphSession.deleteJobsForProcessInstance");
query.setEntity("processInstance", processInstance);
@@ -481,15 +428,16 @@
}
// tasks
- if (includeTasks)
- {
+ if (includeTasks) {
Query query = session.getNamedQuery("GraphSession.findTaskInstanceIdsForProcessInstance");
query.setEntity("processInstance", processInstance);
- List taskInstanceIds = query.list();
+ List<Long> taskInstanceIds = CollectionUtil.checkList(query.list(), Long.class);
- if ((taskInstanceIds != null) && (!taskInstanceIds.isEmpty()))
- {
- log.debug("deleting tasks " + taskInstanceIds + " for process instance " + processInstance.getId());
+ if (!taskInstanceIds.isEmpty()) {
+ log.debug("deleting tasks "
+ + taskInstanceIds
+ + " for process instance "
+ + processInstance.getId());
query = session.getNamedQuery("GraphSession.deleteTaskInstancesById");
query.setParameterList("taskInstanceIds", taskInstanceIds);
}
@@ -505,10 +453,12 @@
// null out the parent process token
Token superProcessToken = processInstance.getSuperProcessToken();
- if (superProcessToken != null)
- {
- log.debug("nulling property subProcessInstance in superProcessToken " + superProcessToken.getId() + " which is referencing the process instance "
- + processInstance.getId() + " which is being deleted");
+ if (superProcessToken != null) {
+ log.debug("nulling property subProcessInstance in superProcessToken "
+ + superProcessToken.getId()
+ + " which is referencing the process instance "
+ + processInstance.getId()
+ + " which is being deleted");
superProcessToken.setSubProcessInstance(null);
}
@@ -516,55 +466,45 @@
log.debug("hibernate session delete for process instance " + processInstance.getId());
session.delete(processInstance);
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't delete process instance '" + processInstance.getId() + "'", e);
+ throw new JbpmException("couldn't delete process instance '" + processInstance.getId() + "'",
+ e);
}
}
- void deleteLogs(ProcessInstance processInstance)
- {
+ void deleteLogs(ProcessInstance processInstance) {
Query query = session.getNamedQuery("GraphSession.findLogsForProcessInstance");
query.setEntity("processInstance", processInstance);
- List logs = query.list();
- Iterator iter = logs.iterator();
- while (iter.hasNext())
- {
- ProcessLog processLog = (ProcessLog)iter.next();
+ List<ProcessLog> logs = CollectionUtil.checkList(query.list(), ProcessLog.class);
+ for (ProcessLog processLog : logs) {
session.delete(processLog);
}
}
- void deleteSubProcesses(Token token)
- {
- if (token != null)
- {
+ void deleteSubProcesses(Token token) {
+ if (token != null) {
Query query = session.getNamedQuery("GraphSession.findSubProcessInstances");
query.setEntity("processInstance", token.getProcessInstance());
- List processInstances = query.list();
+ List<ProcessInstance> subProcessInstances = CollectionUtil.checkList(query.list(), ProcessInstance.class);
- if (processInstances == null || processInstances.isEmpty())
- {
+ if (subProcessInstances.isEmpty()) {
log.debug("no subprocesses to delete for token " + token.getId());
return;
}
- Iterator iter = processInstances.iterator();
- while (iter.hasNext())
- {
- ProcessInstance subProcessInstance = (ProcessInstance)iter.next();
+ for (ProcessInstance subProcessInstance : subProcessInstances) {
+ log.debug("deleting sub process " + subProcessInstance.getId());
subProcessInstance.setSuperProcessToken(null);
token.setSubProcessInstance(null);
- log.debug("deleting sub process " + subProcessInstance.getId());
deleteProcessInstance(subProcessInstance);
}
}
}
- public static class AverageNodeTimeEntry
- {
+ public static class AverageNodeTimeEntry {
+
private long nodeId;
private String nodeName;
private int count;
@@ -572,138 +512,117 @@
private long minDuration;
private long maxDuration;
- public long getNodeId()
- {
+ public long getNodeId() {
return nodeId;
}
- public void setNodeId(final long nodeId)
- {
+ public void setNodeId(final long nodeId) {
this.nodeId = nodeId;
}
- public String getNodeName()
- {
+ public String getNodeName() {
return nodeName;
}
- public void setNodeName(final String nodeName)
- {
+ public void setNodeName(final String nodeName) {
this.nodeName = nodeName;
}
- public int getCount()
- {
+ public int getCount() {
return count;
}
- public void setCount(final int count)
- {
+ public void setCount(final int count) {
this.count = count;
}
- public long getAverageDuration()
- {
+ public long getAverageDuration() {
return averageDuration;
}
- public void setAverageDuration(final long averageDuration)
- {
+ public void setAverageDuration(final long averageDuration) {
this.averageDuration = averageDuration;
}
- public long getMinDuration()
- {
+ public long getMinDuration() {
return minDuration;
}
- public void setMinDuration(final long minDuration)
- {
+ public void setMinDuration(final long minDuration) {
this.minDuration = minDuration;
}
- public long getMaxDuration()
- {
+ public long getMaxDuration() {
return maxDuration;
}
- public void setMaxDuration(final long maxDuration)
- {
+ public void setMaxDuration(final long maxDuration) {
this.maxDuration = maxDuration;
}
}
- public List calculateAverageTimeByNode(final long processDefinitionId, final long minumumDurationMillis)
- {
- List results = null;
- try
- {
+ public List<AverageNodeTimeEntry> calculateAverageTimeByNode(final long processDefinitionId,
+ final long minumumDurationMillis) {
+ try {
Query query = session.getNamedQuery("GraphSession.calculateAverageTimeByNode");
query.setLong("processDefinitionId", processDefinitionId);
query.setDouble("minimumDuration", minumumDurationMillis);
- List listResults = query.list();
+ List<Object[]> listResults = CollectionUtil.checkList(query.list(), Object[].class);
- if (listResults != null)
- {
- results = new ArrayList();
- Iterator iter = listResults.iterator();
- while (iter.hasNext())
- {
- Object[] values = (Object[])iter.next();
+ List<AverageNodeTimeEntry> results;
+ if (!listResults.isEmpty()) {
+ results = new ArrayList<AverageNodeTimeEntry>();
+ for (Object[] values : listResults) {
AverageNodeTimeEntry averageNodeTimeEntry = new AverageNodeTimeEntry();
- averageNodeTimeEntry.setNodeId(((Number)values[0]).longValue());
- averageNodeTimeEntry.setNodeName((String)values[1]);
- averageNodeTimeEntry.setCount(((Number)values[2]).intValue());
- averageNodeTimeEntry.setAverageDuration(((Number)values[3]).longValue());
- averageNodeTimeEntry.setMinDuration(((Number)values[4]).longValue());
- averageNodeTimeEntry.setMaxDuration(((Number)values[5]).longValue());
+ averageNodeTimeEntry.setNodeId(((Number) values[0]).longValue());
+ averageNodeTimeEntry.setNodeName((String) values[1]);
+ averageNodeTimeEntry.setCount(((Number) values[2]).intValue());
+ averageNodeTimeEntry.setAverageDuration(((Number) values[3]).longValue());
+ averageNodeTimeEntry.setMinDuration(((Number) values[4]).longValue());
+ averageNodeTimeEntry.setMaxDuration(((Number) values[5]).longValue());
results.add(averageNodeTimeEntry);
}
}
+ else {
+ results = Collections.emptyList();
+ }
+ return results;
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't load process instances for process definition '" + processDefinitionId + "'", e);
+ throw new JbpmException("couldn't load process instances for process definition '"
+ + processDefinitionId
+ + "'", e);
}
- return results;
}
- public List findActiveNodesByProcessInstance(ProcessInstance processInstance)
- {
- List results = null;
- try
- {
+ public List<Node> findActiveNodesByProcessInstance(ProcessInstance processInstance) {
+ try {
Query query = session.getNamedQuery("GraphSession.findActiveNodesByProcessInstance");
query.setEntity("processInstance", processInstance);
- results = query.list();
-
+ return CollectionUtil.checkList(query.list(), Node.class);
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't active nodes for process instance '" + processInstance + "'", e);
+ throw new JbpmException("couldn't active nodes for process instance '"
+ + processInstance
+ + "'", e);
}
- return results;
}
- public ProcessInstance getProcessInstance(ProcessDefinition processDefinition, String key)
- {
+ public ProcessInstance getProcessInstance(ProcessDefinition processDefinition, String key) {
ProcessInstance processInstance = null;
- try
- {
+ try {
Query query = session.getNamedQuery("GraphSession.findProcessInstanceByKey");
query.setEntity("processDefinition", processDefinition);
query.setString("key", key);
- processInstance = (ProcessInstance)query.uniqueResult();
-
+ processInstance = (ProcessInstance) query.uniqueResult();
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
throw new JbpmException("couldn't get process instance with key '" + key + "'", e);
@@ -711,23 +630,18 @@
return processInstance;
}
- public ProcessInstance loadProcessInstance(ProcessDefinition processDefinition, String key)
- {
+ public ProcessInstance loadProcessInstance(ProcessDefinition processDefinition, String key) {
ProcessInstance processInstance = null;
- try
- {
+ try {
Query query = session.getNamedQuery("GraphSession.findProcessInstanceByKey");
query.setEntity("processDefinition", processDefinition);
query.setString("key", key);
- processInstance = (ProcessInstance)query.uniqueResult();
- if (processInstance == null)
- {
+ processInstance = (ProcessInstance) query.uniqueResult();
+ if (processInstance == null) {
throw new JbpmException("no process instance was found with key " + key);
}
-
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
throw new JbpmException("couldn't load process instance with key '" + key + "'", e);
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/JbpmSchema.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/JbpmSchema.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/JbpmSchema.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -49,21 +49,18 @@
import org.hibernate.engine.Mapping;
import org.hibernate.mapping.ForeignKey;
import org.hibernate.mapping.Table;
-import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.util.JDBCExceptionReporter;
import org.jbpm.JbpmException;
/**
* utilities for the jBPM database schema.
*/
-public class JbpmSchema implements Serializable
-{
+public class JbpmSchema implements Serializable {
private static final long serialVersionUID = 1L;
Configuration configuration = null;
Settings settings;
- Mapping mapping = null;
String[] createSql = null;
String[] dropSql = null;
String[] cleanSql = null;
@@ -72,57 +69,46 @@
Connection connection = null;
Statement statement = null;
- public JbpmSchema(Configuration configuration)
- {
+ public JbpmSchema(Configuration configuration) {
this.configuration = configuration;
this.settings = configuration.buildSettings();
- this.mapping = configuration.buildMapping();
}
- public String[] getCreateSql()
- {
- if (createSql == null)
- {
+ public String[] getCreateSql() {
+ if (createSql == null) {
createSql = configuration.generateSchemaCreationScript(settings.getDialect());
}
return createSql;
}
- public String[] getDropSql()
- {
- if (dropSql == null)
- {
+ public String[] getDropSql() {
+ if (dropSql == null) {
dropSql = configuration.generateDropSchemaScript(settings.getDialect());
}
return dropSql;
}
- public String[] getCleanSql()
- {
- if (cleanSql == null)
- {
- new SchemaExport(configuration);
-
+ public String[] getCleanSql() {
+ if (cleanSql == null) {
Dialect dialect = settings.getDialect();
String catalog = settings.getDefaultCatalogName();
String schema = settings.getDefaultSchemaName();
+ Mapping mapping = configuration.buildMapping();
// loop over all foreign key constraints
List dropForeignKeysSql = new ArrayList();
List createForeignKeysSql = new ArrayList();
+ List deleteSql = new ArrayList();
+
Iterator iter = configuration.getTableMappings();
- while (iter.hasNext())
- {
- Table table = (Table)iter.next();
- if (table.isPhysicalTable())
- {
+ while (iter.hasNext()) {
+ Table table = (Table) iter.next();
+ if (table.isPhysicalTable()) {
Iterator subIter = table.getForeignKeyIterator();
- while (subIter.hasNext())
- {
- ForeignKey fk = (ForeignKey)subIter.next();
+ while (subIter.hasNext()) {
+ ForeignKey fk = (ForeignKey) subIter.next();
- if (fk.isPhysicalConstraint())
- {
+ if (fk.isPhysicalConstraint()) {
// collect the drop foreign key constraint sql
String sqlDropString = fk.sqlDropString(dialect, catalog, schema);
dropForeignKeysSql.add(sqlDropString);
@@ -132,67 +118,65 @@
createForeignKeysSql.add(sqlCreateString);
}
}
+ deleteSql.add("delete from " + table.getName());
}
}
- List deleteSql = new ArrayList();
- iter = configuration.getTableMappings();
- while (iter.hasNext())
- {
- Table table = (Table)iter.next();
- deleteSql.add("delete from " + table.getName());
- }
-
// glue
// - drop foreign key constraints
// - delete contents of all tables
// - create foreign key constraints
// together to form the clean script
- List cleanSqlList = new ArrayList();
- cleanSqlList.addAll(dropForeignKeysSql);
- cleanSqlList.addAll(deleteSql);
- cleanSqlList.addAll(createForeignKeysSql);
-
- cleanSql = (String[])cleanSqlList.toArray(new String[cleanSqlList.size()]);
+ cleanSql = concat(dropForeignKeysSql, deleteSql, createForeignKeysSql);
}
return cleanSql;
}
- public boolean hasJbpmTables()
- {
+ private static String[] concat(List<String>... lists) {
+ int length = 0;
+ for (List<String> list : lists) {
+ length += list.size();
+ }
+ String[] array = new String[length];
+ int i = 0;
+ for (List<String> list : lists) {
+ for (String element : list) {
+ array[i++] = element;
+ }
+ }
+ return array;
+ }
+
+ public boolean hasJbpmTables() {
return (getJbpmTables().size() > 0);
}
- public List getJbpmTables()
- {
+ public List getJbpmTables() {
// delete all the data in the jbpm tables
List jbpmTableNames = new ArrayList();
Iterator iter = configuration.getTableMappings();
- while (iter.hasNext())
- {
- Table table = (Table)iter.next();
- if (table.isPhysicalTable())
- {
+ while (iter.hasNext()) {
+ Table table = (Table) iter.next();
+ if (table.isPhysicalTable()) {
jbpmTableNames.add(table.getName());
}
}
return jbpmTableNames;
}
-
+
public Map getJbpmTablesRecordCount() {
Map recordCounts = new HashMap();
-
+
String sql = null;
-
- try
- {
+
+ try {
Iterator iter = getJbpmTables().iterator();
createConnection();
while (iter.hasNext()) {
statement = connection.createStatement();
String tableName = (String) iter.next();
- sql = "SELECT COUNT(*) FROM "+tableName;
+ sql = "SELECT COUNT(*) FROM " + tableName;
ResultSet resultSet = statement.executeQuery(sql);
resultSet.next();
int count = resultSet.getInt(1);
@@ -201,109 +185,99 @@
recordCounts.put(tableName, count);
}
}
- catch (SQLException e)
- {
+ catch (SQLException e) {
throw new JbpmException("couldn't execute sql '" + sql + "'", e);
}
- finally
- {
+ finally {
closeConnection();
}
return recordCounts;
}
- public void dropSchema()
- {
+ public void dropSchema() {
execute(getDropSql());
}
- public void createSchema()
- {
+ public void createSchema() {
execute(getCreateSql());
}
- public void cleanSchema()
- {
+ public void cleanSchema() {
if (getJbpmTables().size() > 0)
execute(getCleanSql());
}
- public void saveSqlScripts(String dir, String prefix)
- {
- try
- {
+ public void saveSqlScripts(String dir, String prefix) {
+ try {
new File(dir).mkdirs();
saveSqlScript(dir + "/" + prefix + ".drop.sql", getDropSql());
saveSqlScript(dir + "/" + prefix + ".create.sql", getCreateSql());
saveSqlScript(dir + "/" + prefix + ".clean.sql", getCleanSql());
- new SchemaExport(configuration).setDelimiter(getSqlDelimiter()).setOutputFile(dir + "/" + prefix + ".drop.create.sql").create(true, false);
+ saveSqlScript(dir + "/" + prefix + ".drop.create.sql", concat(getDropSql(), getCreateSql()));
}
- catch (IOException e)
- {
+ catch (IOException e) {
throw new JbpmException("couldn't generate scripts", e);
}
}
- public static void main(String[] args)
- {
- if ((args == null) || (args.length == 0))
- {
+ private static String[] concat(String[] array1, String[] array2) {
+ int length1 = array1.length;
+ int length2 = array2.length;
+ String[] result = new String[length1 + length2];
+ System.arraycopy(array1, 0, result, 0, length1);
+ System.arraycopy(array2, 0, result, length1, length2);
+ return result;
+ }
+
+ public static void main(String[] args) {
+ if ((args == null) || (args.length == 0)) {
syntax();
}
- else if ("create".equalsIgnoreCase(args[0]) && args.length <= 3)
- {
+ else if ("create".equalsIgnoreCase(args[0]) && args.length <= 3) {
Configuration configuration = createConfiguration(args, 1);
new JbpmSchema(configuration).createSchema();
}
- else if ("drop".equalsIgnoreCase(args[0]) && args.length <= 3)
- {
+ else if ("drop".equalsIgnoreCase(args[0]) && args.length <= 3) {
Configuration configuration = createConfiguration(args, 1);
new JbpmSchema(configuration).dropSchema();
}
- else if ("clean".equalsIgnoreCase(args[0]) && args.length <= 3)
- {
+ else if ("clean".equalsIgnoreCase(args[0]) && args.length <= 3) {
Configuration configuration = createConfiguration(args, 1);
new JbpmSchema(configuration).cleanSchema();
}
- else if ("scripts".equalsIgnoreCase(args[0]) && args.length >= 3 && args.length <= 5)
- {
+ else if ("scripts".equalsIgnoreCase(args[0]) && args.length >= 3 && args.length <= 5) {
Configuration configuration = createConfiguration(args, 3);
new JbpmSchema(configuration).saveSqlScripts(args[1], args[2]);
}
- else
- {
+ else {
syntax();
}
}
- private static void syntax()
- {
+ private static void syntax() {
System.err.println("syntax:");
System.err.println("JbpmSchema create [<hibernate.cfg.xml> [<hibernate.properties>]]");
System.err.println("JbpmSchema drop [<hibernate.cfg.xml> [<hibernate.properties>]]");
System.err.println("JbpmSchema clean [<hibernate.cfg.xml> [<hibernate.properties>]]");
- System.err.println("JbpmSchema scripts <dir> <prefix> [<hibernate.cfg.xml> [<hibernate.properties>]]");
+ System.err
+ .println("JbpmSchema scripts <dir> <prefix> [<hibernate.cfg.xml> [<hibernate.properties>]]");
}
- static Configuration createConfiguration(String[] args, int index)
- {
+ static Configuration createConfiguration(String[] args, int index) {
String hibernateCfgXml = (args.length > index ? args[index] : "hibernate.cfg.xml");
String hibernateProperties = (args.length > (index + 1) ? args[index + 1] : null);
Configuration configuration = new Configuration();
configuration.configure(new File(hibernateCfgXml));
- if (hibernateProperties != null)
- {
- try
- {
+ if (hibernateProperties != null) {
+ try {
Properties properties = new Properties();
InputStream inputStream = new FileInputStream(hibernateProperties);
properties.load(inputStream);
configuration.setProperties(properties);
}
- catch (IOException e)
- {
+ catch (IOException e) {
throw new JbpmException("couldn't load hibernate configuration", e);
}
}
@@ -311,42 +285,33 @@
return configuration;
}
- void saveSqlScript(String fileName, String[] sql) throws FileNotFoundException
- {
+ void saveSqlScript(String fileName, String[] sql) throws FileNotFoundException {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
- try
- {
+ try {
PrintStream printStream = new PrintStream(fileOutputStream);
- for (int i = 0; i < sql.length; i++)
- {
+ for (int i = 0; i < sql.length; i++) {
printStream.println(sql[i] + getSqlDelimiter());
}
}
- finally
- {
- try
- {
+ finally {
+ try {
fileOutputStream.close();
}
- catch (IOException e)
- {
+ catch (IOException e) {
log.debug("failed to close file", e);
}
}
}
- public void execute(String[] sqls)
- {
+ void execute(String[] sqls) {
String sql = null;
boolean showSql = settings.isShowSqlEnabled();
- try
- {
+ try {
createConnection();
statement = connection.createStatement();
- for (int i = 0; i < sqls.length; i++)
- {
+ for (int i = 0; i < sqls.length; i++) {
sql = sqls[i];
if (showSql)
@@ -355,58 +320,46 @@
}
}
- catch (SQLException e)
- {
+ catch (SQLException e) {
throw new JbpmException("couldn't execute sql '" + sql + "'", e);
}
- finally
- {
+ finally {
closeConnection();
}
}
- void closeConnection()
- {
- if (statement != null)
- {
- try
- {
+ void closeConnection() {
+ if (statement != null) {
+ try {
statement.close();
}
- catch (SQLException e)
- {
+ catch (SQLException e) {
log.debug("could not close jdbc statement", e);
}
}
- if (connection != null)
- {
- try
- {
+ if (connection != null) {
+ try {
JDBCExceptionReporter.logWarnings(connection.getWarnings());
connection.clearWarnings();
connectionProvider.closeConnection(connection);
connectionProvider.close();
}
- catch (SQLException e)
- {
+ catch (SQLException e) {
log.debug("could not close jdbc connection", e);
}
}
}
- void createConnection() throws SQLException
- {
+ void createConnection() throws SQLException {
connectionProvider = settings.getConnectionProvider();
connection = connectionProvider.getConnection();
- if (!connection.getAutoCommit())
- {
+ if (!connection.getAutoCommit()) {
connection.commit();
connection.setAutoCommit(true);
}
}
- public Properties getProperties()
- {
+ public Properties getProperties() {
return configuration.getProperties();
}
@@ -414,10 +367,8 @@
static String sqlDelimiter = null;
- synchronized String getSqlDelimiter()
- {
- if (sqlDelimiter == null)
- {
+ synchronized String getSqlDelimiter() {
+ if (sqlDelimiter == null) {
sqlDelimiter = getProperties().getProperty("jbpm.sql.delimiter", ";");
}
return sqlDelimiter;
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/JobSession.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/JobSession.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/JobSession.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -27,6 +27,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
@@ -36,6 +37,7 @@
import org.jbpm.graph.exe.Token;
import org.jbpm.job.Job;
import org.jbpm.job.Timer;
+import org.jbpm.util.CollectionUtil;
public class JobSession {
@@ -61,20 +63,17 @@
return job;
}
- public List findExclusiveJobs(String lockOwner, ProcessInstance processInstance) {
- List jobs = null;
+ public List<Job> findExclusiveJobs(String lockOwner, ProcessInstance processInstance) {
try {
Query query = session.getNamedQuery("JobSession.findExclusiveJobs");
query.setString("lockOwner", lockOwner);
query.setTimestamp("now", new Date());
query.setParameter("processInstance", processInstance);
- jobs = query.list();
-
+ return CollectionUtil.checkList(query.list(), Job.class);
} catch (Exception e) {
log.error(e);
throw new JbpmException("couldn't find exclusive jobs for thread '"+lockOwner+"' and process instance '"+processInstance+"'", e);
}
- return jobs;
}
/**
@@ -84,14 +83,13 @@
try {
Query query = session.getNamedQuery("JobSession.findJobsByToken");
query.setParameter("token", token);
- List<Job> jobs = query.list();
- return jobs;
+ return CollectionUtil.checkList(query.list(), Job.class);
} catch (Exception e) {
throw new JbpmException("couldn't find jobs for token '"+token+"'", e);
}
}
- public Job getFirstDueJob(String lockOwner, Collection jobIdsToIgnore) {
+ public Job getFirstDueJob(String lockOwner, Collection<Long> jobIdsToIgnore) {
Job job = null;
try {
Query query = null;
@@ -151,15 +149,15 @@
}
}
- public List loadJobs(long[] jobIds) {
+ public List<Job> loadJobs(long[] jobIds) {
int jobCount = jobIds.length;
Long[] jobs = new Long[jobCount];
for (int i = 0; i < jobCount; i++) {
jobs[i] = new Long(jobIds[i]);
}
- return session.createCriteria(Job.class)
- .add(Restrictions.in("id", jobs))
- .list();
+ Criteria criteria = session.createCriteria(Job.class)
+ .add(Restrictions.in("id", jobs));
+ return CollectionUtil.checkList(criteria.list(), Job.class);
}
public Job getJob(long jobId) {
@@ -223,11 +221,10 @@
log.debug(entityCount+" remaining execute-node-jobs for "+processInstance+" were deleted");
}
-
- public List findJobsWithOverdueLockTime(Date treshold) {
+ public List<Job> findJobsWithOverdueLockTime(Date treshold) {
Query query = session.getNamedQuery("JobSession.findJobsWithOverdueLockTime");
query.setDate("now", treshold);
- return query.list();
+ return CollectionUtil.checkList(query.list(), Job.class);
}
private static Log log = LogFactory.getLog(JobSession.class);
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/LoggingSession.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/LoggingSession.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/LoggingSession.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -22,7 +22,6 @@
package org.jbpm.db;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -34,84 +33,95 @@
import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.graph.exe.Token;
import org.jbpm.logging.log.ProcessLog;
+import org.jbpm.util.CollectionUtil;
public class LoggingSession {
JbpmSession jbpmSession;
Session session;
-
+
public LoggingSession(JbpmSession jbpmSession) {
this.jbpmSession = jbpmSession;
this.session = jbpmSession.getSession();
}
-
+
public LoggingSession(Session session) {
this.session = session;
this.jbpmSession = new JbpmSession(session);
}
/**
- * returns a map that maps {@link Token}s to {@link List}s. The lists contain the ordered
- * logs for the given token. The lists are retrieved with {@link #findLogsByToken(long)}.
+ * returns a map of {@linkplain Token tokens} to {@linkplain List lists}. The lists contain the
+ * ordered logs for the given token. The lists are retrieved with {@link #findLogsByToken(long)}.
*/
- public Map findLogsByProcessInstance(long processInstanceId) {
- Map tokenLogs = new HashMap();
+ public Map<Token, List<ProcessLog>> findLogsByProcessInstance(long processInstanceId) {
+ return findLogsByProcessInstance((ProcessInstance) session.load(ProcessInstance.class, processInstanceId));
+ }
+
+ /**
+ * returns a map of {@linkplain Token tokens} to {@linkplain List lists}. The lists contain the
+ * ordered logs for the given token. The lists are retrieved with {@link #findLogsByToken(long)}.
+ */
+ public Map<Token, List<ProcessLog>> findLogsByProcessInstance(ProcessInstance processInstance) {
+ Map<Token, List<ProcessLog>> tokenLogs = new HashMap<Token, List<ProcessLog>>();
try {
- ProcessInstance processInstance = (ProcessInstance) session.load(ProcessInstance.class, new Long(processInstanceId));
collectTokenLogs(tokenLogs, processInstance.getRootToken());
- } catch (Exception e) {
+ }
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't get logs for process instance '"+processInstanceId+"'", e);
- }
+ throw new JbpmException("couldn't get logs for " + processInstance, e);
+ }
return tokenLogs;
}
- private void collectTokenLogs(Map tokenLogs, Token token) {
- tokenLogs.put(token, findLogsByToken(token.getId()));
- Map children = token.getChildren();
- if ( (children!=null)
- && (!children.isEmpty())
- ) {
- Iterator iter = children.values().iterator();
- while (iter.hasNext()) {
- Token child = (Token) iter.next();
+ private void collectTokenLogs(Map<Token, List<ProcessLog>> tokenLogs, Token token) {
+ tokenLogs.put(token, findLogsByToken(token));
+ Map<String, Token> children = token.getChildren();
+ if ((children != null) && (!children.isEmpty())) {
+ for (Token child : children.values()) {
collectTokenLogs(tokenLogs, child);
}
}
}
-
+
/**
* collects the logs for a given token, ordered by creation time.
*/
- public List findLogsByToken(long tokenId) {
- List result = null;
+ public List<ProcessLog> findLogsByToken(long tokenId) {
+ return findLogsByToken((Token) session.load(Token.class, tokenId));
+ }
+
+ /**
+ * collects the logs for a given token, ordered by creation time.
+ */
+ public List<ProcessLog> findLogsByToken(Token token) {
try {
- Token token = (Token) session.load(Token.class, new Long(tokenId));
Query query = session.getNamedQuery("LoggingSession.findLogsByToken");
query.setEntity("token", token);
- result = query.list();
- } catch (Exception e) {
+ return CollectionUtil.checkList(query.list(), ProcessLog.class);
+ }
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't get logs for token '"+tokenId+"'", e);
- }
- return result;
+ throw new JbpmException("couldn't get logs for " + token, e);
+ }
}
-
+
/**
* saves the given process log to the database.
*/
public void saveProcessLog(ProcessLog processLog) {
try {
session.save(processLog);
- } catch (Exception e) {
+ }
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't save process log '"+processLog+"'", e);
- }
+ throw new JbpmException("couldn't save process log '" + processLog + "'", e);
+ }
}
-
+
/**
* load the process log for a given id.
*/
@@ -119,14 +129,15 @@
ProcessLog processLog = null;
try {
processLog = (ProcessLog) session.load(ProcessLog.class, new Long(processLogId));
- } catch (Exception e) {
+ }
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't load process log '"+processLogId+"'", e);
- }
+ throw new JbpmException("couldn't load process log '" + processLogId + "'", e);
+ }
return processLog;
}
-
+
/**
* get the process log for a given id.
*/
@@ -134,13 +145,14 @@
ProcessLog processLog = null;
try {
processLog = (ProcessLog) session.get(ProcessLog.class, new Long(processLogId));
- } catch (Exception e) {
+ }
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't get process log '"+processLogId+"'", e);
- }
+ throw new JbpmException("couldn't get process log '" + processLogId + "'", e);
+ }
return processLog;
}
-
+
private static final Log log = LogFactory.getLog(LoggingSession.class);
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/TaskMgmtSession.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/TaskMgmtSession.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/TaskMgmtSession.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -22,9 +22,8 @@
package org.jbpm.db;
import java.io.Serializable;
-import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collections;
-import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
@@ -34,155 +33,137 @@
import org.jbpm.JbpmException;
import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.taskmgmt.exe.TaskInstance;
+import org.jbpm.util.CollectionUtil;
public class TaskMgmtSession implements Serializable {
private static final long serialVersionUID = 1L;
-
+
JbpmSession jbpmSession = null;
Session session = null;
-
+
public TaskMgmtSession(JbpmSession jbpmSession) {
this.jbpmSession = jbpmSession;
this.session = jbpmSession.getSession();
}
-
+
public TaskMgmtSession(Session session) {
this.session = session;
this.jbpmSession = new JbpmSession(session);
}
/**
- * get the tasllist for a given actor.
+ * get the tasklist for a given actor.
*/
- public List findTaskInstances(String actorId) {
- List result = null;
+ public List<TaskInstance> findTaskInstances(String actorId) {
try {
Query query = session.getNamedQuery("TaskMgmtSession.findTaskInstancesByActorId");
query.setString("actorId", actorId);
- result = query.list();
- } catch (Exception e) {
+ return CollectionUtil.checkList(query.list(), TaskInstance.class);
+ }
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't get task instances list for actor '"+actorId+"'", e);
- }
- return result;
+ throw new JbpmException("couldn't get task instances list for actor '" + actorId + "'", e);
+ }
}
-
- /**
- * get all the task instances for all the given actorIds.
- * @return a list of task instances. An empty list is returned in case no task instances are found.
- */
- public List findTaskInstances(List actorIds) {
- if (actorIds==null) return new ArrayList(0);
- return findTaskInstances((String[])actorIds.toArray(new String[actorIds.size()]));
- }
/**
* get all the task instances for all the given actorIds.
+ *
+ * @return a list of task instances. An empty list is returned in case no task instances are
+ * found.
*/
- public List findTaskInstances(String[] actorIds) {
- List result = null;
+ public List<TaskInstance> findTaskInstances(List<String> actorIds) {
try {
Query query = session.getNamedQuery("TaskMgmtSession.findTaskInstancesByActorIds");
query.setParameterList("actorIds", actorIds);
- result = query.list();
- } catch (Exception e) {
+ return CollectionUtil.checkList(query.list(), TaskInstance.class);
+ }
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't get task instances list for actors '"+actorIds+"'", e);
- }
- return result;
+ throw new JbpmException("couldn't get task instances list for actors '" + actorIds + "'", e);
+ }
}
/**
- * get the taskinstances for which the given actor is in the pool.
+ * get all the task instances for all the given actorIds.
*/
- public List findPooledTaskInstances(String actorId) {
- List result = null;
+ public List<TaskInstance> findTaskInstances(String[] actorIds) {
+ return findTaskInstances(Arrays.asList(actorIds));
+ }
+
+ /**
+ * get the task instances for which the given actor is in the pool.
+ */
+ public List<TaskInstance> findPooledTaskInstances(String actorId) {
try {
Query query = session.getNamedQuery("TaskMgmtSession.findPooledTaskInstancesByActorId");
- query.setString("swimlaneActorId", actorId);
- List identifiers = query.list();
- if (!identifiers.isEmpty()) {
- result = new ArrayList(identifiers.size());
- for (Iterator i = identifiers.iterator(); i.hasNext();) {
- Long taskInstanceId = (Long) i.next();
- result.add(session.load(TaskInstance.class, taskInstanceId));
- }
- }
- else {
- result = Collections.EMPTY_LIST;
- }
- } catch (Exception e) {
+ query.setString("actorId", actorId);
+ List<Long> taskInstanceIds = CollectionUtil.checkList(query.list(), Long.class);
+ return findTaskInstancesByIds(taskInstanceIds);
+ }
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't get pooled task instances list for actor '"+actorId+"'", e);
- }
- return result;
+ throw new JbpmException(
+ "couldn't get pooled task instances list for actor '" + actorId + "'", e);
+ }
}
-
+
/**
- * get the taskinstances for which the given actor is in the pool.
+ * get the task instances for which the given actor is in the pool.
*/
- public List findPooledTaskInstances(List actorIds) {
- List result = null;
+ public List<TaskInstance> findPooledTaskInstances(List<String> actorIds) {
try {
Query query = session.getNamedQuery("TaskMgmtSession.findPooledTaskInstancesByActorIds");
query.setParameterList("actorIds", actorIds);
- List identifiers = query.list();
- if (!identifiers.isEmpty()) {
- result = new ArrayList(identifiers.size());
- for (Iterator i = identifiers.iterator(); i.hasNext();) {
- Long taskInstanceId = (Long) i.next();
- result.add(session.load(TaskInstance.class, taskInstanceId));
- }
- }
- else {
- result = Collections.EMPTY_LIST;
- }
- } catch (Exception e) {
+ List<Long> taskInstanceIds = CollectionUtil.checkList(query.list(), Long.class);
+ return findTaskInstancesByIds(taskInstanceIds);
+ }
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't get pooled task instances list for actors '"+actorIds+"'", e);
- }
- return result;
+ throw new JbpmException("couldn't get pooled task instances list for actors '"
+ + actorIds
+ + "'", e);
+ }
}
/**
- * get active taskinstances for a given token.
+ * get active task instances for a given token.
*/
- public List findTaskInstancesByToken(long tokenId) {
- List result = null;
+ public List<TaskInstance> findTaskInstancesByToken(long tokenId) {
try {
Query query = session.getNamedQuery("TaskMgmtSession.findTaskInstancesByTokenId");
query.setLong("tokenId", tokenId);
- result = query.list();
- } catch (Exception e) {
+ return CollectionUtil.checkList(query.list(), TaskInstance.class);
+ }
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't get task instances by token '"+tokenId+"'", e);
- }
- return result;
+ throw new JbpmException("couldn't get task instances by token '" + tokenId + "'", e);
+ }
}
-
+
/**
- * get active taskinstances for a given token.
+ * get active task instances for a given process instance.
*/
- public List findTaskInstancesByProcessInstance(ProcessInstance processInstance) {
- List result = null;
+ public List<TaskInstance> findTaskInstancesByProcessInstance(ProcessInstance processInstance) {
try {
Query query = session.getNamedQuery("TaskMgmtSession.findTaskInstancesByProcessInstance");
query.setEntity("processInstance", processInstance);
- result = query.list();
- } catch (Exception e) {
+ return CollectionUtil.checkList(query.list(), TaskInstance.class);
+ }
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't get task instances by process instance '"+processInstance+"'", e);
- }
- return result;
+ throw new JbpmException("couldn't get task instances by process instance '"
+ + processInstance
+ + "'", e);
+ }
}
-
/**
* get the task instance for a given task instance-id.
@@ -191,14 +172,15 @@
TaskInstance taskInstance = null;
try {
taskInstance = (TaskInstance) session.load(TaskInstance.class, new Long(taskInstanceId));
- } catch (Exception e) {
+ }
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't get task instance '"+taskInstanceId+"'", e);
- }
+ throw new JbpmException("couldn't get task instance '" + taskInstanceId + "'", e);
+ }
return taskInstance;
}
-
+
/**
* get the task instance for a given task instance-id.
*/
@@ -206,25 +188,32 @@
TaskInstance taskInstance = null;
try {
taskInstance = (TaskInstance) session.get(TaskInstance.class, new Long(taskInstanceId));
- } catch (Exception e) {
+ }
+ catch (Exception e) {
log.error(e);
jbpmSession.handleException();
- throw new JbpmException("couldn't get task instance '"+taskInstanceId+"'", e);
- }
+ throw new JbpmException("couldn't get task instance '" + taskInstanceId + "'", e);
+ }
return taskInstance;
}
-
- public List findTaskInstancesByIds(List taskInstanceIds) {
- List result = null;
- try {
- Query query = session.getNamedQuery("TaskMgmtSession.findTaskInstancesByIds");
- query.setParameterList("taskInstanceIds", taskInstanceIds);
- result = query.list();
- } catch (Exception e) {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't get task instances by ids '"+taskInstanceIds+"'", e);
- }
+
+ public List<TaskInstance> findTaskInstancesByIds(List<Long> taskInstanceIds) {
+ List<TaskInstance> result;
+ if (taskInstanceIds.isEmpty()) {
+ result = Collections.emptyList();
+ }
+ else {
+ try {
+ Query query = session.getNamedQuery("TaskMgmtSession.findTaskInstancesByIds");
+ query.setParameterList("taskInstanceIds", taskInstanceIds);
+ result = CollectionUtil.checkList(query.list(), TaskInstance.class);
+ }
+ catch (Exception e) {
+ log.error(e);
+ jbpmSession.handleException();
+ throw new JbpmException("couldn't get task instances by ids '" + taskInstanceIds + "'", e);
+ }
+ }
return result;
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/compatibility/JbpmSchemaUpdate.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/compatibility/JbpmSchemaUpdate.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/db/compatibility/JbpmSchemaUpdate.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -4,8 +4,11 @@
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.Writer;
import java.sql.Connection;
import java.sql.SQLException;
+import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
@@ -13,215 +16,245 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.hibernate.HibernateException;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.cfg.Settings;
import org.hibernate.connection.ConnectionProvider;
-import org.hibernate.connection.ConnectionProviderFactory;
import org.hibernate.dialect.Dialect;
import org.hibernate.tool.hbm2ddl.DatabaseMetadata;
+import org.hibernate.util.JDBCExceptionReporter;
+import org.hibernate.util.PropertiesHelper;
import org.hibernate.util.ReflectHelper;
/**
- * This is a modified version of the hibernate tools schema update.
- * The modification is to support saving of the update script to a file.
- *
+ * This is a modified version of the hibernate tools schema update. The modification is to support
+ * saving of the update script to a file.
+ *
* @author Christoph Sturm
* @author Koen Aers
*/
public class JbpmSchemaUpdate {
- private static final Log log = LogFactory.getLog(JbpmSchemaUpdate.class);
- private ConnectionProvider connectionProvider;
- private Configuration configuration;
- private Dialect dialect;
- private List exceptions;
+ private Configuration configuration;
+ private Settings settings;
- public JbpmSchemaUpdate(Configuration cfg) throws HibernateException {
- this( cfg, cfg.getProperties() );
- }
+ private File outputFile;
+ private String delimiter;
- public JbpmSchemaUpdate(Configuration cfg, Properties connectionProperties) throws HibernateException {
- this.configuration = cfg;
- dialect = Dialect.getDialect(connectionProperties);
- Properties props = new Properties();
- props.putAll( dialect.getDefaultProperties() );
- props.putAll(connectionProperties);
- connectionProvider = ConnectionProviderFactory.newConnectionProvider(props);
- exceptions = new ArrayList();
- }
+ private final List<Exception> exceptions = new ArrayList<Exception>();
- public JbpmSchemaUpdate(Configuration cfg, Settings settings) throws HibernateException {
- this.configuration = cfg;
- dialect = settings.getDialect();
- connectionProvider = settings.getConnectionProvider();
- exceptions = new ArrayList();
- }
-
- public static void main(String[] args) {
- try {
- Configuration cfg = new Configuration();
+ private static final Log log = LogFactory.getLog(JbpmSchemaUpdate.class);
- boolean script = true;
- // If true then execute db updates, otherwise just generate and display updates
- boolean doUpdate = true;
- String propFile = null;
-
- File out = null;
+ public JbpmSchemaUpdate(Configuration configuration) {
+ this(configuration, configuration.getProperties());
+ }
- for ( int i=0; i<args.length; i++ ) {
- if( args[i].startsWith("--") ) {
- if( args[i].equals("--quiet") ) {
- script = false;
- }
- else if( args[i].startsWith("--properties=") ) {
- propFile = args[i].substring(13);
- }
- else if ( args[i].startsWith("--config=") ) {
- cfg.configure( args[i].substring(9) );
- }
- else if ( args[i].startsWith("--text") ) {
- doUpdate = false;
- }
- else if ( args[i].startsWith("--naming=") ) {
- cfg.setNamingStrategy(
- (NamingStrategy) ReflectHelper.classForName( args[i].substring(9) ).newInstance()
- );
- }
- else if (args[i].startsWith("--output=")) {
- out = new File(args[i].substring(9));
- }
- }
- else {
- cfg.addFile(args[i]);
- }
+ public JbpmSchemaUpdate(Configuration configuration, Properties properties) {
+ Properties copy = (Properties) properties.clone();
+ PropertiesHelper.resolvePlaceHolders(copy);
+ this.configuration = configuration;
+ this.settings = configuration.buildSettings(copy);
+ }
- }
-
- if (propFile!=null) {
- Properties props = new Properties();
- props.putAll( cfg.getProperties() );
- props.load( new FileInputStream(propFile) );
- cfg.setProperties(props);
- }
+ public JbpmSchemaUpdate(Configuration configuration, Settings settings) {
+ this.configuration = configuration;
+ this.settings = settings;
+ }
- new JbpmSchemaUpdate(cfg).execute(script, doUpdate, out);
- }
- catch (Exception e) {
- log.error( "Error running schema update", e );
- }
- }
+ /**
+ * Set an output file. The generated script will be written to this file.
+ */
+ public void setOutputFile(File outputFile) {
+ this.outputFile = outputFile;
+ }
- /**
- * Execute the schema updates
- * @param script print all DDL to the console
- */
- public void execute(boolean script, boolean doUpdate, File out) {
+ public void setDelimiter(String delimiter) {
+ this.delimiter = delimiter;
+ }
- log.info("Running hbm2ddl schema update");
+ public static void main(String[] args) {
+ try {
+ Configuration cfg = new Configuration();
- Connection connection=null;
- Statement stmt=null;
- boolean autoCommitWasEnabled = true;
- FileWriter writer = null;
-
- if (script && out != null) {
- try {
- log.info("Creating filewriter to file : " + out.getAbsolutePath());
- writer = new FileWriter(out);
- } catch (IOException e) {
- log.debug("IOException while creating filewriter");
- log.debug(e);
- }
- }
+ boolean script = true;
+ boolean doUpdate = true;
+ String propFile = null;
+ File out = null;
- exceptions.clear();
+ for (int i = 0; i < args.length; i++) {
+ if (args[i].startsWith("--")) {
+ if (args[i].equals("--quiet")) {
+ script = false;
+ }
+ else if (args[i].startsWith("--properties=")) {
+ propFile = args[i].substring(13);
+ }
+ else if (args[i].startsWith("--config=")) {
+ cfg.configure(args[i].substring(9));
+ }
+ else if (args[i].startsWith("--text")) {
+ doUpdate = false;
+ }
+ else if (args[i].startsWith("--naming=")) {
+ Class<?> clazz = ReflectHelper.classForName(args[i].substring(9));
+ cfg.setNamingStrategy(clazz.asSubclass(NamingStrategy.class).newInstance());
+ }
+ else if (args[i].startsWith("--output=")) {
+ out = new File(args[i].substring(9));
+ }
+ }
+ else {
+ cfg.addFile(args[i]);
+ }
+ }
- try {
+ if (propFile != null) {
+ InputStream inStream = new FileInputStream(propFile);
+ try {
+ Properties props = new Properties();
+ props.load(inStream);
+ cfg.addProperties(props);
+ }
+ finally {
+ inStream.close();
+ }
+ }
- DatabaseMetadata meta;
- try {
- log.info("fetching database metadata");
- connection = connectionProvider.getConnection();
- if ( !connection.getAutoCommit() ) {
- connection.commit();
- connection.setAutoCommit(true);
- autoCommitWasEnabled = false;
- }
- meta = new DatabaseMetadata(connection, dialect);
- stmt = connection.createStatement();
- }
- catch (SQLException sqle) {
- exceptions.add(sqle);
- log.error("could not get database metadata", sqle);
- throw sqle;
- }
+ new JbpmSchemaUpdate(cfg).execute(script, doUpdate, out);
+ }
+ catch (Exception e) {
+ log.error("Error running schema update", e);
+ }
+ }
- log.info("updating schema");
+ /**
+ * Executes the schema update tool.
+ *
+ * @param printScript print DDL statements to the console
+ * @param doUpdate post DDL statements to the database
+ * @param outputFile write DDL statements to this file, can be <code>null</code>
+ */
+ public void execute(boolean printScript, boolean doUpdate, File outputFile) {
+ setOutputFile(outputFile);
+ execute(printScript, doUpdate);
+ }
- String[] createSQL = configuration.generateSchemaUpdateScript(dialect, meta);
- for (int j = 0; j < createSQL.length; j++) {
+ /**
+ * Executes the schema update tool.
+ *
+ * @param printScript print DDL statements to the console
+ * @param doUpdate post DDL statements to the database
+ */
+ public void execute(boolean printScript, boolean doUpdate) {
+ log.info("running schema update");
+ exceptions.clear();
+ try {
+ String[] script = generateScript(doUpdate);
+ if (printScript) {
+ printScript(script);
+ }
+ if (outputFile != null) {
+ writeFile(script);
+ }
+ }
+ catch (SQLException e) {
+ exceptions.add(e);
+ log.error("database connection failed", e);
+ }
+ catch (IOException e) {
+ exceptions.add(e);
+ log.error("could not write file: " + outputFile, e);
+ }
+ }
- final String sql = createSQL[j];
- try {
- if (script) {
- System.out.println(sql);
- if (writer != null) {
- writer.write(sql + ";\n");
- }
- }
- if (doUpdate) {
- log.debug(sql);
- stmt.executeUpdate(sql);
- }
- }
- catch (SQLException e) {
- exceptions.add(e);
- log.error( "Unsuccessful: " + sql );
- log.error( e.getMessage() );
- }
- }
-
- if (writer != null) {
- writer.close();
- }
+ private String[] generateScript(boolean doUpdate) throws SQLException {
+ ConnectionProvider connectionProvider = settings.getConnectionProvider();
+ try {
+ log.info("acquiring a connection");
+ Connection connection = connectionProvider.getConnection();
+ try {
+ if (!connection.getAutoCommit()) {
+ connection.commit();
+ connection.setAutoCommit(true);
+ }
+ log.info("fetching database metadata");
+ Dialect dialect = settings.getDialect();
+ DatabaseMetadata meta = new DatabaseMetadata(connection, dialect);
- log.info("schema update complete");
+ log.info("generating schema update script");
+ String[] script = configuration.generateSchemaUpdateScript(dialect, meta);
- }
- catch (Exception e) {
- exceptions.add(e);
- log.error("could not complete schema update", e);
- }
- finally {
+ if (doUpdate) {
+ log.info("updating schema");
+ doUpdate(script, connection);
+ log.info("schema update complete");
+ }
- try {
- if (stmt!=null) stmt.close();
- if (!autoCommitWasEnabled) connection.setAutoCommit(false);
- if (connection!=null) connection.close();
- if (connectionProvider!=null) connectionProvider.close();
- }
- catch (Exception e) {
- exceptions.add(e);
- log.error("Error closing connection", e);
- }
+ return script;
+ }
+ finally {
+ JDBCExceptionReporter.logAndClearWarnings(connection);
+ connectionProvider.closeConnection(connection);
+ }
+ }
+ finally {
+ connectionProvider.close();
+ }
+ }
- }
- }
+ private void doUpdate(String[] script, Connection connection) throws SQLException {
+ Statement statement = connection.createStatement();
+ try {
+ for (int i = 0; i < script.length; i++) {
+ String sql = script[i];
+ log.debug(sql);
+ try {
+ statement.execute(sql);
+ SQLWarning warning = statement.getWarnings();
+ if (warning != null) {
+ JDBCExceptionReporter.logWarnings(warning);
+ }
+ }
+ catch (SQLException e) {
+ exceptions.add(e);
+ log.error("unsuccessful: " + sql);
+ log.error(e.getMessage());
+ }
+ }
+ }
+ finally {
+ statement.close();
+ }
+ }
- /**
- * Returns a List of all Exceptions which occured during the export.
- * @return A List containig the Exceptions occured during the export
- */
- public List getExceptions() {
- return exceptions;
+ private void printScript(String[] script) {
+ for (int i = 0; i < script.length; i++) {
+ System.out.println(script[i]);
}
-
-}
+ }
+ private void writeFile(String[] script) throws IOException {
+ Writer writer = new FileWriter(outputFile);
+ String lineSeparator = System.getProperty("line.separator");
+ try {
+ for (int i = 0; i < script.length; i++) {
+ writer.write(script[i]);
+ if (delimiter != null)
+ writer.write(delimiter);
+ writer.write(lineSeparator);
+ }
+ }
+ finally {
+ writer.close();
+ }
+ }
-
-
-
-
+ /**
+ * Returns a List of all Exceptions that occurred during the export.
+ *
+ * @return the exceptions that occurred during the export
+ */
+ public List<Exception> getExceptions() {
+ return exceptions;
+ }
+}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/action/ActionTypes.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/action/ActionTypes.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/action/ActionTypes.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -30,6 +30,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.JbpmConfiguration;
+import org.jbpm.graph.def.Action;
import org.jbpm.graph.node.NodeTypes;
import org.jbpm.util.ClassLoaderUtil;
import org.jbpm.util.XmlUtil;
@@ -38,20 +39,20 @@
public class ActionTypes {
- public static Set getActionTypes() {
+ public static Set<Class<? extends Action>> getActionTypes() {
return actionNames.keySet();
}
- public static Set getActionNames() {
+ public static Set<String> getActionNames() {
return actionTypes.keySet();
}
- public static Class getActionType(String name) {
- return (Class) actionTypes.get(name);
+ public static Class<? extends Action> getActionType(String name) {
+ return actionTypes.get(name);
}
- public static String getActionName(Class type) {
- return (String) actionNames.get(type);
+ public static String getActionName(Class<? extends Action> type) {
+ return actionNames.get(type);
}
public static boolean hasActionName(String name) {
@@ -59,24 +60,24 @@
}
static final Log log = LogFactory.getLog(ActionTypes.class);
- static Map actionTypes = initialiseActionTypes();
- static Map actionNames = NodeTypes.createInverseMapping(actionTypes);
+ static Map<String, Class<? extends Action>> actionTypes = initialiseActionTypes();
+ static Map<Class<? extends Action>, String> actionNames = NodeTypes.createInverseMapping(actionTypes);
- static Map initialiseActionTypes() {
- Map types = new HashMap();
+ static Map<String, Class<? extends Action>> initialiseActionTypes() {
+ Map<String, Class<? extends Action>> types = new HashMap<String, Class<? extends Action >>();
String resource = JbpmConfiguration.Configs.getString("resource.action.types");
InputStream actionTypesStream = ClassLoaderUtil.getStream(resource);
Element actionTypesElement = XmlUtil.parseXmlInputStream(actionTypesStream).getDocumentElement();
- Iterator actionTypeIterator = XmlUtil.elementIterator(actionTypesElement, "action-type");
+ Iterator<?> actionTypeIterator = XmlUtil.elementIterator(actionTypesElement, "action-type");
while(actionTypeIterator.hasNext()) {
Element actionTypeElement = (Element) actionTypeIterator.next();
String elementTag = actionTypeElement.getAttribute("element");
String className = actionTypeElement.getAttribute("class");
try {
- Class actionClass = ClassLoaderUtil.getClassLoader().loadClass(className);
- types.put(elementTag, actionClass);
+ Class<?> actionClass = ClassLoaderUtil.getClassLoader().loadClass(className);
+ types.put(elementTag, actionClass.asSubclass(Action.class));
} catch (Exception e) {
// NOTE that Error's are not caught because that might halt the JVM and mask the original Error.
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/action/Script.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/action/Script.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/action/Script.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -23,7 +23,6 @@
import java.util.HashMap;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.Map;
import java.util.Set;
@@ -37,46 +36,47 @@
import org.jbpm.graph.exe.ExecutionContext;
import org.jbpm.graph.exe.Token;
import org.jbpm.jpdl.xml.JpdlXmlReader;
-import org.jbpm.jpdl.xml.Parsable;
+import bsh.EvalError;
import bsh.Interpreter;
+import bsh.ParseException;
import bsh.TargetError;
-public class Script extends Action implements Parsable {
+public class Script extends Action {
private static final long serialVersionUID = 1L;
protected String expression = null;
- protected Set variableAccesses = null;
+ protected Set<VariableAccess> variableAccesses = null;
public void read(Element scriptElement, JpdlXmlReader jpdlReader) {
if (scriptElement.isTextOnly()) {
expression = scriptElement.getText();
} else {
- this.variableAccesses = new HashSet(jpdlReader.readVariableAccesses(scriptElement));
+ this.variableAccesses = new HashSet<VariableAccess>(jpdlReader.readVariableAccesses(scriptElement));
expression = scriptElement.element("expression").getText();
}
}
public void execute(ExecutionContext executionContext) throws Exception {
- Map outputMap = eval(executionContext);
+ Map<String, Object> outputMap = eval(executionContext);
setVariables(outputMap, executionContext);
}
- public Map eval(Token token) throws Exception {
+ public Map<String, Object> eval(Token token) throws DelegationException {
return eval(new ExecutionContext(token));
}
- public Map eval(ExecutionContext executionContext) throws Exception {
- Map inputMap = createInputMap(executionContext);
- Set outputNames = getOutputNames();
+ public Map<String, Object> eval(ExecutionContext executionContext) throws DelegationException {
+ Map<String, Object> inputMap = createInputMap(executionContext);
+ Set<String> outputNames = getOutputNames();
return eval(inputMap, outputNames);
}
- public Map createInputMap(ExecutionContext executionContext) {
+ public Map<String, Object> createInputMap(ExecutionContext executionContext) {
Token token = executionContext.getToken();
- Map inputMap = new HashMap();
+ Map<String, Object> inputMap = new HashMap<String, Object>();
inputMap.put( "executionContext", executionContext );
inputMap.put( "token", token );
inputMap.put( "node", executionContext.getNode() );
@@ -87,22 +87,18 @@
ContextInstance contextInstance = executionContext.getContextInstance();
if (! hasReadableVariable()) {
// we copy all the variableInstances of the context into the interpreter
- Map variables = contextInstance.getVariables(token);
+ Map<String, Object> variables = contextInstance.getVariables(token);
if ( variables != null ) {
- Iterator iter = variables.entrySet().iterator();
- while( iter.hasNext() ) {
- Map.Entry entry = (Map.Entry) iter.next();
- String variableName = (String) entry.getKey();
+ for (Map.Entry<String, Object> entry : variables.entrySet()) {
+ String variableName = entry.getKey();
Object variableValue = entry.getValue();
inputMap.put(variableName, variableValue);
}
}
} else {
- // we only copy the specified variableInstances into the interpreterz
- Iterator iter = variableAccesses.iterator();
- while (iter.hasNext()) {
- VariableAccess variableAccess = (VariableAccess) iter.next();
+ // we only copy the specified variableInstances into the interpreter
+ for (VariableAccess variableAccess : variableAccesses) {
if (variableAccess.isReadable()) {
String variableName = variableAccess.getVariableName();
String mappedName = variableAccess.getMappedName();
@@ -115,54 +111,44 @@
return inputMap;
}
- public Map eval(Map inputMap, Set outputNames) throws Exception {
- Map outputMap = new HashMap();
+ public Map<String, Object> eval(Map<String, Object> inputMap, Set<String> outputNames) throws DelegationException {
+ Map<String, Object> outputMap = new HashMap<String, Object>();
try {
log.debug("script input: "+inputMap);
Interpreter interpreter = new Interpreter();
- Iterator iter = inputMap.keySet().iterator();
- while (iter.hasNext()) {
- String inputName = (String) iter.next();
- Object inputValue = inputMap.get(inputName);
+ for (Map.Entry<String, Object> entry : inputMap.entrySet()) {
+ String inputName = entry.getKey();
+ Object inputValue = entry.getValue();
interpreter.set(inputName, inputValue);
- }
+ }
interpreter.eval(expression);
- iter = outputNames.iterator();
- while (iter.hasNext()) {
- String outputName = (String) iter.next();
+ for (String outputName : outputNames) {
Object outputValue = interpreter.get(outputName);
outputMap.put(outputName, outputValue);
}
log.debug("script output: "+outputMap);
+ } catch (ParseException e) {
+ throw new DelegationException("parse error occurred", e);
} catch (TargetError e) {
- throw new DelegationException("script evaluation exception", e.getTarget());
- } catch (Exception e) {
+ throw new DelegationException("script threw exception", e.getTarget());
+ } catch (EvalError e) {
log.warn("exception during evaluation of script expression", e);
- // try to throw the cause of the EvalError
- if (e.getCause() instanceof Exception) {
- throw (Exception) e.getCause();
- } else if (e.getCause() instanceof Error) {
- throw (Error) e.getCause();
- } else {
- throw e;
- }
+ throw new DelegationException("script evaluation failed", e);
}
return outputMap;
}
public void addVariableAccess(VariableAccess variableAccess) {
- if (variableAccesses==null) variableAccesses = new HashSet();
+ if (variableAccesses==null) variableAccesses = new HashSet<VariableAccess>();
variableAccesses.add(variableAccess);
}
- Set getOutputNames() {
- Set outputNames = new HashSet();
+ Set<String> getOutputNames() {
+ Set<String> outputNames = new HashSet<String>();
if (variableAccesses!=null) {
- Iterator iter = variableAccesses.iterator();
- while (iter.hasNext()) {
- VariableAccess variableAccess = (VariableAccess) iter.next();
+ for (VariableAccess variableAccess : variableAccesses) {
if (variableAccess.isWritable()) {
outputNames.add(variableAccess.getMappedName());
}
@@ -173,9 +159,7 @@
boolean hasReadableVariable() {
if (variableAccesses==null) return false;
- Iterator iter = variableAccesses.iterator();
- while (iter.hasNext()) {
- VariableAccess variableAccess = (VariableAccess) iter.next();
+ for (VariableAccess variableAccess : variableAccesses) {
if (variableAccess.isReadable()) {
return true;
}
@@ -183,32 +167,29 @@
return false;
}
- void setVariables(Map outputMap, ExecutionContext executionContext) {
+ void setVariables(Map<String, Object> outputMap, ExecutionContext executionContext) {
if ( (outputMap!=null)
&& (!outputMap.isEmpty())
&& (executionContext!=null)
) {
- Map variableNames = getVariableNames();
+ Map<String, String> variableNames = getVariableNames();
ContextInstance contextInstance = executionContext.getContextInstance();
Token token = executionContext.getToken();
- Iterator iter = outputMap.keySet().iterator();
- while (iter.hasNext()) {
- String mappedName = (String) iter.next();
- String variableName = (String) variableNames.get(mappedName);
+ for (Map.Entry<String, String> entry : variableNames.entrySet()) {
+ String mappedName = entry.getKey();
+ String variableName = entry.getValue();
contextInstance.setVariable(variableName, outputMap.get(mappedName), token);
}
}
}
- Map getVariableNames() {
- Map variableNames = new HashMap();
- Iterator iter = variableAccesses.iterator();
- while (iter.hasNext()) {
- VariableAccess variableAccess = (VariableAccess) iter.next();
+ Map<String, String> getVariableNames() {
+ Map<String, String> variableNames = new HashMap<String, String>();
+ for (VariableAccess variableAccess : variableAccesses) {
if (variableAccess.isWritable()) {
variableNames.put(variableAccess.getMappedName(), variableAccess.getVariableName());
- }
+ }
}
return variableNames;
}
@@ -219,10 +200,10 @@
public void setExpression(String expression) {
this.expression = expression;
}
- public Set getVariableAccesses() {
+ public Set<VariableAccess> getVariableAccesses() {
return variableAccesses;
}
- public void setVariableAccesses(Set variableAccesses) {
+ public void setVariableAccesses(Set<VariableAccess> variableAccesses) {
this.variableAccesses = variableAccesses;
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/Action.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/Action.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/Action.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -31,7 +31,6 @@
import org.jbpm.jpdl.el.impl.JbpmExpressionEvaluator;
import org.jbpm.jpdl.xml.JpdlXmlReader;
import org.jbpm.jpdl.xml.Parsable;
-import org.jbpm.util.ClassLoaderUtil;
import org.jbpm.util.EqualsUtil;
public class Action implements ActionHandler, Parsable, Serializable {
@@ -137,7 +136,7 @@
// if the process definition is already set
if (processDefinition!=null) {
// update the process definition action map
- Map actionMap = processDefinition.getActions();
+ Map<String, Action> actionMap = processDefinition.getActions();
// the != string comparison is to avoid null pointer checks. it is no problem if the body is executed a few times too much :-)
if ( (this.name != name)
&& (actionMap!=null) ) {
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/Event.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/Event.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/Event.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -52,7 +52,7 @@
long id = 0;
protected String eventType = null;
protected GraphElement graphElement = null;
- protected List actions = null;
+ protected List<Action> actions = null;
// constructors /////////////////////////////////////////////////////////////
@@ -74,7 +74,7 @@
* is the list of actions associated to this event.
* @return an empty list if no actions are associated.
*/
- public List getActions() {
+ public List<Action> getActions() {
return actions;
}
@@ -85,7 +85,7 @@
public Action addAction(Action action) {
if (action==null) throw new IllegalArgumentException("can't add a null action to an event");
- if (actions==null) actions = new ArrayList();
+ if (actions==null) actions = new ArrayList<Action>();
actions.add(action);
action.event = this;
return action;
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/ExceptionHandler.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/ExceptionHandler.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/ExceptionHandler.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -23,7 +23,6 @@
import java.io.Serializable;
import java.util.ArrayList;
-import java.util.Iterator;
import java.util.List;
import org.jbpm.graph.exe.ExecutionContext;
@@ -36,7 +35,7 @@
long id = 0;
protected String exceptionClassName = null;
protected GraphElement graphElement = null;
- protected List actions = null;
+ protected List<Action> actions = null;
public ExceptionHandler() {
}
@@ -44,7 +43,7 @@
public boolean matches( Throwable exception ) {
boolean matches = true;
if (exceptionClassName!=null) {
- Class clazz = ClassLoaderUtil.loadClass(exceptionClassName);
+ Class<?> clazz = ClassLoaderUtil.loadClass(exceptionClassName);
if (! clazz.isAssignableFrom(exception.getClass())) {
matches = false;
}
@@ -54,9 +53,7 @@
public void handleException(GraphElement graphElement, ExecutionContext executionContext) throws Exception {
if (actions!=null) {
- Iterator iter = actions.iterator();
- while (iter.hasNext()) {
- Action action = (Action) iter.next();
+ for (Action action : actions) {
graphElement.executeAction(action, executionContext);
}
}
@@ -64,12 +61,12 @@
// actions
/////////////////////////////////////////////////////////////////////////////
- public List getActions() {
+ public List<Action> getActions() {
return actions;
}
public void addAction(Action action) {
- if (actions==null) actions = new ArrayList();
+ if (actions==null) actions = new ArrayList<Action>();
actions.add(action);
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/GraphElement.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/GraphElement.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/GraphElement.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -25,7 +25,6 @@
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -54,8 +53,8 @@
protected String name = null;
protected String description = null;
protected ProcessDefinition processDefinition = null;
- protected Map events = null;
- protected List exceptionHandlers = null;
+ protected Map<String, Event> events = null;
+ protected List<ExceptionHandler> exceptionHandlers = null;
public GraphElement() {
}
@@ -76,7 +75,7 @@
/**
* gets the events, keyd by eventType (java.lang.String).
*/
- public Map getEvents() {
+ public Map<String, Event> getEvents() {
return events;
}
@@ -87,7 +86,7 @@
public Event getEvent(String eventType) {
Event event = null;
if (events != null) {
- event = (Event) events.get(eventType);
+ event = events.get(eventType);
}
return event;
}
@@ -108,7 +107,7 @@
throw new IllegalArgumentException("can't add an event without type to graph element");
}
if (events == null) {
- events = new HashMap();
+ events = new HashMap<String, Event>();
}
events.put(event.getEventType(), event);
event.graphElement = this;
@@ -124,7 +123,7 @@
throw new IllegalArgumentException("can't remove an event without type from graph element");
}
if (events != null) {
- removedEvent = (Event) events.remove(event.getEventType());
+ removedEvent = events.remove(event.getEventType());
if (removedEvent != null) {
event.graphElement = null;
}
@@ -137,7 +136,7 @@
/**
* is the list of exception handlers associated to this graph element.
*/
- public List getExceptionHandlers() {
+ public List<ExceptionHandler> getExceptionHandlers() {
return exceptionHandlers;
}
@@ -146,7 +145,7 @@
throw new IllegalArgumentException("can't add null exceptionHandler to graph element");
}
if (exceptionHandlers == null) {
- exceptionHandlers = new ArrayList();
+ exceptionHandlers = new ArrayList<ExceptionHandler>();
}
exceptionHandlers.add(exceptionHandler);
exceptionHandler.graphElement = this;
@@ -166,7 +165,7 @@
if ((exceptionHandlers != null)
&& (Math.min(oldIndex, newIndex) >= 0)
&& (Math.max(oldIndex, newIndex) < exceptionHandlers.size())) {
- Object o = exceptionHandlers.remove(oldIndex);
+ ExceptionHandler o = exceptionHandlers.remove(oldIndex);
exceptionHandlers.add(newIndex, o);
} else {
throw new IndexOutOfBoundsException("couldn't reorder element from index '" + oldIndex
@@ -214,7 +213,7 @@
}
// execute the runtime actions
- List runtimeActions = getRuntimeActionsForEvent(executionContext, eventType);
+ List<Action> runtimeActions = getRuntimeActionsForEvent(executionContext, eventType);
executeActions(runtimeActions, executionContext, isPropagated);
// remove the event from the context
@@ -227,11 +226,9 @@
}
}
- void executeActions(List actions, ExecutionContext executionContext, boolean isPropagated) {
+ void executeActions(List<Action> actions, ExecutionContext executionContext, boolean isPropagated) {
if (actions != null) {
- Iterator iter = actions.iterator();
- while (iter.hasNext()) {
- Action action = (Action) iter.next();
+ for (Action action : actions) {
if (action.acceptsPropagatedEvents() || (!isPropagated)) {
if (action.isAsync()) {
ExecuteActionJob job = createAsyncActionExecutionJob(executionContext.getToken(), action);
@@ -305,24 +302,22 @@
}
}
- List getRuntimeActionsForEvent(ExecutionContext executionContext, String eventType) {
- List runtimeActionsForEvent = null;
- List runtimeActions = executionContext.getProcessInstance().getRuntimeActions();
+ List<Action> getRuntimeActionsForEvent(ExecutionContext executionContext, String eventType) {
+ List<Action> actionsForEvent = null;
+ List<RuntimeAction> runtimeActions = executionContext.getProcessInstance().getRuntimeActions();
if (runtimeActions != null) {
- Iterator iter = runtimeActions.iterator();
- while (iter.hasNext()) {
- RuntimeAction runtimeAction = (RuntimeAction) iter.next();
+ for (RuntimeAction runtimeAction : runtimeActions) {
// if the runtime-action action is registered on this element and this eventType
if ((this.equals(runtimeAction.getGraphElement()))
&& (eventType.equals(runtimeAction.getEventType()))) {
// ... add its action to the list of runtime actions
- if (runtimeActionsForEvent == null)
- runtimeActionsForEvent = new ArrayList();
- runtimeActionsForEvent.add(runtimeAction.getAction());
- }
+ if (actionsForEvent == null)
+ actionsForEvent = new ArrayList<Action>();
+ actionsForEvent.add(runtimeAction.getAction());
+ }
}
}
- return runtimeActionsForEvent;
+ return actionsForEvent;
}
/*
@@ -426,12 +421,10 @@
ExceptionHandler exceptionHandler = null;
if (exceptionHandlers != null) {
- Iterator iter = exceptionHandlers.iterator();
- while (iter.hasNext() && (exceptionHandler == null)) {
- ExceptionHandler candidate = (ExceptionHandler) iter.next();
+ for (ExceptionHandler candidate : exceptionHandlers) {
if (candidate.matches(exception)) {
exceptionHandler = candidate;
- }
+ }
}
}
@@ -445,8 +438,8 @@
/**
* @return all the parents of this graph element ordered by age.
*/
- public List getParents() {
- List parents = new ArrayList();
+ public List<GraphElement> getParents() {
+ List<GraphElement> parents = new ArrayList<GraphElement>();
GraphElement parent = getParent();
if (parent != null) {
parent.addParentChain(parents);
@@ -457,13 +450,13 @@
/**
* @return this graph element plus all the parents ordered by age.
*/
- public List getParentChain() {
- List parents = new ArrayList();
+ public List<GraphElement> getParentChain() {
+ List<GraphElement> parents = new ArrayList<GraphElement>();
this.addParentChain(parents);
return parents;
}
- void addParentChain(List parentChain) {
+ void addParentChain(List<GraphElement> parentChain) {
parentChain.add(this);
GraphElement parent = getParent();
if (parent != null) {
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/Node.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/Node.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/Node.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -25,7 +25,6 @@
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
@@ -52,7 +51,7 @@
public enum NodeType { Node, StartState, EndState, State, Task, Fork, Join, Decision };
protected List<Transition> leavingTransitions = null;
- transient Map leavingTransitionMap = null;
+ transient Map<String, Transition> leavingTransitionMap = null;
protected Set<Transition> arrivingTransitions = null;
protected Action action = null;
protected SuperState superState = null;
@@ -135,16 +134,16 @@
/**
* are the leaving {@link Transition}s, mapped by their name (java.lang.String).
*/
- public Map getLeavingTransitionsMap()
+ public Map<String, Transition> getLeavingTransitionsMap()
{
if ((leavingTransitionMap == null) && (leavingTransitions != null))
{
// initialize the cached leaving transition map
- leavingTransitionMap = new HashMap();
- ListIterator iter = leavingTransitions.listIterator(leavingTransitions.size());
+ leavingTransitionMap = new HashMap<String, Transition>();
+ ListIterator<Transition> iter = leavingTransitions.listIterator(leavingTransitions.size());
while (iter.hasPrevious())
{
- Transition leavingTransition = (Transition)iter.previous();
+ Transition leavingTransition = iter.previous();
leavingTransitionMap.put(leavingTransition.getName(), leavingTransition);
}
}
@@ -161,7 +160,7 @@
if (leavingTransition == null)
throw new IllegalArgumentException("can't add a null leaving transition to an node");
if (leavingTransitions == null)
- leavingTransitions = new ArrayList();
+ leavingTransitions = new ArrayList<Transition>();
leavingTransitions.add(leavingTransition);
leavingTransition.from = this;
leavingTransitionMap = null;
@@ -208,7 +207,7 @@
Transition transition = null;
if (leavingTransitions != null)
{
- transition = (Transition)getLeavingTransitionsMap().get(transitionName);
+ transition = getLeavingTransitionsMap().get(transitionName);
}
if ((transition == null) && (superState != null))
{
@@ -241,19 +240,18 @@
return name;
}
- boolean containsName(List leavingTransitions, String name)
+ boolean containsName(List<Transition> leavingTransitions, String name)
{
- Iterator iter = leavingTransitions.iterator();
- while (iter.hasNext())
- {
- Transition transition = (Transition)iter.next();
- if ((name == null) && (transition.getName() == null))
- {
- return true;
+ if (name != null) {
+ for (Transition transition : leavingTransitions) {
+ if (name.equals(transition.getName()))
+ return true;
}
- else if ((name != null) && (name.equals(transition.getName())))
- {
- return true;
+ }
+ else {
+ for (Transition transition : leavingTransitions) {
+ if (transition.getName() == null)
+ return true;
}
}
return false;
@@ -318,7 +316,7 @@
if (arrivingTransition == null)
throw new IllegalArgumentException("can't add a null arrivingTransition to a node");
if (arrivingTransitions == null)
- arrivingTransitions = new HashSet();
+ arrivingTransitions = new HashSet<Transition>();
arrivingTransitions.add(arrivingTransition);
arrivingTransition.to = this;
return arrivingTransition;
@@ -512,7 +510,7 @@
throw new IllegalArgumentException("couldn't set name '" + name + "' on node '" + this
+ "'cause the superState of this node has already another child node with the same name");
}
- Map nodes = superState.getNodesMap();
+ Map<String, Node> nodes = superState.getNodesMap();
nodes.remove(oldName);
nodes.put(name, this);
}
@@ -523,7 +521,7 @@
throw new IllegalArgumentException("couldn't set name '" + name + "' on node '" + this
+ "'cause the process definition of this node has already another node with the same name");
}
- Map nodeMap = processDefinition.getNodesMap();
+ Map<String, Node> nodeMap = processDefinition.getNodesMap();
nodeMap.remove(oldName);
nodeMap.put(name, this);
}
@@ -564,7 +562,7 @@
}
/** returns a list of child nodes (only applicable for {@link SuperState})s. */
- public List getNodes()
+ public List<Node> getNodes()
{
return null;
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/NodeCollection.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/NodeCollection.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/NodeCollection.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -32,13 +32,13 @@
/**
* is the ordered list of nodes.
*/
- List getNodes();
+ List<Node> getNodes();
/**
* maps node-names to nodes. returns an empty map if
* no nodes are contained.
*/
- Map getNodesMap();
+ Map<String, Node> getNodesMap();
/**
* retrieves a node by name.
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/ProcessDefinition.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/ProcessDefinition.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/ProcessDefinition.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -28,7 +28,6 @@
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
@@ -58,9 +57,9 @@
protected boolean isTerminationImplicit = false;
protected Node startState = null;
protected List<Node> nodes = null;
- transient Map nodesMap = null;
- protected Map actions = null;
- protected Map definitions = null;
+ transient Map<String, Node> nodesMap = null;
+ protected Map<String, Action> actions = null;
+ protected Map<String, ModuleDefinition> definitions = null;
// event types //////////////////////////////////////////////////////////////
@@ -98,16 +97,15 @@
// now add all the default modules that are configured in the file jbpm.default.modules
String resource = JbpmConfiguration.Configs.getString("resource.default.modules");
Properties defaultModulesProperties = ClassLoaderUtil.getProperties(resource);
- Iterator iter = defaultModulesProperties.keySet().iterator();
- while (iter.hasNext()) {
- String moduleClassName = (String) iter.next();
+ for (Object key : defaultModulesProperties.keySet()) {
+ String moduleClassName = (String) key;
try {
ModuleDefinition moduleDefinition = (ModuleDefinition) ClassLoaderUtil.loadClass(moduleClassName).newInstance();
processDefinition.addDefinition(moduleDefinition);
} catch (Exception e) {
throw new JbpmException("couldn't instantiate default module '"+moduleClassName+"'", e);
- }
+ }
}
return processDefinition;
}
@@ -126,11 +124,11 @@
return new ProcessInstance(this);
}
- public ProcessInstance createProcessInstance(Map variables) {
+ public ProcessInstance createProcessInstance(Map<String, Object> variables) {
return new ProcessInstance(this, variables, null);
}
- public ProcessInstance createProcessInstance(Map variables, String businessKey) {
+ public ProcessInstance createProcessInstance(Map<String, Object> variables, String businessKey) {
return new ProcessInstance(this, variables, businessKey);
}
@@ -207,13 +205,11 @@
}
// javadoc description in NodeCollection
- public Map getNodesMap() {
+ public Map<String, Node> getNodesMap() {
if (nodesMap==null) {
- nodesMap = new HashMap();
+ nodesMap = new HashMap<String, Node>();
if (nodes!=null) {
- Iterator iter = nodes.iterator();
- while (iter.hasNext()) {
- Node node = (Node) iter.next();
+ for (Node node : nodes) {
nodesMap.put(node.getName(),node);
}
}
@@ -224,7 +220,7 @@
// javadoc description in NodeCollection
public Node getNode(String name) {
if (nodes==null) return null;
- return (Node) getNodesMap().get(name);
+ return getNodesMap().get(name);
}
// javadoc description in NodeCollection
@@ -236,7 +232,7 @@
// javadoc description in NodeCollection
public Node addNode(Node node) {
if (node == null) throw new IllegalArgumentException("can't add a null node to a processdefinition");
- if (nodes == null) nodes = new ArrayList();
+ if (nodes == null) nodes = new ArrayList<Node>();
nodes.add(node);
node.processDefinition = this;
nodesMap = null;
@@ -289,7 +285,7 @@
return findNode(this, hierarchicalName);
}
- public static String generateNodeName(List nodes) {
+ public static String generateNodeName(List<Node> nodes) {
String name = null;
if (nodes==null) {
name = "1";
@@ -301,10 +297,8 @@
return name;
}
- static boolean containsName(List nodes, String name) {
- Iterator iter = nodes.iterator();
- while (iter.hasNext()) {
- Node node = (Node) iter.next();
+ static boolean containsName(List<Node> nodes, String name) {
+ for (Node node : nodes) {
if ( name.equals(node.getName()) ) {
return true;
}
@@ -363,7 +357,7 @@
public Action addAction(Action action) {
if (action == null) throw new IllegalArgumentException("can't add a null action to an process definition");
if (action.getName() == null) throw new IllegalArgumentException("can't add an unnamed action to an process definition");
- if (actions == null) actions = new HashMap();
+ if (actions == null) actions = new HashMap<String, Action>();
actions.put(action.getName(), action);
action.processDefinition = this;
return action;
@@ -386,10 +380,10 @@
public Action getAction(String name) {
if (actions == null) return null;
- return (Action) actions.get(name);
+ return actions.get(name);
}
- public Map getActions() {
+ public Map<String, Action> getActions() {
return actions;
}
@@ -407,7 +401,7 @@
public ModuleDefinition addDefinition(ModuleDefinition moduleDefinition) {
if (moduleDefinition == null) throw new IllegalArgumentException("can't add a null moduleDefinition to a process definition");
if (definitions == null)
- definitions = new HashMap();
+ definitions = new HashMap<String, ModuleDefinition>();
definitions.put(moduleDefinition.getClass().getName(), moduleDefinition);
moduleDefinition.setProcessDefinition(this);
return moduleDefinition;
@@ -417,7 +411,7 @@
ModuleDefinition removedDefinition = null;
if (moduleDefinition == null) throw new IllegalArgumentException("can't remove a null moduleDefinition from a process definition");
if (definitions != null) {
- removedDefinition = (ModuleDefinition) definitions.remove(moduleDefinition.getClass().getName());
+ removedDefinition = definitions.remove(moduleDefinition.getClass().getName());
if (removedDefinition!=null) {
moduleDefinition.setProcessDefinition(null);
}
@@ -425,30 +419,30 @@
return removedDefinition;
}
- public ModuleDefinition getDefinition(Class clazz) {
- ModuleDefinition moduleDefinition = null;
+ public <D extends ModuleDefinition> D getDefinition(Class<D> clazz) {
+ D moduleDefinition = null;
if (definitions != null) {
- moduleDefinition = (ModuleDefinition) definitions.get(clazz.getName());
+ moduleDefinition = clazz.cast(definitions.get(clazz.getName()));
}
return moduleDefinition;
}
public ContextDefinition getContextDefinition() {
- return (ContextDefinition) getDefinition(ContextDefinition.class);
+ return getDefinition(ContextDefinition.class);
}
public FileDefinition getFileDefinition() {
- return (FileDefinition) getDefinition(FileDefinition.class);
+ return getDefinition(FileDefinition.class);
}
public TaskMgmtDefinition getTaskMgmtDefinition() {
- return (TaskMgmtDefinition) getDefinition(TaskMgmtDefinition.class);
+ return getDefinition(TaskMgmtDefinition.class);
}
- public Map getDefinitions() {
+ public Map<String, ModuleDefinition> getDefinitions() {
return definitions;
}
- public void setDefinitions(Map definitions) {
+ public void setDefinitions(Map<String, ModuleDefinition> definitions) {
this.definitions = definitions;
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/SuperState.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/SuperState.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/SuperState.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -23,7 +23,6 @@
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -31,18 +30,17 @@
import org.jbpm.JbpmException;
import org.jbpm.graph.exe.ExecutionContext;
import org.jbpm.jpdl.xml.JpdlXmlReader;
-import org.jbpm.jpdl.xml.Parsable;
/**
* brings hierarchy into the elements of a process definition by creating a
* parent-child relation between {@link GraphElement}s.
*/
-public class SuperState extends Node implements Parsable, NodeCollection {
+public class SuperState extends Node implements NodeCollection {
private static final long serialVersionUID = 1L;
- protected List nodes = null;
- transient Map nodesMap = null;
+ protected List<Node> nodes = null;
+ transient Map<String, Node> nodesMap = null;
public SuperState() {
}
@@ -86,25 +84,23 @@
|| (nodes.size()==0) ) {
throw new JbpmException("transition enters superstate +"+this+"' and it there is no first child-node to delegate to");
}
- Node startNode = (Node) nodes.get(0);
+ Node startNode = nodes.get(0);
startNode.enter(executionContext);
}
// nodes ////////////////////////////////////////////////////////////////////
// javadoc description in NodeCollection
- public List getNodes() {
+ public List<Node> getNodes() {
return nodes;
}
// javadoc description in NodeCollection
- public Map getNodesMap() {
+ public Map<String, Node> getNodesMap() {
if ( (nodesMap==null)
&& (nodes!=null) ) {
- nodesMap = new HashMap();
- Iterator iter = nodes.iterator();
- while (iter.hasNext()) {
- Node node = (Node) iter.next();
+ nodesMap = new HashMap<String, Node>();
+ for (Node node : nodes) {
nodesMap.put(node.getName(),node);
}
}
@@ -113,7 +109,7 @@
// javadoc description in NodeCollection
public Node getNode(String name) {
- return (Node) getNodesMap().get(name);
+ return getNodesMap().get(name);
}
@@ -125,7 +121,7 @@
// javadoc description in NodeCollection
public Node addNode(Node node) {
if (node == null) throw new IllegalArgumentException("can't add a null node to a superstate");
- if (nodes == null) nodes = new ArrayList();
+ if (nodes == null) nodes = new ArrayList<Node>();
nodes.add(node);
node.superState = this;
nodesMap = null;
@@ -151,7 +147,7 @@
if ( (nodes!=null)
&& (Math.min(oldIndex, newIndex)>=0)
&& (Math.max(oldIndex, newIndex)<nodes.size()) ) {
- Object o = nodes.remove(oldIndex);
+ Node o = nodes.remove(oldIndex);
nodes.add(newIndex, o);
} else {
throw new IndexOutOfBoundsException("couldn't reorder element from index '"+oldIndex+"' to index '"+newIndex+"' in nodeList '"+nodes+"'");
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/Transition.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/Transition.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/def/Transition.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -23,7 +23,6 @@
import java.util.ArrayList;
import java.util.Collections;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -173,7 +172,7 @@
Node destination = to;
while (destination != null && destination.isSuperStateNode())
{
- List nodes = destination.getNodes();
+ List<Node> nodes = destination.getNodes();
destination = nodes != null && !nodes.isEmpty() ? (Node)nodes.get(0) : null;
}
@@ -187,7 +186,7 @@
if (destination.getSuperState() != null)
{
// collect all the superstates being left
- List leavingSuperStates = collectAllSuperStates(destination, from);
+ List<SuperState> leavingSuperStates = collectAllSuperStates(destination, from);
// reverse the order so that events are fired from outer to inner superstates
Collections.reverse(leavingSuperStates);
// fire a superstate-enter event for all superstates being left
@@ -203,7 +202,7 @@
if (executionContext.getTransitionSource().getSuperState() != null)
{
// collect all the superstates being left
- List leavingSuperStates = collectAllSuperStates(executionContext.getTransitionSource(), to);
+ List<SuperState> leavingSuperStates = collectAllSuperStates(executionContext.getTransitionSource(), to);
// fire a node-leave event for all superstates being left
fireSuperStateEvents(leavingSuperStates, Event.EVENTTYPE_SUPERSTATE_LEAVE, executionContext);
}
@@ -212,10 +211,10 @@
/*
* collect all superstates of a that do not contain node b.
*/
- static List collectAllSuperStates(Node a, Node b)
+ static List<SuperState> collectAllSuperStates(Node a, Node b)
{
SuperState superState = a.getSuperState();
- List leavingSuperStates = new ArrayList();
+ List<SuperState> leavingSuperStates = new ArrayList<SuperState>();
while (superState != null)
{
if (!superState.containsNode(b))
@@ -234,12 +233,9 @@
/*
* fires the give event on all the superstates in the list.
*/
- void fireSuperStateEvents(List superStates, String eventType, ExecutionContext executionContext)
+ void fireSuperStateEvents(List<SuperState> superStates, String eventType, ExecutionContext executionContext)
{
- Iterator iter = superStates.iterator();
- while (iter.hasNext())
- {
- SuperState leavingSuperState = (SuperState)iter.next();
+ for (SuperState leavingSuperState : superStates) {
leavingSuperState.fireEvent(eventType, executionContext);
}
}
@@ -256,7 +252,7 @@
throw new IllegalArgumentException("couldn't set name '" + name + "' on transition '" + this
+ "'cause the from-node of this transition has already another leaving transition with the same name");
}
- Map fromLeavingTransitions = from.getLeavingTransitionsMap();
+ Map<String, Transition> fromLeavingTransitions = from.getLeavingTransitionsMap();
fromLeavingTransitions.remove(this.name);
fromLeavingTransitions.put(name, this);
}
@@ -274,19 +270,12 @@
}
else
{
- List fromParentChain = from.getParentChain();
- List toParentChain = to.getParentChain();
- Iterator fromIter = fromParentChain.iterator();
- while (fromIter.hasNext() && (parent == null))
- {
- GraphElement fromParent = (GraphElement)fromIter.next();
- Iterator toIter = toParentChain.iterator();
- while (toIter.hasNext() && (parent == null))
- {
- GraphElement toParent = (GraphElement)toIter.next();
- if (fromParent == toParent)
- {
+ outerLoop:
+ for (GraphElement fromParent : from.getParentChain()) {
+ for (GraphElement toParent : to.getParentChain()) {
+ if (fromParent == toParent) {
parent = fromParent;
+ break outerLoop;
}
}
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/exe/Execution.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/exe/Execution.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/exe/Execution.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -32,6 +32,8 @@
*/
public class Execution extends ProcessInstance {
+ private static final long serialVersionUID = 1L;
+
public Execution(ProcessDefinition pd) {
super(pd);
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/exe/ExecutionContext.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/exe/ExecutionContext.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/exe/ExecutionContext.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -155,12 +155,12 @@
getNode().leave(this, transition);
}
- public ModuleDefinition getDefinition(Class clazz)
+ public <D extends ModuleDefinition> D getDefinition(Class<D> clazz)
{
return getProcessDefinition().getDefinition(clazz);
}
- public ModuleInstance getInstance(Class clazz)
+ public <I extends ModuleInstance> I getInstance(Class<I> clazz)
{
ProcessInstance processInstance = (token != null ? token.getProcessInstance() : null);
return (processInstance != null ? processInstance.getInstance(clazz) : null);
@@ -168,12 +168,12 @@
public ContextInstance getContextInstance()
{
- return (ContextInstance)getInstance(ContextInstance.class);
+ return getInstance(ContextInstance.class);
}
public TaskMgmtInstance getTaskMgmtInstance()
{
- return (TaskMgmtInstance)getInstance(TaskMgmtInstance.class);
+ return getInstance(TaskMgmtInstance.class);
}
public JbpmContext getJbpmContext()
@@ -286,14 +286,14 @@
// thread local execution context
- static ThreadLocal threadLocalContextStack = new ThreadLocal();
+ static ThreadLocal<Stack<ExecutionContext>> threadLocalContextStack = new ThreadLocal<Stack<ExecutionContext>>();
- static Stack getContextStack()
+ static Stack<ExecutionContext> getContextStack()
{
- Stack stack = (Stack)threadLocalContextStack.get();
+ Stack<ExecutionContext> stack = threadLocalContextStack.get();
if (stack == null)
{
- stack = new Stack();
+ stack = new Stack<ExecutionContext>();
threadLocalContextStack.set(stack);
}
return stack;
@@ -315,10 +315,10 @@
public static ExecutionContext currentExecutionContext()
{
ExecutionContext executionContext = null;
- Stack stack = getContextStack();
+ Stack<ExecutionContext> stack = getContextStack();
if (!stack.isEmpty())
{
- executionContext = (ExecutionContext)stack.peek();
+ executionContext = stack.peek();
}
return executionContext;
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/exe/ProcessInstance.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/exe/ProcessInstance.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/exe/ProcessInstance.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -26,7 +26,6 @@
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -69,11 +68,11 @@
protected Token rootToken;
protected Token superProcessToken;
protected boolean isSuspended;
- protected Map instances;
- protected Map transientInstances;
- protected List runtimeActions;
+ protected Map<String, ModuleInstance> instances;
+ protected Map<String, ModuleInstance> transientInstances;
+ protected List<RuntimeAction> runtimeActions;
/** not persisted */
- protected List cascadeProcessInstances;
+ protected List<ProcessInstance> cascadeProcessInstances;
// constructors /////////////////////////////////////////////////////////////
@@ -104,7 +103,7 @@
* before the process-start event is fired, which is also before the execution of the initial node.
* @throws JbpmException if processDefinition is null.
*/
- public ProcessInstance(ProcessDefinition processDefinition, Map variables)
+ public ProcessInstance(ProcessDefinition processDefinition, Map<String, Object> variables)
{
this(processDefinition, variables, null);
}
@@ -119,7 +118,7 @@
* before the process-start event is fired, which is also before the execution of the initial node.
* @throws JbpmException if processDefinition is null.
*/
- public ProcessInstance(ProcessDefinition processDefinition, Map variables, String key)
+ public ProcessInstance(ProcessDefinition processDefinition, Map<String, Object> variables, String key)
{
if (processDefinition == null)
throw new JbpmException("can't create a process instance when processDefinition is null");
@@ -145,7 +144,7 @@
fireStartEvent(initialNode);
}
- public void addInitialContextVariables(Map variables)
+ public void addInitialContextVariables(Map<String, Object> variables)
{
ContextInstance contextInstance = getContextInstance();
if ((contextInstance != null) && (variables != null))
@@ -156,22 +155,19 @@
public void addInitialModuleDefinitions(ProcessDefinition processDefinition)
{
- Map definitions = processDefinition.getDefinitions();
+ Map<String, ModuleDefinition> definitions = processDefinition.getDefinitions();
// if the state-definition has optional definitions
if (definitions != null)
{
- instances = new HashMap();
+ instances = new HashMap<String, ModuleInstance>();
// loop over each optional definition
- Iterator iter = definitions.values().iterator();
- while (iter.hasNext())
- {
- ModuleDefinition definition = (ModuleDefinition)iter.next();
+ for (ModuleDefinition definition : definitions.values()) {
// and create the corresponding optional instance
ModuleInstance instance = definition.createInstance();
if (instance != null)
{
addInstance(instance);
- }
+ }
}
}
}
@@ -201,7 +197,7 @@
if (moduleInstance == null)
throw new IllegalArgumentException("can't add a null moduleInstance to a process instance");
if (instances == null)
- instances = new HashMap();
+ instances = new HashMap<String, ModuleInstance>();
instances.put(moduleInstance.getClass().getName(), moduleInstance);
moduleInstance.setProcessInstance(this);
return moduleInstance;
@@ -217,7 +213,7 @@
throw new IllegalArgumentException("can't remove a null moduleInstance from a process instance");
if (instances != null)
{
- removedModuleInstance = (ModuleInstance)instances.remove(moduleInstance.getClass().getName());
+ removedModuleInstance = instances.remove(moduleInstance.getClass().getName());
if (removedModuleInstance != null)
{
moduleInstance.setProcessInstance(null);
@@ -229,27 +225,27 @@
/**
* looks up an optional module instance by its class.
*/
- public ModuleInstance getInstance(Class clazz)
+ public <I extends ModuleInstance> I getInstance(Class<I> clazz)
{
- ModuleInstance moduleInstance = null;
+ I moduleInstance = null;
if (instances != null)
{
- moduleInstance = (ModuleInstance)instances.get(clazz.getName());
+ moduleInstance = clazz.cast(instances.get(clazz.getName()));
}
if (moduleInstance == null)
{
if (transientInstances == null)
- transientInstances = new HashMap();
+ transientInstances = new HashMap<String, ModuleInstance>();
// client requested an instance that is not in the map of instances.
// so we can safely assume that the client wants a transient instance
- moduleInstance = (ModuleInstance)transientInstances.get(clazz.getName());
+ moduleInstance = clazz.cast(transientInstances.get(clazz.getName()));
if (moduleInstance == null)
{
try
{
- moduleInstance = (ModuleInstance)clazz.newInstance();
+ moduleInstance = clazz.newInstance();
moduleInstance.setProcessInstance(this);
}
@@ -269,7 +265,7 @@
*/
public ContextInstance getContextInstance()
{
- return (ContextInstance)getInstance(ContextInstance.class);
+ return getInstance(ContextInstance.class);
}
/**
@@ -277,7 +273,7 @@
*/
public TaskMgmtInstance getTaskMgmtInstance()
{
- return (TaskMgmtInstance)getInstance(TaskMgmtInstance.class);
+ return getInstance(TaskMgmtInstance.class);
}
/**
@@ -286,7 +282,7 @@
*/
public LoggingInstance getLoggingInstance()
{
- return (LoggingInstance)getInstance(LoggingInstance.class);
+ return getInstance(LoggingInstance.class);
}
// operations ///////////////////////////////////////////////////////////////
@@ -411,7 +407,7 @@
if (runtimeAction == null)
throw new IllegalArgumentException("can't add a null runtimeAction to a process instance");
if (runtimeActions == null)
- runtimeActions = new ArrayList();
+ runtimeActions = new ArrayList<RuntimeAction>();
runtimeActions.add(runtimeAction);
runtimeAction.processInstance = this;
return runtimeAction;
@@ -439,7 +435,7 @@
/**
* is the list of all runtime actions.
*/
- public List getRuntimeActions()
+ public List<RuntimeAction> getRuntimeActions()
{
return runtimeActions;
}
@@ -481,9 +477,9 @@
/**
* collects all instances for this process instance.
*/
- public List findAllTokens()
+ public List<Token> findAllTokens()
{
- List tokens = new ArrayList();
+ List<Token> tokens = new ArrayList<Token>();
tokens.add(rootToken);
rootToken.collectChildrenRecursively(tokens);
return tokens;
@@ -493,14 +489,14 @@
{
if (cascadeProcessInstances == null)
{
- cascadeProcessInstances = new ArrayList();
+ cascadeProcessInstances = new ArrayList<ProcessInstance>();
}
cascadeProcessInstances.add(cascadeProcessInstance);
}
- public Collection removeCascadeProcessInstances()
+ public Collection<ProcessInstance> removeCascadeProcessInstances()
{
- Collection removed = cascadeProcessInstances;
+ Collection<ProcessInstance> removed = cascadeProcessInstances;
cascadeProcessInstances = null;
return removed;
}
@@ -540,7 +536,7 @@
return end;
}
- public Map getInstances()
+ public Map<String, ModuleInstance> getInstances()
{
return instances;
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/exe/Token.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/exe/Token.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/exe/Token.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -26,7 +26,6 @@
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -73,7 +72,7 @@
protected ProcessInstance processInstance = null;
protected Token parent = null;
protected Map<String,Token> children = null;
- protected List comments = null;
+ protected List<Comment> comments = null;
protected ProcessInstance subProcessInstance = null;
protected int nextLogIndex = 0;
boolean isAbleToReactivateParent = true;
@@ -238,9 +237,9 @@
/**
* a set of all the leaving transitions on the current node for which the condition expression resolves to true.
*/
- public Set getAvailableTransitions()
+ public Set<Transition> getAvailableTransitions()
{
- Set availableTransitions = new HashSet();
+ Set<Transition> availableTransitions = new HashSet<Transition>();
if (node != null)
{
addAvailableTransitionsOfNode(node, availableTransitions);
@@ -252,15 +251,12 @@
* adds available transitions of that node to the Set and after that calls itself recursivly for the SuperSate of the
* Node if it has a super state
*/
- private void addAvailableTransitionsOfNode(Node currentNode, Set availableTransitions)
+ private void addAvailableTransitionsOfNode(Node currentNode, Set<Transition> availableTransitions)
{
- List leavingTransitions = currentNode.getLeavingTransitions();
+ List<Transition> leavingTransitions = currentNode.getLeavingTransitions();
if (leavingTransitions != null)
{
- Iterator iter = leavingTransitions.iterator();
- while (iter.hasNext())
- {
- Transition transition = (Transition)iter.next();
+ for (Transition transition : leavingTransitions) {
String conditionExpression = transition.getCondition();
if (conditionExpression != null)
{
@@ -314,10 +310,7 @@
// end all this token's children
if (children != null)
{
- Iterator iter = children.values().iterator();
- while (iter.hasNext())
- {
- Token child = (Token)iter.next();
+ for (Token child : children.values()) {
if (!child.hasEnded())
{
child.end();
@@ -363,12 +356,12 @@
public void addComment(Comment comment)
{
if (comments == null)
- comments = new ArrayList();
+ comments = new ArrayList<Comment>();
comments.add(comment);
comment.setToken(this);
}
- public List getComments()
+ public List<Comment> getComments()
{
return comments;
}
@@ -386,7 +379,6 @@
}
else
{
-
if (!parent.hasActiveChildren())
{
parent.end();
@@ -404,14 +396,12 @@
// still active (= not ended)
if (children != null)
{
- Iterator iter = children.values().iterator();
- while ((iter.hasNext()) && (!foundActiveChildToken))
- {
- Token child = (Token)iter.next();
+ for (Token child : children.values()) {
if (!child.hasEnded())
{
foundActiveChildToken = true;
- }
+ break;
+ }
}
}
return foundActiveChildToken;
@@ -424,7 +414,7 @@
*/
public void addLog(ProcessLog processLog)
{
- LoggingInstance li = (LoggingInstance)processInstance.getInstance(LoggingInstance.class);
+ LoggingInstance li = processInstance.getLoggingInstance();
if (li != null)
{
processLog.setToken(this);
@@ -438,7 +428,7 @@
*/
public void startCompositeLog(CompositeLog compositeLog)
{
- LoggingInstance li = (LoggingInstance)processInstance.getInstance(LoggingInstance.class);
+ LoggingInstance li = processInstance.getLoggingInstance();
if (li != null)
{
compositeLog.setToken(this);
@@ -451,7 +441,7 @@
*/
public void endCompositeLog()
{
- LoggingInstance li = (LoggingInstance)processInstance.getInstance(LoggingInstance.class);
+ LoggingInstance li = processInstance.getLoggingInstance();
if (li != null)
{
li.endCompositeLog();
@@ -490,7 +480,7 @@
Token child = null;
if (children != null)
{
- child = (Token)children.get(name);
+ child = children.get(name);
}
return child;
}
@@ -504,14 +494,14 @@
return parent.getFullName() + "/" + name;
}
- public List getChildrenAtNode(Node aNode)
+ public List<Token> getChildrenAtNode(Node aNode)
{
- List foundChildren = new ArrayList();
+ List<Token> foundChildren = new ArrayList<Token>();
getChildrenAtNode(aNode, foundChildren);
return foundChildren;
}
- void getChildrenAtNode(Node aNode, List foundTokens)
+ void getChildrenAtNode(Node aNode, List<Token> foundTokens)
{
if (aNode.equals(node))
{
@@ -519,24 +509,19 @@
}
else if (children != null && !children.isEmpty())
{
- for (Iterator it = children.values().iterator(); it.hasNext();)
- {
- Token aChild = (Token)it.next();
- aChild.getChildrenAtNode(aNode, foundTokens);
+ for (Token child : children.values()) {
+ child.getChildrenAtNode(aNode, foundTokens);
}
}
}
- public void collectChildrenRecursively(List tokens)
+ public void collectChildrenRecursively(List<Token> tokens)
{
if (children != null)
{
- Iterator iter = children.values().iterator();
- while (iter.hasNext())
- {
- Token child = (Token)iter.next();
+ for (Token child : children.values()) {
tokens.add(child);
- child.collectChildrenRecursively(tokens);
+ child.collectChildrenRecursively(tokens);
}
}
}
@@ -574,11 +559,11 @@
int slashIndex = path.indexOf('/');
if (slashIndex == -1)
{
- return (Token)(children != null ? children.get(path) : null);
+ return (children != null ? children.get(path) : null);
}
Token token = null;
String name = path.substring(0, slashIndex);
- token = (Token)children.get(name);
+ token = children.get(name);
if (token != null)
{
return token.findToken(path.substring(slashIndex + 1));
@@ -586,19 +571,16 @@
return null;
}
- public Map getActiveChildren()
+ public Map<String, Token> getActiveChildren()
{
- Map activeChildren = new HashMap();
+ Map<String, Token> activeChildren = new HashMap<String, Token>();
if (children != null)
{
- Iterator iter = children.entrySet().iterator();
- while (iter.hasNext())
- {
- Map.Entry entry = (Map.Entry)iter.next();
- Token child = (Token)entry.getValue();
+ for (Map.Entry<String, Token> entry : children.entrySet()) {
+ Token child = entry.getValue();
if (!child.hasEnded())
{
- String childName = (String)entry.getKey();
+ String childName = entry.getKey();
activeChildren.put(childName, child);
}
}
@@ -624,7 +606,7 @@
if (end != null)
return true;
- Map leavingTransitions = node.getLeavingTransitionsMap();
+ Map<String, Transition> leavingTransitions = node.getLeavingTransitionsMap();
if ((leavingTransitions != null) && (leavingTransitions.size() > 0))
{
// ok: found a non-terminated token
@@ -632,10 +614,7 @@
}
// loop over all active child tokens
- Iterator iter = getActiveChildren().values().iterator();
- while (iter.hasNext())
- {
- Token child = (Token)iter.next();
+ for (Token child : getActiveChildren().values()) {
if (!child.isTerminatedImplicitly())
{
return false;
@@ -663,11 +642,8 @@
// propagate to child tokens
if (children != null)
{
- Iterator iter = children.values().iterator();
- while (iter.hasNext())
- {
- Token child = (Token)iter.next();
- child.suspend();
+ for (Token child : children.values()) {
+ child.suspend();
}
}
}
@@ -704,11 +680,8 @@
// propagate to child tokens
if (children != null)
{
- Iterator iter = children.values().iterator();
- while (iter.hasNext())
- {
- Token child = (Token)iter.next();
- child.resume();
+ for (Token child : children.values()) {
+ child.resume();
}
}
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/Decision.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/Decision.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/Decision.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -21,7 +21,6 @@
*/
package org.jbpm.graph.node;
-import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
@@ -35,19 +34,17 @@
import org.jbpm.instantiation.Delegation;
import org.jbpm.jpdl.el.impl.JbpmExpressionEvaluator;
import org.jbpm.jpdl.xml.JpdlXmlReader;
-import org.jbpm.jpdl.xml.Parsable;
-import org.jbpm.util.ClassLoaderUtil;
/**
* decision node.
*/
-public class Decision extends Node implements Parsable
+public class Decision extends Node
{
static final String NEWLINE = System.getProperty("line.separator");
static final String DECISION_CONDITION_RESULT = "decision_condition_result";
static final long serialVersionUID = 1L;
- List decisionConditions = null;
+ List<DecisionCondition> decisionConditions = null;
Delegation decisionDelegation = null;
String decisionExpression = null;
@@ -127,10 +124,7 @@
else if (decisionConditions != null && !decisionConditions.isEmpty())
{
// backwards compatible mode based on separate DecisionCondition's
- Iterator iter = decisionConditions.iterator();
- while (iter.hasNext() && (transition == null))
- {
- DecisionCondition decisionCondition = (DecisionCondition)iter.next();
+ for (DecisionCondition decisionCondition : decisionConditions) {
Object result = JbpmExpressionEvaluator.evaluate(decisionCondition.getExpression(), executionContext);
if (Boolean.TRUE.equals(result))
{
@@ -139,18 +133,15 @@
if (transition != null)
{
transition.removeConditionEnforcement();
+ break;
}
- }
+ }
}
}
else
{
// new mode based on conditions in the transition itself
- Iterator iter = leavingTransitions.iterator();
- while (iter.hasNext() && (transition == null))
- {
- Transition candidate = (Transition)iter.next();
-
+ for (Transition candidate : leavingTransitions) {
String conditionExpression = candidate.getCondition();
if (conditionExpression != null)
{
@@ -158,6 +149,7 @@
if (Boolean.TRUE.equals(result))
{
transition = candidate;
+ break;
}
}
}
@@ -194,7 +186,7 @@
executionContext.leaveNode(transition);
}
- public List getDecisionConditions()
+ public List<DecisionCondition> getDecisionConditions()
{
return decisionConditions;
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/Fork.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/Fork.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/Fork.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -21,10 +21,8 @@
*/
package org.jbpm.graph.node;
-import java.util.ArrayList;
import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
+import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
@@ -36,7 +34,6 @@
import org.jbpm.graph.exe.ExecutionContext;
import org.jbpm.graph.exe.Token;
import org.jbpm.jpdl.xml.JpdlXmlReader;
-import org.jbpm.jpdl.xml.Parsable;
/**
* specifies configurable fork behaviour.
@@ -60,7 +57,7 @@
* </ul>
* </p>
*/
-public class Fork extends Node implements Parsable {
+public class Fork extends Node {
private static final long serialVersionUID = 1L;
@@ -95,8 +92,7 @@
Token token = executionContext.getToken();
// phase one: collect all the transitionNames
- Collection transitionNames = null;
- List forkedTokens = new ArrayList();
+ Collection<?> transitionNames = null;
// by default, the fork spawns a token for each leaving transition
if (script==null) {
@@ -105,16 +101,11 @@
} else { // a script is specified
// if a script is specified, use that script to calculate the set
// of leaving transitions to be used for forking tokens.
- Map outputMap = null;
- try {
- outputMap = script.eval(token);
- } catch (Exception e) {
- this.raiseException(e, executionContext);
- }
+ Map<String, Object> outputMap = script.eval(token);
if (outputMap.size()==1) {
Object result = outputMap.values().iterator().next();
if (result instanceof Collection) {
- transitionNames = (Collection) result;
+ transitionNames = (Collection<?>) result;
}
}
if (transitionNames==null) {
@@ -129,36 +120,29 @@
// @see also http://jira.jboss.com/jira/browse/JBPM-642
// phase two: create forked tokens for the collected transition names
- Iterator iter = transitionNames.iterator();
- while (iter.hasNext()) {
- String transitionName = (String) iter.next();
- forkedTokens.add(createForkedToken(token, transitionName));
+ Map<String, Token> forkedTokens = new HashMap<String, Token>();
+ for (Object element : transitionNames) {
+ String transitionName = (String) element;
+ Token childToken = createForkedToken(token, transitionName);
+ forkedTokens.put(transitionName, childToken);
}
// phase three: launch child tokens from the fork over the given transitions
- iter = forkedTokens.iterator();
- while( iter.hasNext() ) {
- ForkedToken forkedToken = (ForkedToken) iter.next();
- Token childToken = forkedToken.token;
- String leavingTransitionName = forkedToken.leavingTransitionName;
+ for (Map.Entry<String, Token> forkedToken : forkedTokens.entrySet()) {
+ Token childToken = forkedToken.getValue();
+ String leavingTransitionName = forkedToken.getKey();
ExecutionContext childExecutionContext = new ExecutionContext(childToken);
if (leavingTransitionName!=null) {
leave(childExecutionContext, leavingTransitionName);
} else {
leave(childExecutionContext);
- }
+ }
}
}
- protected ForkedToken createForkedToken(Token parent, String transitionName) {
+ protected Token createForkedToken(Token parent, String transitionName) {
// instantiate the new token
- Token childToken = new Token(parent, getTokenName(parent, transitionName));
-
- // create a forked token
- ForkedToken forkedToken = null;
- forkedToken = new ForkedToken(childToken, transitionName);
-
- return forkedToken;
+ return new Token(parent, getTokenName(parent, transitionName));
}
protected String getTokenName(Token parent, String transitionName) {
@@ -188,14 +172,5 @@
this.script = script;
}
- static class ForkedToken {
- Token token = null;
- String leavingTransitionName = null;
- public ForkedToken(Token token, String leavingTransitionName) {
- this.token = token;
- this.leavingTransitionName = leavingTransitionName;
- }
- }
-
private static Log log = LogFactory.getLog(Fork.class);
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/InterleaveEnd.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/InterleaveEnd.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/InterleaveEnd.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -35,7 +35,7 @@
* Alternatively, the back and done transitions can be specified
* in this interleave handler.
*/
-public class InterleaveEnd extends Node implements Parsable {
+public class InterleaveEnd extends Node {
private static final long serialVersionUID = 1L;
@@ -60,7 +60,7 @@
public void execute(ExecutionContext executionContext) {
Token token = executionContext.getToken();
Node interleaveEndNode = token.getNode();
- Collection transitionNames = getInterleaveStart().retrieveTransitionNames(token);
+ Collection<String> transitionNames = getInterleaveStart().retrieveTransitionNames(token);
// if the set is *not* empty
if ( ! transitionNames.isEmpty() ) {
// go back to the interleave start handler
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/InterleaveStart.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/InterleaveStart.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/InterleaveStart.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -33,39 +33,34 @@
import org.jbpm.graph.exe.ExecutionContext;
import org.jbpm.graph.exe.Token;
import org.jbpm.jpdl.xml.JpdlXmlReader;
-import org.jbpm.jpdl.xml.Parsable;
+import org.jbpm.util.CollectionUtil;
/**
- * is an unordered set of child nodeMap. the path of execution will
- * be given to each node exactly once. the sequence of the child
- * nodeMap will be determined at runtime. this implements the
- * workflow pattern interleved parallel routing.
- *
- * If no script is supplied, the transition names will be sequenced
- * in arbitrary order.
- * If a script is provided, the variable transitionNames contains the
- * available transition names. The returned value has to be one of
- * those transitionNames.
- * Instead of supplying a script, its also possible to subclass this
- * class and override the selectTransition method.
+ * is an unordered set of child nodeMap. the path of execution will be given to each node exactly
+ * once. the sequence of the child nodeMap will be determined at runtime. this implements the
+ * workflow pattern interleved parallel routing. If no script is supplied, the transition names will
+ * be sequenced in arbitrary order. If a script is provided, the variable transitionNames contains
+ * the available transition names. The returned value has to be one of those transitionNames.
+ * Instead of supplying a script, its also possible to subclass this class and override the
+ * selectTransition method.
*/
-public class InterleaveStart extends Node implements Parsable {
-
+public class InterleaveStart extends Node {
+
private static final long serialVersionUID = 1L;
String variableName = "interleave-transition-names";
- Interleaver interleaver = new DefaultInterleaver();
-
+ Interleaver interleaver = new DefaultInterleaver();
+
public interface Interleaver {
- String selectNextTransition(Collection transitionNames);
+ String selectNextTransition(Collection<String> transitionNames);
}
-
+
public class DefaultInterleaver implements Interleaver {
- public String selectNextTransition(Collection transitionNames) {
- return (String) transitionNames.iterator().next();
+ public String selectNextTransition(Collection<String> transitionNames) {
+ return transitionNames.iterator().next();
}
}
-
+
public InterleaveStart() {
}
@@ -75,11 +70,11 @@
public void read(Element element, JpdlXmlReader jpdlReader) {
// TODO
-
+
// just making sure that the context definition is present
// because the interleave node needs the context instance at runtime
ProcessDefinition processDefinition = jpdlReader.getProcessDefinition();
- if (processDefinition.getDefinition(ContextDefinition.class)==null) {
+ if (processDefinition.getDefinition(ContextDefinition.class) == null) {
processDefinition.addDefinition(new ContextDefinition());
}
}
@@ -90,43 +85,45 @@
public void execute(ExecutionContext executionContext) {
Token token = executionContext.getToken();
- Collection transitionNames = retrieveTransitionNames(token);
+ Collection<String> transitionNames = retrieveTransitionNames(token);
// if this is the first time we enter
- if ( transitionNames == null ) {
+ if (transitionNames == null) {
// collect all leaving transition names
- transitionNames = new ArrayList(getTransitionNames(token));
+ transitionNames = new ArrayList<String>(getTransitionNames(token));
}
-
+
// select one of the remaining transition names
String nextTransition = interleaver.selectNextTransition(transitionNames);
// remove it from the remaining transitions
transitionNames.remove(nextTransition);
// store the transition names
- storeTransitionNames(transitionNames,token);
+ storeTransitionNames(transitionNames, token);
// pass the token over the selected transition
token.getNode().leave(executionContext, nextTransition);
}
- protected Collection getTransitionNames(Token token) {
+ protected Collection<String> getTransitionNames(Token token) {
Node node = token.getNode();
return node.getLeavingTransitionsMap().keySet();
}
- protected void storeTransitionNames(Collection transitionNames, Token token) {
- ContextInstance ci = (ContextInstance) token.getProcessInstance().getInstance(ContextInstance.class);
- if (ci==null) throw new JbpmException("an interleave start node requires the availability of a context");
- ci.setVariable(variableName,transitionNames, token);
+ protected void storeTransitionNames(Collection<String> transitionNames, Token token) {
+ ContextInstance ci = token.getProcessInstance().getContextInstance();
+ if (ci == null)
+ throw new JbpmException("an interleave start node requires the availability of a context");
+ ci.setVariable(variableName, transitionNames, token);
}
- public Collection retrieveTransitionNames(Token token) {
- ContextInstance ci = (ContextInstance) token.getProcessInstance().getInstance(ContextInstance.class);
- return (Collection) ci.getVariable(variableName, token);
+ public Collection<String> retrieveTransitionNames(Token token) {
+ ContextInstance ci = token.getProcessInstance().getContextInstance();
+ Collection<?> collection = (Collection<?>) ci.getVariable(variableName, token);
+ return collection != null ? CollectionUtil.checkCollection(collection, String.class) : null;
}
public void removeTransitionNames(Token token) {
- ContextInstance ci = (ContextInstance) token.getProcessInstance().getInstance(ContextInstance.class);
+ ContextInstance ci = token.getProcessInstance().getContextInstance();
ci.setVariable(variableName,null, token);
}
@@ -136,4 +133,5 @@
public void setInterleaver(Interleaver interleaver) {
this.interleaver = interleaver;
}
-}
+
+}
\ No newline at end of file
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/Join.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/Join.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/Join.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -35,14 +35,13 @@
import org.jbpm.graph.exe.ExecutionContext;
import org.jbpm.graph.exe.Token;
import org.jbpm.jpdl.xml.JpdlXmlReader;
-import org.jbpm.jpdl.xml.Parsable;
-public class Join extends Node implements Parsable {
+public class Join extends Node {
private static final long serialVersionUID = 1L;
/**
- * specifies wether what type of hibernate lock should be acquired.
+ * specifies what type of hibernate lock should be acquired.
* null value defaults to LockMode.FORCE
*/
String parentLockMode;
@@ -57,7 +56,7 @@
/**
* a fixed set of concurrent tokens.
*/
- Collection tokenNames = null;
+ Collection<String> tokenNames = null;
/**
* a script that calculates concurrent tokens at runtime.
@@ -154,10 +153,9 @@
// if the result is a collection
if ( result instanceof Collection ) {
// it must be a collection of tokenNames
- Collection runtimeTokenNames = (Collection) result;
+ Collection<?> runtimeTokenNames = (Collection<?>) result;
reactivateParent = mustParentBeReactivated(parentToken, runtimeTokenNames.iterator() );
-
// if it's a boolean...
} else if ( result instanceof Boolean ) {
// the boolean specifies if the parent needs to be reactivated
@@ -169,12 +167,10 @@
int n = 0;
// wheck how many tokens already arrived in the join
- Iterator iter = parentToken.getChildren().values().iterator();
- while ( iter.hasNext() ) {
- Token concurrentToken = (Token)iter.next();
- if (this.equals(concurrentToken.getNode())) {
+ for (Token concurrentToken : parentToken.getChildren().values()) {
+ if (equals(concurrentToken.getNode())) {
n++;
- }
+ }
}
if ( n < nOutOfM ) {
reactivateParent = false;
@@ -191,9 +187,8 @@
if (reactivateParent) {
// write to all child tokens that the parent is already reactivated
- Iterator iter = parentToken.getChildren().values().iterator();
- while ( iter.hasNext() ) {
- ((Token)iter.next()).setAbleToReactivateParent( false );
+ for (Token child : parentToken.getChildren().values()) {
+ child.setAbleToReactivateParent(false);
}
// write to all child tokens that the parent is already reactivated
@@ -204,7 +199,7 @@
}
}
- public boolean mustParentBeReactivated(Token parentToken, Iterator childTokenNameIterator) {
+ public boolean mustParentBeReactivated(Token parentToken, Iterator<?> childTokenNameIterator) {
boolean reactivateParent = true;
while ( (childTokenNameIterator.hasNext())
&& (reactivateParent) ){
@@ -232,10 +227,10 @@
public void setScript(Script script) {
this.script = script;
}
- public Collection getTokenNames() {
+ public Collection<String> getTokenNames() {
return tokenNames;
}
- public void setTokenNames(Collection tokenNames) {
+ public void setTokenNames(Collection<String> tokenNames) {
this.tokenNames = tokenNames;
}
public boolean isDiscriminator() {
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/Merge.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/Merge.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/Merge.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -21,14 +21,15 @@
*/
package org.jbpm.graph.node;
-import java.util.*;
+import java.util.Collection;
-import org.jbpm.graph.def.*;
-import org.jbpm.graph.exe.*;
+import org.jbpm.graph.def.Node;
+import org.jbpm.graph.exe.ExecutionContext;
+import org.jbpm.graph.exe.Token;
/**
- * TODO is the merge node usefull ?
- * i don't think the merge node is usefull because every node has an
+ * TODO is the merge node useful ?
+ * i don't think the merge node is useful because every node has an
* implicit merge in front of it (= multiple transitions can arrive in
* the same node). maybe we should just leave this in for the sake
* of workflow patterns ?
@@ -57,22 +58,18 @@
// this is a synchronizing multi merge
} else {
- Collection concurrentTokens = token.getParent().getChildren().values();
+ Collection<Token> concurrentTokens = token.getParent().getChildren().values();
boolean reactivate = true;
- Iterator iter = concurrentTokens.iterator();
- while ( (iter.hasNext())
- && (reactivate) ) {
- Token concurrentToken = (Token) iter.next();
+ for (Token concurrentToken : concurrentTokens) {
if (! mergeNode.equals(concurrentToken.getNode())) {
reactivate = false;
- }
+ break;
+ }
}
if ( reactivate ) {
- iter = concurrentTokens.iterator();
- while (iter.hasNext()) {
- Token concurrentToken = (Token) iter.next();
- mergeNode.leave(new ExecutionContext(concurrentToken));
+ for (Token concurrentToken : concurrentTokens) {
+ mergeNode.leave(new ExecutionContext(concurrentToken));
}
}
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/NodeTypes.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/NodeTypes.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/NodeTypes.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -30,48 +30,49 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.JbpmConfiguration;
+import org.jbpm.graph.def.Node;
import org.jbpm.util.ClassLoaderUtil;
import org.jbpm.util.XmlUtil;
import org.w3c.dom.Element;
public class NodeTypes {
- public static Set getNodeTypes() {
+ public static Set<String> getNodeTypes() {
return nodeTypes.keySet();
}
- public static Set getNodeNames() {
+ public static Set<Class<? extends Node>> getNodeNames() {
return nodeNames.keySet();
}
- public static Class getNodeType(String name) {
- return (Class) nodeTypes.get(name);
+ public static Class<? extends Node> getNodeType(String name) {
+ return nodeTypes.get(name);
}
- public static String getNodeName(Class type) {
- return (String) nodeNames.get(type);
+ public static String getNodeName(Class<? extends Node> type) {
+ return nodeNames.get(type);
}
private static final Log log = LogFactory.getLog(NodeTypes.class);
- static Map nodeTypes = initialiseNodeTypes();
- static Map nodeNames = createInverseMapping(nodeTypes);
+ static Map<String, Class<? extends Node>> nodeTypes = initialiseNodeTypes();
+ static Map<Class<? extends Node>, String> nodeNames = createInverseMapping(nodeTypes);
- static Map initialiseNodeTypes() {
- Map types = new HashMap();
+ static Map<String, Class<? extends Node>> initialiseNodeTypes() {
+ Map<String, Class<? extends Node>> types = new HashMap<String, Class<? extends Node>>();
String resource = JbpmConfiguration.Configs.getString("resource.node.types");
InputStream actionTypesStream = ClassLoaderUtil.getStream(resource);
Element nodeTypesElement = XmlUtil.parseXmlInputStream(actionTypesStream).getDocumentElement();
- Iterator nodeTypeIterator = XmlUtil.elementIterator(nodeTypesElement, "node-type");
+ Iterator<?> nodeTypeIterator = XmlUtil.elementIterator(nodeTypesElement, "node-type");
while(nodeTypeIterator.hasNext()) {
Element nodeTypeElement = (Element) nodeTypeIterator.next();
String elementTag = nodeTypeElement.getAttribute("element");
String className = nodeTypeElement.getAttribute("class");
try {
- Class nodeClass = ClassLoaderUtil.getClassLoader().loadClass(className);
- types.put(elementTag, nodeClass);
+ Class<?> nodeClass = ClassLoaderUtil.getClassLoader().loadClass(className);
+ types.put(elementTag, nodeClass.asSubclass(Node.class));
} catch (Exception e) {
if (!"org.jboss.seam.jbpm.Page".equals(className)) {
@@ -83,13 +84,11 @@
return types;
}
- public static Map createInverseMapping(Map map) {
- Map names = new HashMap();
- Iterator iter = map.entrySet().iterator();
- while (iter.hasNext()) {
- Map.Entry entry = (Map.Entry) iter.next();
- names.put(entry.getValue(), entry.getKey());
+ public static <K, V> Map<V, K> createInverseMapping(Map<K, V> map) {
+ Map<V, K> inverse = new HashMap<V, K>();
+ for (Map.Entry<K, V> entry : map.entrySet()) {
+ inverse.put(entry.getValue(), entry.getKey());
}
- return names;
+ return inverse;
}
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/ProcessFactory.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/ProcessFactory.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/ProcessFactory.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -75,10 +75,10 @@
name = null;
}
- Class nodeType = NodeTypes.getNodeType(typeName);
+ Class<? extends Node> nodeType = NodeTypes.getNodeType(typeName);
if ( nodeType==null ) throw new IllegalArgumentException("unknown node type name '" + typeName + "'");
try {
- node = (Node) nodeType.newInstance();
+ node = nodeType.newInstance();
node.setName(name);
} catch (Exception e) {
throw new JbpmException("couldn't instantiate nodehandler for type '" + typeName + "'");
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/ProcessState.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/ProcessState.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/ProcessState.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -23,7 +23,6 @@
import java.util.ArrayList;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.List;
import java.util.Set;
@@ -46,10 +45,9 @@
import org.jbpm.graph.log.ProcessStateLog;
import org.jbpm.jpdl.el.impl.JbpmExpressionEvaluator;
import org.jbpm.jpdl.xml.JpdlXmlReader;
-import org.jbpm.jpdl.xml.Parsable;
import org.jbpm.util.Clock;
-public class ProcessState extends Node implements Parsable {
+public class ProcessState extends Node {
private static final long serialVersionUID = 1L;
@@ -60,7 +58,7 @@
}
protected ProcessDefinition subProcessDefinition = null;
- protected Set variableAccesses = null;
+ protected Set<VariableAccess> variableAccesses = null;
protected String subProcessName = null;
// event types //////////////////////////////////////////////////////////////
@@ -110,7 +108,7 @@
log.debug("subprocess for process-state '"+name+"' not yet bound");
}
- this.variableAccesses = new HashSet(jpdlReader.readVariableAccesses(processStateElement));
+ this.variableAccesses = new HashSet<VariableAccess>(jpdlReader.readVariableAccesses(processStateElement));
}
private SubProcessResolver getSubProcessResolver() {
@@ -130,7 +128,7 @@
&& (subProcessName!=null)
) {
SubProcessResolver subProcessResolver = getSubProcessResolver();
- List attributes = new ArrayList();
+ List<FlyweightAttribute> attributes = new ArrayList<FlyweightAttribute>();
String subProcessNameResolved = (String) JbpmExpressionEvaluator.evaluate(subProcessName, executionContext);
if (log.isDebugEnabled()) {
log.debug("SubProcessName after eval: " + subProcessNameResolved);
@@ -156,9 +154,7 @@
subContextInstance.setTransientVariables(superContextInstance.getTransientVariables());
// loop over all the variable accesses
- Iterator iter = variableAccesses.iterator();
- while (iter.hasNext()) {
- VariableAccess variableAccess = (VariableAccess) iter.next();
+ for (VariableAccess variableAccess : variableAccesses) {
// if this variable access is readable
if (variableAccess.isReadable()) {
// the variable is copied from the super process variable name
@@ -192,9 +188,7 @@
ContextInstance subContextInstance = subProcessInstance.getContextInstance();
// loop over all the variable accesses
- Iterator iter = variableAccesses.iterator();
- while (iter.hasNext()) {
- VariableAccess variableAccess = (VariableAccess) iter.next();
+ for (VariableAccess variableAccess : variableAccesses) {
// if this variable access is writable
if (variableAccess.isWritable()) {
// the variable is copied from the sub process mapped name
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/StartState.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/StartState.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/StartState.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -21,8 +21,6 @@
*/
package org.jbpm.graph.node;
-import java.util.Map;
-
import org.dom4j.Element;
import org.jbpm.graph.def.Event;
import org.jbpm.graph.def.Node;
@@ -88,11 +86,4 @@
public Transition addArrivingTransition(Transition t) {
throw new UnsupportedOperationException( "illegal operation : its not possible to add a transition that is arriving in a start state" );
}
-
- public void setArrivingTransitions(Map arrivingTransitions) {
- if ( (arrivingTransitions!=null)
- && (arrivingTransitions.size()>0)) {
- throw new UnsupportedOperationException( "illegal operation : its not possible to set a non-empty map in the arriving transitions of a start state" );
- }
- }
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/TaskNode.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/TaskNode.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/graph/node/TaskNode.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -21,22 +21,29 @@
*/
package org.jbpm.graph.node;
-import java.util.*;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
import org.dom4j.Element;
-import org.jbpm.graph.def.*;
-import org.jbpm.graph.exe.*;
+import org.jbpm.graph.def.Node;
+import org.jbpm.graph.def.Transition;
+import org.jbpm.graph.exe.ExecutionContext;
+import org.jbpm.graph.exe.Token;
import org.jbpm.jpdl.el.impl.JbpmExpressionEvaluator;
-import org.jbpm.jpdl.xml.*;
-import org.jbpm.taskmgmt.def.*;
-import org.jbpm.taskmgmt.exe.*;
+import org.jbpm.jpdl.xml.JpdlXmlReader;
+import org.jbpm.taskmgmt.def.Task;
+import org.jbpm.taskmgmt.exe.TaskInstance;
+import org.jbpm.taskmgmt.exe.TaskMgmtInstance;
/**
* is a node that relates to one or more tasks.
* Property <code>signal</code> specifies how task completion
* triggers continuation of execution.
*/
-public class TaskNode extends Node implements Parsable {
+public class TaskNode extends Node {
private static final long serialVersionUID = 1L;
@@ -103,7 +110,7 @@
}
}
- Set tasks = null;
+ Set<Task> tasks = null;
int signal = SIGNAL_LAST;
boolean createTasks = true;
boolean endTasks = false;
@@ -121,6 +128,7 @@
return NodeType.Task;
}
+ @Override
public void read(Element element, JpdlXmlReader jpdlReader) {
// get the signal
String signalText = element.attributeValue("signal");
@@ -151,7 +159,7 @@
}
public void addTask(Task task) {
- if (tasks==null) tasks = new HashSet();
+ if (tasks==null) tasks = new HashSet<Task>();
tasks.add(task);
task.setTaskNode(this);
}
@@ -166,13 +174,11 @@
// if this tasknode should create instances
if ( (createTasks)
&& (tasks!=null) ) {
- Iterator iter = tasks.iterator();
- while (iter.hasNext()) {
- Task task = (Task) iter.next();
+ for (Task task : tasks) {
executionContext.setTask(task);
if (evaluateTaskCondition(task.getCondition(), executionContext)) {
tmi.createTaskInstance(task, executionContext);
- }
+ }
}
}
@@ -238,18 +244,16 @@
TaskMgmtInstance tmi = getTaskMgmtInstance(token);
boolean isLastToComplete = true;
- Iterator iter = tmi.getTaskInstances().iterator();
- while ( iter.hasNext()
- && (isLastToComplete) ) {
- TaskInstance other = (TaskInstance) iter.next();
+ for (TaskInstance other : tmi.getTaskInstances()) {
if ( (token!=null)
- && (token.equals(other.getToken()))
- && (! other.equals(taskInstance))
- && (other.isSignalling())
- && (!other.hasEnded())
- ) {
+ && (token.equals(other.getToken()))
+ && (! other.equals(taskInstance))
+ && (other.isSignalling())
+ && (!other.hasEnded())
+ ) {
isLastToComplete = false;
- }
+ break;
+ }
}
return isLastToComplete;
@@ -257,11 +261,9 @@
public void removeTaskInstanceSynchronization(Token token) {
TaskMgmtInstance tmi = getTaskMgmtInstance(token);
- Collection taskInstances = tmi.getTaskInstances();
+ Collection<TaskInstance> taskInstances = tmi.getTaskInstances();
if (taskInstances!=null) {
- Iterator iter = taskInstances.iterator();
- while (iter.hasNext()) {
- TaskInstance taskInstance = (TaskInstance) iter.next();
+ for (TaskInstance taskInstance : taskInstances) {
if (token.equals(taskInstance.getToken())) {
// remove signalling
if (taskInstance.isSignalling()) {
@@ -274,8 +276,8 @@
// if this is a non-finished task and all those
// tasks should be finished
if ( (! taskInstance.hasEnded())
- && (endTasks)
- ) {
+ && (endTasks)
+ ) {
if (tasks.contains(taskInstance.getTask())) {
// end this task
taskInstance.end();
@@ -287,7 +289,7 @@
}
TaskMgmtInstance getTaskMgmtInstance(Token token) {
- return (TaskMgmtInstance) token.getProcessInstance().getInstance(TaskMgmtInstance.class);
+ return token.getProcessInstance().getTaskMgmtInstance();
}
// getters and setters
@@ -297,12 +299,10 @@
* is a Map with the tasks, keyed by task-name or an empty map in case
* no tasks are present in this task-node.
*/
- public Map getTasksMap() {
- Map tasksMap = new HashMap();
+ public Map<String, Task> getTasksMap() {
+ Map<String, Task> tasksMap = new HashMap<String, Task>();
if (tasks!=null) {
- Iterator iter = tasks.iterator();
- while (iter.hasNext()) {
- Task task = (Task) iter.next();
+ for (Task task : tasks) {
tasksMap.put(task.getName(), task);
}
}
@@ -314,10 +314,10 @@
* does not exist in this node.
*/
public Task getTask(String taskName) {
- return (Task) getTasksMap().get(taskName);
+ return getTasksMap().get(taskName);
}
- public Set getTasks() {
+ public Set<Task> getTasks() {
return tasks;
}
public int getSignal() {
@@ -338,7 +338,7 @@
public void setSignal(int signal) {
this.signal = signal;
}
- public void setTasks(Set tasks) {
+ public void setTasks(Set<Task> tasks) {
this.tasks = tasks;
}
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/instantiation/BeanInstantiator.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/instantiation/BeanInstantiator.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/instantiation/BeanInstantiator.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -27,7 +27,7 @@
import org.apache.commons.logging.LogFactory;
import org.dom4j.Element;
-public class BeanInstantiator extends FieldInstantiator implements Instantiator {
+public class BeanInstantiator extends FieldInstantiator {
protected void setPropertyValue(Class clazz, Object newInstance, String propertyName, Element propertyElement) {
try {
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/job/executor/JobExecutor.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/job/executor/JobExecutor.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/job/executor/JobExecutor.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -4,10 +4,9 @@
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.Iterator;
+import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -31,54 +30,55 @@
protected int lockMonitorInterval;
protected int lockBufferTime;
- protected Map threads = new HashMap();
+ protected Map<String, Thread> threads = new HashMap<String, Thread>();
protected LockMonitorThread lockMonitorThread;
- protected Map monitoredJobIds = Collections.synchronizedMap(new HashMap());
+ protected Map<String, Long> monitoredJobIds = new Hashtable<String, Long>();
protected boolean isStarted = false;
protected static String hostName;
public synchronized void start() {
- if (! isStarted) {
- log.debug("starting thread group '"+name+"'...");
- for (int i=0; i<nbrOfThreads; i++) {
+ if (!isStarted) {
+ log.debug("starting thread group '" + name + "'...");
+ for (int i = 0; i < nbrOfThreads; i++) {
startThread();
}
- lockMonitorThread = new LockMonitorThread(jbpmConfiguration, lockMonitorInterval, maxLockTime, lockBufferTime);
+ lockMonitorThread = new LockMonitorThread(jbpmConfiguration, lockMonitorInterval,
+ maxLockTime, lockBufferTime);
isStarted = true;
- } else {
- log.debug("ignoring start: thread group '"+name+"' is already started'");
}
+ else {
+ log.debug("ignoring start: thread group '" + name + "' is already started'");
+ }
}
-
+
/**
- * signals to all threads in this job executor to stop. It may be that
- * threads are in the middle of something and they will finish that firts.
- * Use {@link #stopAndJoin()} in case you want a method that blocks until
- * all the threads are actually finished.
- * @return a list of all the stopped threads. In case no threads were stopped
- * an empty list will be returned.
+ * signals to all threads in this job executor to stop. It may be that threads are in the middle
+ * of something and they will finish that first. Use {@link #stopAndJoin()} in case you want a
+ * method that blocks until all the threads are actually finished.
+ *
+ * @return a list of all the stopped threads. In case no threads were stopped an empty list will
+ * be returned.
*/
- public synchronized List stop() {
- List stoppedThreads = new ArrayList(threads.size());
+ public synchronized List<Thread> stop() {
+ List<Thread> stoppedThreads = new ArrayList<Thread>(threads.size());
if (isStarted) {
- log.debug("stopping thread group '"+name+"'...");
- for (int i=0; i<nbrOfThreads; i++) {
+ log.debug("stopping thread group '" + name + "'...");
+ for (int i = 0; i < nbrOfThreads; i++) {
stoppedThreads.add(stopThread());
}
lockMonitorThread.deactivate();
isStarted = false;
- } else {
- log.debug("ignoring stop: thread group '"+name+"' not started");
}
+ else {
+ log.debug("ignoring stop: thread group '" + name + "' not started");
+ }
return stoppedThreads;
}
public void stopAndJoin() throws InterruptedException {
- Iterator iter = stop().iterator();
- while (iter.hasNext()) {
- Thread thread = (Thread) iter.next();
+ for (Thread thread : stop()) {
thread.join();
}
lockMonitorThread.join();
@@ -88,32 +88,34 @@
String threadName = getNextThreadName();
Thread thread = createThread(threadName);
threads.put(threadName, thread);
- log.debug("starting new job executor thread '"+threadName+"'");
+ log.debug("starting new job executor thread '" + threadName + "'");
thread.start();
}
protected Thread createThread(String threadName) {
- return new JobExecutorThread(threadName, this, jbpmConfiguration, idleInterval, maxIdleInterval, maxLockTime, historyMaxSize);
+ return new JobExecutorThread(threadName, this);
}
protected String getNextThreadName() {
- return getThreadName(threads.size()+1);
+ return getThreadName(threads.size() + 1);
}
+
protected String getLastThreadName() {
return getThreadName(threads.size());
}
-
+
private String getThreadName(int index) {
- return name + ":" + getHostName() + ":" + index;
+ return name + ":" + getHostAddress() + ":" + index;
}
- private static String getHostName() {
+ private static String getHostAddress() {
if (hostName == null) {
try {
hostName = InetAddress.getLocalHost().getHostAddress();
- } catch (UnknownHostException e) {
+ }
+ catch (UnknownHostException e) {
hostName = "127.0.0.1";
- }
+ }
}
return hostName;
}
@@ -121,122 +123,137 @@
protected synchronized Thread stopThread() {
String threadName = getLastThreadName();
JobExecutorThread thread = (JobExecutorThread) threads.remove(threadName);
- log.debug("removing job executor thread '"+threadName+"'");
+ log.debug("removing job executor thread '" + threadName + "'");
thread.deactivate();
return thread;
}
- public void setMonitoredJobIds(Map monitoredJobIds) {
- this.monitoredJobIds = monitoredJobIds;
- }
-
- public Set getMonitoredJobIds() {
- return new HashSet(monitoredJobIds.values());
+ public Set<Long> getMonitoredJobIds() {
+ return new HashSet<Long>(monitoredJobIds.values());
}
-
+
public void addMonitoredJobId(String threadName, long jobId) {
monitoredJobIds.put(threadName, new Long(jobId));
}
-
+
public void removeMonitoredJobId(String threadName) {
monitoredJobIds.remove(threadName);
}
- public void setHistoryMaxSize(int historyMaxSize) {
- this.historyMaxSize = historyMaxSize;
- }
-
+ /**
+ * @throws UnsupportedOperationException to prevent invocation
+ * @deprecated <code>monitoredJobIds</code> is an internal control field
+ */
+ public void setMonitoredJobIds(Map<String, Long> monitoredJobIds) {
+ throw new UnsupportedOperationException();
+ }
+
public int getHistoryMaxSize() {
return historyMaxSize;
}
-
- public void setIdleInterval(int idleInterval) {
- this.idleInterval = idleInterval;
+
+ public void setHistoryMaxSize(int historyMaxSize) {
+ this.historyMaxSize = historyMaxSize;
}
-
+
public int getIdleInterval() {
return idleInterval;
}
-
- public void setStarted(boolean isStarted) {
- this.isStarted = isStarted;
+
+ public void setIdleInterval(int idleInterval) {
+ this.idleInterval = idleInterval;
}
-
+
+ /**
+ * Tells whether this job executor has been {@linkplain #start() started}.
+ */
public boolean isStarted() {
return isStarted;
}
-
- public void setJbpmConfiguration(JbpmConfiguration jbpmConfiguration) {
- this.jbpmConfiguration = jbpmConfiguration;
- }
-
+
+ /**
+ * @throws UnsupportedOperationException to prevent invocation
+ * @deprecated <code>isStarted</code> is an internal control field
+ */
+ public void setStarted(boolean isStarted) {
+ throw new UnsupportedOperationException();
+ }
+
public JbpmConfiguration getJbpmConfiguration() {
return jbpmConfiguration;
}
-
- public void setMaxIdleInterval(int maxIdleInterval) {
- this.maxIdleInterval = maxIdleInterval;
- }
-
+
+ public void setJbpmConfiguration(JbpmConfiguration jbpmConfiguration) {
+ this.jbpmConfiguration = jbpmConfiguration;
+ }
+
public int getMaxIdleInterval() {
return maxIdleInterval;
}
-
- public void setName(String name) {
- this.name = name;
+
+ public void setMaxIdleInterval(int maxIdleInterval) {
+ this.maxIdleInterval = maxIdleInterval;
}
-
+
public String getName() {
return name;
}
-
- public void setSize(int nbrOfThreads) {
- this.nbrOfThreads = nbrOfThreads;
+
+ public void setName(String name) {
+ this.name = name;
}
-
+
public int getSize() {
return nbrOfThreads;
}
-
- public void setThreads(Map threads) {
- this.threads = threads;
+
+ public void setSize(int nbrOfThreads) {
+ this.nbrOfThreads = nbrOfThreads;
}
-
- public Map getThreads() {
+
+ public Map<String, Thread> getThreads() {
return threads;
}
-
- public void setMaxLockTime(int maxLockTime) {
- this.maxLockTime = maxLockTime;
+
+ /**
+ * @throws UnsupportedOperationException to prevent invocation
+ * @deprecated <code>thread</code> is an internal control field
+ */
+ public void setThreads(Map<String, Thread> threads) {
+ throw new UnsupportedOperationException();
}
-
+
public int getMaxLockTime() {
return maxLockTime;
}
-
- public void setLockBufferTime(int lockBufferTime) {
- this.lockBufferTime = lockBufferTime;
+
+ public void setMaxLockTime(int maxLockTime) {
+ this.maxLockTime = maxLockTime;
}
-
+
public int getLockBufferTime() {
return lockBufferTime;
}
-
- public void setLockMonitorInterval(int lockMonitorInterval) {
- this.lockMonitorInterval = lockMonitorInterval;
+
+ public void setLockBufferTime(int lockBufferTime) {
+ this.lockBufferTime = lockBufferTime;
}
-
+
public int getLockMonitorInterval() {
return lockMonitorInterval;
}
-
- public void setNbrOfThreads(int nbrOfThreads) {
- this.nbrOfThreads = nbrOfThreads;
+
+ public void setLockMonitorInterval(int lockMonitorInterval) {
+ this.lockMonitorInterval = lockMonitorInterval;
}
-
+
public int getNbrOfThreads() {
return nbrOfThreads;
}
-
+
+ public void setNbrOfThreads(int nbrOfThreads) {
+ this.nbrOfThreads = nbrOfThreads;
+ }
+
private static Log log = LogFactory.getLog(JobExecutor.class);
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/job/executor/JobExecutorServlet.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/job/executor/JobExecutorServlet.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/job/executor/JobExecutorServlet.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -23,8 +23,6 @@
import java.io.IOException;
import java.io.PrintWriter;
-import java.util.Collection;
-import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
@@ -90,10 +88,7 @@
out.println("<html>");
out.println("<body>");
out.println("<h2>JBoss jBPM Scheduler Servlet</h2><hr />");
- Collection threads = jbpmConfiguration.getJobExecutor().getThreads().values();
- Iterator iter = threads.iterator();
- while (iter.hasNext()) {
- Thread thread = (Thread) iter.next();
+ for (Thread thread : jbpmConfiguration.getJobExecutor().getThreads().values()) {
out.println("<h4>"+thread.getName()+"</h4>");
out.println("<b>isAlive</b>:"+thread.isAlive());
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/job/executor/JobExecutorThread.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/job/executor/JobExecutorThread.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/job/executor/JobExecutorThread.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -5,8 +5,6 @@
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
-import java.util.Iterator;
-import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -18,135 +16,141 @@
import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.job.Job;
import org.jbpm.persistence.JbpmPersistenceException;
+import org.jbpm.persistence.db.StaleObjectLogConfigurer;
import org.jbpm.svc.Services;
public class JobExecutorThread extends Thread {
- public JobExecutorThread( String name,
- JobExecutor jobExecutor,
- JbpmConfiguration jbpmConfiguration,
- int idleInterval,
- int maxIdleInterval,
- long maxLockTime,
- int maxHistory
- ) {
+ final JobExecutor jobExecutor;
+ final JbpmConfiguration jbpmConfiguration;
+ final int idleInterval;
+ final int maxIdleInterval;
+ final long maxLockTime;
+
+ int currentIdleInterval;
+ volatile boolean isActive = true;
+
+ public JobExecutorThread(String name, JobExecutor jobExecutor) {
super(name);
this.jobExecutor = jobExecutor;
+ this.jbpmConfiguration = jobExecutor.getJbpmConfiguration();
+ this.idleInterval = jobExecutor.getIdleInterval();
+ this.maxIdleInterval = jobExecutor.getMaxIdleInterval();
+ this.maxLockTime = jobExecutor.getMaxLockTime();
+ }
+
+ public JobExecutorThread(String name, JobExecutor jobExecutor,
+ JbpmConfiguration jbpmConfiguration, int idleInterval, int maxIdleInterval, long maxLockTime,
+ int maxHistory) {
+ super(name);
+ this.jobExecutor = jobExecutor;
this.jbpmConfiguration = jbpmConfiguration;
this.idleInterval = idleInterval;
this.maxIdleInterval = maxIdleInterval;
this.maxLockTime = maxLockTime;
}
- final JobExecutor jobExecutor;
- final JbpmConfiguration jbpmConfiguration;
- final int idleInterval;
- final int maxIdleInterval;
- final long maxLockTime;
-
- int currentIdleInterval;
- volatile boolean isActive = true;
-
public void run() {
currentIdleInterval = idleInterval;
while (isActive) {
try {
- Collection acquiredJobs = acquireJobs();
+ Collection<Job> acquiredJobs = acquireJobs();
- if (! acquiredJobs.isEmpty()) {
- Iterator iter = acquiredJobs.iterator();
- while (iter.hasNext() && isActive) {
- Job job = (Job) iter.next();
+ if (!acquiredJobs.isEmpty()) {
+ for (Job job : acquiredJobs) {
executeJob(job);
+ if (!isActive)
+ break;
}
-
- } else { // no jobs acquired
- if (isActive) {
- long waitPeriod = getWaitPeriod();
- if (waitPeriod>0) {
- synchronized(jobExecutor) {
- jobExecutor.wait(waitPeriod);
- }
+ }
+ else if (isActive) {
+ long waitPeriod = getWaitPeriod();
+ if (waitPeriod > 0) {
+ synchronized (jobExecutor) {
+ jobExecutor.wait(waitPeriod);
}
}
}
-
- // no exception so resetting the currentIdleInterval
+
+ // no exception, resetting the currentIdleInterval
currentIdleInterval = idleInterval;
-
- } catch (InterruptedException e) {
- log.info((isActive? "active" : "inactive")+" job executor thread '"+getName()+"' got interrupted");
- } catch (Exception e) {
- log.error("exception in job executor thread. waiting "+currentIdleInterval+" milliseconds", e);
+ }
+ catch (InterruptedException e) {
+ log.info((isActive ? "active" : "inactive")
+ + " job executor thread '"
+ + getName()
+ + "' got interrupted");
+ }
+ catch (Exception e) {
+ log.error("exception in job executor thread. waiting "
+ + currentIdleInterval
+ + " milliseconds", e);
try {
- synchronized(jobExecutor) {
+ synchronized (jobExecutor) {
jobExecutor.wait(currentIdleInterval);
}
- } catch (InterruptedException e2) {
+ }
+ catch (InterruptedException e2) {
log.debug("delay after exception got interrupted", e2);
}
- // after an exception, the current idle interval is doubled to prevent
+ // after an exception, the current idle interval is doubled to prevent
// continuous exception generation when e.g. the db is unreachable
- currentIdleInterval <<= 1;
+ currentIdleInterval *= 2;
if (currentIdleInterval > maxIdleInterval || currentIdleInterval < 0) {
currentIdleInterval = maxIdleInterval;
}
}
}
- log.info(getName()+" leaves cyberspace");
+ log.info(getName() + " leaves cyberspace");
}
- protected Collection acquireJobs() {
- Collection acquiredJobs;
+ protected Collection<Job> acquireJobs() {
+ Collection<Job> acquiredJobs = Collections.emptyList();
synchronized (jobExecutor) {
- log.debug("acquiring jobs for execution...");
- List jobsToLock = Collections.EMPTY_LIST;
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
+ log.debug("querying for acquirable job...");
+ String lockOwner = getName();
JobSession jobSession = jbpmContext.getJobSession();
- String lockOwner = getName();
- log.debug("querying for acquirable job...");
Job job = jobSession.getFirstAcquirableJob(lockOwner);
- if (job!=null) {
+
+ if (job != null) {
if (job.isExclusive()) {
- log.debug("found exclusive " + job);
ProcessInstance processInstance = job.getProcessInstance();
- log.debug("finding other exclusive jobs for " + processInstance);
- jobsToLock = jobSession.findExclusiveJobs(lockOwner, processInstance);
- log.debug("trying to obtain exclusive locks on " + jobsToLock + " for " + processInstance);
- } else {
+ log.debug("loaded exclusive " + job + ", finding exclusive jobs for " + processInstance);
+ acquiredJobs = jobSession.findExclusiveJobs(lockOwner, processInstance);
+ log.debug("trying to obtain locks on " + acquiredJobs + " for " + processInstance);
+ }
+ else {
+ acquiredJobs = Collections.singletonList(job);
log.debug("trying to obtain lock on " + job);
- jobsToLock = Collections.singletonList(job);
}
-
+
Date lockTime = new Date();
- for (Iterator iter = jobsToLock.iterator(); iter.hasNext();) {
- job = (Job) iter.next();
- job.setLockOwner(lockOwner);
- job.setLockTime(lockTime);
- // jbpmContext.getSession().update(job);
+ for (Job acquiredJob : acquiredJobs) {
+ acquiredJob.setLockOwner(lockOwner);
+ acquiredJob.setLockTime(lockTime);
}
-
- // HACKY HACK : this is a workaround for a hibernate problem that is fixed in hibernate 3.2.1
- // TODO remove this hack already?
- // if (job instanceof Timer) {
- // Hibernate.initialize(((Timer)job).getGraphElement());
- // }
- } else {
- log.debug("no acquirable jobs in job table");
}
- } finally {
+ else {
+ log.debug("no acquirable jobs");
+ }
+ }
+ finally {
try {
jbpmContext.close();
- acquiredJobs = jobsToLock;
- log.debug("obtained lock on jobs: "+acquiredJobs);
+ log.debug("obtained lock on jobs: " + acquiredJobs);
}
catch (JbpmPersistenceException e) {
// if this is a stale object exception, keep it quiet
if (Services.isCausedByStaleState(e)) {
- log.debug("optimistic locking failed, couldn't obtain lock on jobs "+jobsToLock);
- acquiredJobs = Collections.EMPTY_LIST;
- } else {
+ log.debug("problem acquiring jobs " + acquiredJobs + ": optimistic locking failed");
+ StaleObjectLogConfigurer.getStaleObjectExceptionsLog().error("problem acquiring jobs "
+ + acquiredJobs
+ + ": optimistic locking failed", e);
+ acquiredJobs = Collections.emptyList();
+ }
+ else {
throw e;
}
}
@@ -166,33 +170,37 @@
if (job.execute(jbpmContext)) {
jobSession.deleteJob(job);
}
- } catch (Exception e) {
+ }
+ catch (Exception e) {
log.debug("exception while executing " + job, e);
if (!isPersistenceException(e)) {
StringWriter memoryWriter = new StringWriter();
e.printStackTrace(new PrintWriter(memoryWriter));
job.setException(memoryWriter.toString());
- job.setRetries(job.getRetries()-1);
+ job.setRetries(job.getRetries() - 1);
}
else {
// allowing a transaction to proceed after a persistence exception is unsafe
jbpmContext.setRollbackOnly();
}
}
-
+
// if this job is locked too long
- long totalLockTimeInMillis = System.currentTimeMillis() - job.getLockTime().getTime();
- if (totalLockTimeInMillis>maxLockTime) {
+ long totalLockTimeInMillis = System.currentTimeMillis() - job.getLockTime().getTime();
+ if (totalLockTimeInMillis > maxLockTime) {
jbpmContext.setRollbackOnly();
}
- } finally {
+ }
+ finally {
try {
jbpmContext.close();
- } catch (JbpmPersistenceException e) {
+ }
+ catch (JbpmPersistenceException e) {
// if this is a stale state exception, keep it quiet
if (Services.isCausedByStaleState(e)) {
- log.debug("optimistic locking failed, couldn't complete job "+job);
- } else {
+ log.debug("optimistic locking failed, couldn't complete job " + job);
+ }
+ else {
throw e;
}
}
@@ -213,21 +221,24 @@
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
JobSession jobSession = jbpmContext.getJobSession();
- Collection jobIdsToIgnore = jobExecutor.getMonitoredJobIds();
+ Collection<Long> jobIdsToIgnore = jobExecutor.getMonitoredJobIds();
Job job = jobSession.getFirstDueJob(getName(), jobIdsToIgnore);
- if (job!=null) {
+ if (job != null) {
nextDueDate = job.getDueDate();
jobExecutor.addMonitoredJobId(getName(), job.getId());
}
- } finally {
+ }
+ finally {
try {
jbpmContext.close();
- } catch (JbpmPersistenceException e) {
+ }
+ catch (JbpmPersistenceException e) {
// if this is a stale object exception, keep it quiet
if (Services.isCausedByStaleState(e)) {
log.debug("optimistic locking failed, couldn't get next due date");
nextDueDate = null;
- } else {
+ }
+ else {
throw e;
}
}
@@ -238,14 +249,14 @@
protected long getWaitPeriod() {
long interval = currentIdleInterval;
Date nextDueDate = getNextDueDate();
- if (nextDueDate!=null) {
+ if (nextDueDate != null) {
long currentTime = System.currentTimeMillis();
long nextDueTime = nextDueDate.getTime();
- if (nextDueTime < currentTime+currentIdleInterval) {
- interval = nextDueTime-currentTime;
+ if (nextDueTime < currentTime + currentIdleInterval) {
+ interval = nextDueTime - currentTime;
}
}
- if (interval<0) {
+ if (interval < 0) {
interval = 0;
}
return interval;
@@ -255,18 +266,17 @@
* @deprecated As of jBPM 3.2.3, replaced by {@link #deactivate()}
*/
public void setActive(boolean isActive) {
- if (isActive == false)
+ if (isActive == false)
deactivate();
}
/**
- * Indicates that this thread should stop running.
- * Execution will cease shortly afterwards.
+ * Indicates that this thread should stop running. Execution will cease shortly afterwards.
*/
public void deactivate() {
if (isActive) {
isActive = false;
- interrupt();
+ interrupt();
}
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/job/executor/LockMonitorThread.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/job/executor/LockMonitorThread.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/job/executor/LockMonitorThread.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -1,7 +1,6 @@
package org.jbpm.job.executor;
import java.util.Date;
-import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
@@ -64,17 +63,13 @@
JobSession jobSession = jbpmContext.getJobSession();
Date treshold = new Date(System.currentTimeMillis()-maxLockTime-lockBufferTime);
- List jobsWithOverdueLockTime = jobSession.findJobsWithOverdueLockTime(treshold);
- Iterator iter = jobsWithOverdueLockTime.iterator();
- while (iter.hasNext()) {
- Job job = (Job) iter.next();
- // unlock
+ List<Job> jobsWithOverdueLockTime = jobSession.findJobsWithOverdueLockTime(treshold);
+ for (Job job : jobsWithOverdueLockTime) {
log.debug("unlocking "+job+ " owned by thread "+job.getLockOwner());
job.setLockOwner(null);
job.setLockTime(null);
jobSession.saveJob(job);
}
-
} finally {
try {
jbpmContext.close();
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/jpdl/xml/JpdlXmlReader.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/jpdl/xml/JpdlXmlReader.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/jpdl/xml/JpdlXmlReader.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -64,12 +64,12 @@
private static final long serialVersionUID = 1L;
protected InputSource inputSource = null;
- protected List problems = new ArrayList();
+ protected List<Problem> problems = new ArrayList<Problem>();
protected ProblemListener problemListener = null;
protected ProcessDefinition processDefinition = null;
protected String initialNodeName = null;
- protected Collection unresolvedTransitionDestinations = null;
- protected Collection unresolvedActionReferences = null;
+ protected Collection<Object[]> unresolvedTransitionDestinations = null;
+ protected Collection<Object[]> unresolvedActionReferences = null;
/**
* the parsed process definition as DOM tree (available after readProcessDefinition)
@@ -133,9 +133,9 @@
processDefinition = ProcessDefinition.createNewProcessDefinition();
// initialize lists
- problems = new ArrayList();
- unresolvedTransitionDestinations = new ArrayList();
- unresolvedActionReferences = new ArrayList();
+ problems = new ArrayList<Problem>();
+ unresolvedTransitionDestinations = new ArrayList<Object[]>();
+ unresolvedActionReferences = new ArrayList<Object[]>();
try {
// parse the document into a dom tree
@@ -174,10 +174,8 @@
}
if (problems!=null) {
- Iterator iter = problems.iterator();
- while (iter.hasNext()) {
- Problem problem = (Problem) iter.next();
- log.warn("process parse warning: "+problem.getDescription());
+ for (Problem problem : problems) {
+ log.warn("process parse warning: "+problem.getDescription());
}
}
@@ -190,7 +188,7 @@
}
protected void readSwimlanes(Element processDefinitionElement) {
- Iterator iter = processDefinitionElement.elementIterator("swimlane");
+ Iterator<?> iter = processDefinitionElement.elementIterator("swimlane");
TaskMgmtDefinition taskMgmtDefinition = processDefinition.getTaskMgmtDefinition();
while (iter.hasNext()) {
Element swimlaneElement = (Element) iter.next();
@@ -227,12 +225,12 @@
}
public void readNodes(Element element, NodeCollection nodeCollection) {
- Iterator nodeElementIter = element.elementIterator();
+ Iterator<?> nodeElementIter = element.elementIterator();
while (nodeElementIter.hasNext()) {
Element nodeElement = (Element) nodeElementIter.next();
String nodeName = nodeElement.getName();
// get the node type
- Class nodeType = NodeTypes.getNodeType(nodeName);
+ Class<?> nodeType = NodeTypes.getNodeType(nodeName);
if (nodeType!=null) {
Node node = null;
@@ -241,6 +239,7 @@
node = (Node) nodeType.newInstance();
} catch (Exception e) {
log.error("couldn't instantiate node '"+nodeName+"', of type '"+nodeType.getName()+"'", e);
+ continue;
}
node.setProcessDefinition(processDefinition);
@@ -265,18 +264,16 @@
}
public void readTasks(Element element, TaskNode taskNode) {
- List elements = element.elements("task");
- TaskMgmtDefinition tmd = (TaskMgmtDefinition) processDefinition.getDefinition(TaskMgmtDefinition.class);
+ List<?> elements = element.elements("task");
+ TaskMgmtDefinition tmd = processDefinition.getTaskMgmtDefinition();
if (elements.size()>0) {
if (tmd==null) {
tmd = new TaskMgmtDefinition();
}
processDefinition.addDefinition(tmd);
-
- Iterator iter = elements.iterator();
- while (iter.hasNext()) {
- Element taskElement = (Element) iter.next();
- readTask(taskElement, tmd, taskNode);
+
+ for (Object taskElement : elements) {
+ readTask((Element) taskElement, tmd, taskNode);
}
}
}
@@ -456,15 +453,15 @@
taskController.setTaskControllerDelegation(taskControllerDelegation);
} else {
- List variableAccesses = readVariableAccesses(taskControllerElement);
+ List<VariableAccess> variableAccesses = readVariableAccesses(taskControllerElement);
taskController.setVariableAccesses(variableAccesses);
}
return taskController;
}
- public List readVariableAccesses(Element element) {
- List variableAccesses = new ArrayList();
- Iterator iter = element.elementIterator("variable");
+ public List<VariableAccess> readVariableAccesses(Element element) {
+ List<VariableAccess> variableAccesses = new ArrayList<VariableAccess>();
+ Iterator<?> iter = element.elementIterator("variable");
while (iter.hasNext()) {
Element variableElement = (Element) iter.next();
@@ -534,7 +531,7 @@
}
protected void readNodeTimers(Element nodeElement, Node node) {
- Iterator iter = nodeElement.elementIterator("timer");
+ Iterator<?> iter = nodeElement.elementIterator("timer");
while (iter.hasNext()) {
Element timerElement = (Element) iter.next();
readNodeTimer(timerElement, node);
@@ -561,7 +558,7 @@
}
protected void readTaskTimers(Element taskElement, Task task) {
- Iterator iter = taskElement.elementIterator();
+ Iterator<?> iter = taskElement.elementIterator();
while (iter.hasNext()) {
Element element = (Element) iter.next();
if ( ("timer".equals(element.getName()))
@@ -590,7 +587,7 @@
addAction(task, Event.EVENTTYPE_TASK_CREATE, createTimerAction);
// read the cancel-event types
- Collection cancelEventTypes = new ArrayList();
+ Collection<String> cancelEventTypes = new ArrayList<String>();
String cancelEventTypeText = timerElement.attributeValue("cancel-event");
if (cancelEventTypeText!=null) {
@@ -603,10 +600,8 @@
// set the default
cancelEventTypes.add(Event.EVENTTYPE_TASK_END);
}
-
- Iterator iter = cancelEventTypes.iterator();
- while (iter.hasNext()) {
- String cancelEventType = (String) iter.next();
+
+ for (String cancelEventType : cancelEventTypes) {
CancelTimerAction cancelTimerAction = new CancelTimerAction();
cancelTimerAction.setTimerName(name);
addAction(task, cancelEventType, cancelTimerAction);
@@ -614,7 +609,7 @@
}
protected void readEvents(Element parentElement, GraphElement graphElement) {
- Iterator iter = parentElement.elementIterator("event");
+ Iterator<?> iter = parentElement.elementIterator("event");
while (iter.hasNext()) {
Element eventElement = (Element) iter.next();
String eventType = eventElement.attributeValue("type");
@@ -627,7 +622,7 @@
public void readActions(Element eventElement, GraphElement graphElement, String eventType) {
// for all the elements in the event element
- Iterator nodeElementIter = eventElement.elementIterator();
+ Iterator<?> nodeElementIter = eventElement.elementIterator();
while (nodeElementIter.hasNext()) {
Element actionElement = (Element) nodeElementIter.next();
String actionName = actionElement.getName();
@@ -655,7 +650,7 @@
public Action readSingleAction(Element nodeElement) {
Action action = null;
// search for the first action element in the node
- Iterator iter = nodeElement.elementIterator();
+ Iterator<?> iter = nodeElement.elementIterator();
while (iter.hasNext() && (action==null)) {
Element candidate = (Element) iter.next();
if (ActionTypes.hasActionName(candidate.getName())) {
@@ -670,9 +665,9 @@
// create a new instance of the action
Action action = null;
String actionName = actionElement.getName();
- Class actionType = ActionTypes.getActionType(actionName);
+ Class<? extends Action> actionType = ActionTypes.getActionType(actionName);
try {
- action = (Action) actionType.newInstance();
+ action = actionType.newInstance();
} catch (Exception e) {
log.error("couldn't instantiate action '"+actionName+"', of type '"+actionType.getName()+"'", e);
}
@@ -698,7 +693,7 @@
}
protected void readExceptionHandlers(Element graphElementElement, GraphElement graphElement) {
- Iterator iter = graphElementElement.elementIterator("exception-handler");
+ Iterator<?> iter = graphElementElement.elementIterator("exception-handler");
while (iter.hasNext()) {
Element exceptionHandlerElement = (Element) iter.next();
readExceptionHandler(exceptionHandlerElement, graphElement);
@@ -713,7 +708,7 @@
graphElement.addExceptionHandler(exceptionHandler);
// read the actions in the body of the exception-handler element
- Iterator iter = exceptionHandlerElement.elementIterator();
+ Iterator<?> iter = exceptionHandlerElement.elementIterator();
while (iter.hasNext()) {
Element childElement = (Element) iter.next();
if (ActionTypes.hasActionName(childElement.getName())) {
@@ -730,20 +725,16 @@
}
public void resolveTransitionDestinations() {
- Iterator iter = unresolvedTransitionDestinations.iterator();
- while (iter.hasNext()) {
- Object[] unresolvedTransition = (Object[]) iter.next();
+ for (Object[] unresolvedTransition : unresolvedTransitionDestinations) {
Element nodeElement = (Element) unresolvedTransition[0];
Node node = (Node) unresolvedTransition[1];
resolveTransitionDestinations(nodeElement.elements("transition"), node);
}
}
- public void resolveTransitionDestinations(List transitionElements, Node node) {
- Iterator iter = transitionElements.iterator();
- while (iter.hasNext()) {
- Element transitionElement = (Element) iter.next();
- resolveTransitionDestination(transitionElement, node);
+ public void resolveTransitionDestinations(List<?> transitionElements, Node node) {
+ for (Object transitionElement : transitionElements) {
+ resolveTransitionDestination((Element) transitionElement, node);
}
}
@@ -806,9 +797,7 @@
}
public void resolveActionReferences() {
- Iterator iter = unresolvedActionReferences.iterator();
- while (iter.hasNext()) {
- Object[] unresolvedActionReference = (Object[]) iter.next();
+ for (Object[] unresolvedActionReference : unresolvedActionReferences) {
Element actionElement = (Element) unresolvedActionReference[0];
Action action = (Action) unresolvedActionReference[1];
String referencedActionName = actionElement.attributeValue("ref-name");
@@ -826,16 +815,13 @@
if ( (taskMgmtDefinition!=null)
&& (taskMgmtDefinition.getSwimlanes()!=null)
) {
- Iterator iter = taskMgmtDefinition.getSwimlanes().values().iterator();
- while (iter.hasNext()) {
- Swimlane swimlane = (Swimlane) iter.next();
-
+ for (Swimlane swimlane : taskMgmtDefinition.getSwimlanes().values()) {
Task startTask = taskMgmtDefinition.getStartTask();
Swimlane startTaskSwimlane = (startTask!=null ? startTask.getSwimlane() : null);
if ( (swimlane.getAssignmentDelegation()==null)
- && (swimlane!=startTaskSwimlane)
- ) {
+ && (swimlane!=startTaskSwimlane)
+ ) {
addWarning("swimlane '"+swimlane.getName()+"' does not have an assignment");
}
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/svc/Services.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/svc/Services.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/svc/Services.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -25,7 +25,6 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -50,8 +49,8 @@
import org.jbpm.svc.save.SaveOperation;
import org.jbpm.tx.TxService;
-public class Services implements Serializable
-{
+public class Services implements Serializable {
+
private static final long serialVersionUID = 1L;
public static final String SERVICENAME_AUTHENTICATION = "authentication";
@@ -64,10 +63,9 @@
public static final String SERVICENAME_JCR = "jcr";
public static final String SERVICENAME_ADDRESSRESOLVER = "addressresolver";
- static final List defaultSaveOperations = createDefaultSaveOperations();
+ static final List<SaveOperation> defaultSaveOperations = createDefaultSaveOperations();
- private static List createDefaultSaveOperations()
- {
+ private static List<SaveOperation> createDefaultSaveOperations() {
SaveOperation[] operations = new SaveOperation[4];
operations[0] = new CheckUnpersistableVariablesOperation();
// first we save the runtime data (process instance)
@@ -81,99 +79,80 @@
Map<String, ServiceFactory> serviceFactories;
Map<String, Service> services;
- List serviceNames = null;
- List saveOperations = null;
+ List<String> serviceNames;
+ List<SaveOperation> saveOperations;
- public static Service getCurrentService(String name)
- {
+ public static Service getCurrentService(String name) {
return getCurrentService(name, true);
}
- public static Service getCurrentService(String name, boolean isRequired)
- {
+ public static Service getCurrentService(String name, boolean isRequired) {
Service service = null;
JbpmContext jbpmContext = JbpmContext.getCurrentJbpmContext();
- if (jbpmContext != null)
- {
+ if (jbpmContext != null) {
service = jbpmContext.getServices().getService(name);
}
- if (isRequired && (service == null))
- {
+ if (isRequired && (service == null)) {
throw new JbpmServiceException("service '" + name + "' unavailable");
}
return service;
}
- public Services(Map serviceFactories)
- {
- this(serviceFactories, new ArrayList(serviceFactories.keySet()), null);
+ public Services(Map<String, ServiceFactory> serviceFactories) {
+ this(serviceFactories, new ArrayList<String>(serviceFactories.keySet()), null);
}
- public Services(Map serviceFactories, List serviceNames, List saveOperations)
- {
+ public Services(Map<String, ServiceFactory> serviceFactories, List<String> serviceNames,
+ List<SaveOperation> saveOperations) {
this.serviceFactories = serviceFactories;
this.serviceNames = serviceNames;
this.saveOperations = saveOperations != null ? saveOperations : defaultSaveOperations;
}
- public void setSaveOperations(List saveOperations)
- {
- if (saveOperations == null)
- {
+ public void setSaveOperations(List<SaveOperation> saveOperations) {
+ if (saveOperations == null) {
throw new IllegalArgumentException("saveOperations cannot be null");
}
this.saveOperations = saveOperations;
}
- public void addSaveOperation(SaveOperation saveOperation)
- {
- if (saveOperation == null)
- {
+ public void addSaveOperation(SaveOperation saveOperation) {
+ if (saveOperation == null) {
throw new IllegalArgumentException("saveOperation cannot be null");
}
- if (saveOperations == defaultSaveOperations)
- {
- saveOperations = new ArrayList(defaultSaveOperations);
+ if (saveOperations == defaultSaveOperations) {
+ saveOperations = new ArrayList<SaveOperation>(defaultSaveOperations);
}
saveOperations.add(saveOperation);
}
- public Map<String, ServiceFactory> getServiceFactories()
- {
- if (serviceFactories == null)
- {
+ public Map<String, ServiceFactory> getServiceFactories() {
+ if (serviceFactories == null) {
serviceFactories = new HashMap<String, ServiceFactory>();
}
return serviceFactories;
}
- public ServiceFactory getServiceFactory(String name)
- {
+ public ServiceFactory getServiceFactory(String name) {
return getServiceFactories().get(name);
}
- public boolean hasService(String name)
- {
+ public boolean hasService(String name) {
boolean hasService = false;
- if (services != null)
- {
+ if (services != null) {
hasService = services.containsKey(name);
}
return hasService;
}
- public Service getService(String name)
- {
- if (services == null)
- {
+ public Service getService(String name) {
+ if (services == null) {
services = new HashMap<String, Service>();
}
Service service = services.get(name);
- if (service == null)
- {
+ if (service == null) {
ServiceFactory serviceFactory = getServiceFactory(name);
- if (serviceFactory != null)
- {
+ if (serviceFactory != null) {
service = serviceFactory.openService();
services.put(name, service);
}
@@ -181,176 +160,134 @@
return service;
}
- public void save(ProcessInstance processInstance, JbpmContext jbpmContext)
- {
- Iterator iter = saveOperations.iterator();
-
- if (log.isDebugEnabled())
- {
- if (saveOperations == defaultSaveOperations)
- {
+ public void save(ProcessInstance processInstance, JbpmContext jbpmContext) {
+ if (log.isDebugEnabled()) {
+ if (saveOperations == defaultSaveOperations) {
log.debug("executing default save operations");
}
- else
- {
+ else {
log.debug("executing custom save operations");
}
}
-
- while (iter.hasNext())
- {
- SaveOperation saveOperation = (SaveOperation)iter.next();
+ for (SaveOperation saveOperation : saveOperations) {
saveOperation.save(processInstance, jbpmContext);
}
}
// services /////////////////////////////////////////////////////////////////
- public AuthenticationService getAuthenticationService()
- {
- return (AuthenticationService)getService(SERVICENAME_AUTHENTICATION);
+ public AuthenticationService getAuthenticationService() {
+ return (AuthenticationService) getService(SERVICENAME_AUTHENTICATION);
}
- public AuthorizationService getAuthorizationService()
- {
- return (AuthorizationService)getService(SERVICENAME_AUTHORIZATION);
+ public AuthorizationService getAuthorizationService() {
+ return (AuthorizationService) getService(SERVICENAME_AUTHORIZATION);
}
- public LoggingService getLoggingService()
- {
- return (LoggingService)getService(SERVICENAME_LOGGING);
+ public LoggingService getLoggingService() {
+ return (LoggingService) getService(SERVICENAME_LOGGING);
}
- public MessageService getMessageService()
- {
- return (MessageService)getService(SERVICENAME_MESSAGE);
+ public MessageService getMessageService() {
+ return (MessageService) getService(SERVICENAME_MESSAGE);
}
- public PersistenceService getPersistenceService()
- {
- return (PersistenceService)getService(SERVICENAME_PERSISTENCE);
+ public PersistenceService getPersistenceService() {
+ return (PersistenceService) getService(SERVICENAME_PERSISTENCE);
}
- public SchedulerService getSchedulerService()
- {
- return (SchedulerService)getService(SERVICENAME_SCHEDULER);
+ public SchedulerService getSchedulerService() {
+ return (SchedulerService) getService(SERVICENAME_SCHEDULER);
}
- public TxService getTxService()
- {
- return (TxService)getService(SERVICENAME_TX);
+ public TxService getTxService() {
+ return (TxService) getService(SERVICENAME_TX);
}
- public void setAuthenticationService(AuthenticationService authenticationService)
- {
+ public void setAuthenticationService(AuthenticationService authenticationService) {
services.put(SERVICENAME_AUTHENTICATION, authenticationService);
}
- public void setAuthorizationService(AuthorizationService authorizationService)
- {
+ public void setAuthorizationService(AuthorizationService authorizationService) {
services.put(SERVICENAME_AUTHORIZATION, authorizationService);
}
- public void setLoggingService(LoggingService loggingService)
- {
+ public void setLoggingService(LoggingService loggingService) {
services.put(SERVICENAME_LOGGING, loggingService);
}
- public void setMessageService(MessageService messageService)
- {
+ public void setMessageService(MessageService messageService) {
services.put(SERVICENAME_MESSAGE, messageService);
}
- public void setPersistenceService(PersistenceService persistenceService)
- {
+ public void setPersistenceService(PersistenceService persistenceService) {
services.put(SERVICENAME_PERSISTENCE, persistenceService);
}
- public void setSchedulerService(SchedulerService schedulerService)
- {
+ public void setSchedulerService(SchedulerService schedulerService) {
services.put(SERVICENAME_SCHEDULER, schedulerService);
}
- public void setTxService(TxService txService)
- {
+ public void setTxService(TxService txService) {
services.put(SERVICENAME_TX, txService);
}
- public void close()
- {
- if (services != null)
- {
+ public void close() {
+ if (services != null) {
Exception firstException = null;
- Iterator iter = serviceNames.iterator();
- while (iter.hasNext())
- {
- String serviceName = (String)iter.next();
- Service service = (Service)services.get(serviceName);
- if (service != null)
- {
- try
- {
+ for (String serviceName : serviceNames) {
+ Service service = services.get(serviceName);
+ if (service != null) {
+ try {
log.debug("closing service '" + serviceName + "': " + service);
service.close();
}
- catch (JbpmPersistenceException e)
- {
- // if this is a stale state exception, the jbpm configuration has control over the logging
- if (isCausedByStaleState(e))
- {
+ catch (JbpmPersistenceException e) {
+ // if this is a stale state exception, the jbpm configuration has control over the
+ // logging
+ if (isCausedByStaleState(e)) {
log.info("problem closing service '" + serviceName + "': optimistic locking failed");
- StaleObjectLogConfigurer.getStaleObjectExceptionsLog().error("problem closing service '" + serviceName + "': optimistic locking failed", e);
+ StaleObjectLogConfigurer.getStaleObjectExceptionsLog()
+ .error("problem closing service '" + serviceName + "': optimistic locking failed", e);
}
- else
- {
+ else {
log.error("problem closing service '" + serviceName + "'", e);
}
- if (firstException == null)
- {
+ if (firstException == null) {
firstException = e;
}
}
- catch (Exception e)
- {
- // NOTE that Error's are not caught because that might halt the JVM and mask the original Error.
+ catch (Exception e) {
+ // NOTE that Error's are not caught because that might halt the JVM and mask the
+ // original Error.
log.error("problem closing service '" + serviceName + "'", e);
- if (firstException == null)
- {
+ if (firstException == null) {
firstException = e;
}
}
}
}
- if (firstException != null)
- {
- if (firstException instanceof JbpmException)
- {
- throw (JbpmException)firstException;
- }
- throw new JbpmException("problem closing services", firstException);
+ if (firstException != null) {
+ throw firstException instanceof JbpmException ? (JbpmException) firstException
+ : new JbpmException("problem closing services", firstException);
}
}
}
- public static boolean isCausedByStaleState(JbpmPersistenceException persistenceException)
- {
- for (Throwable cause = persistenceException.getCause(); cause != null; cause = cause.getCause())
- {
+ public static boolean isCausedByStaleState(JbpmPersistenceException persistenceException) {
+ for (Throwable cause = persistenceException.getCause(); cause != null; cause = cause.getCause()) {
if (cause instanceof StaleStateException)
return true;
}
return false;
}
- public static void assignId(Object object)
- {
+ public static void assignId(Object object) {
JbpmContext jbpmContext = JbpmContext.getCurrentJbpmContext();
- if (jbpmContext != null)
- {
+ if (jbpmContext != null) {
// give this process instance an id
Services services = jbpmContext.getServices();
- if (services.hasService(Services.SERVICENAME_PERSISTENCE))
- {
+ if (services.hasService(Services.SERVICENAME_PERSISTENCE)) {
PersistenceService persistenceService = services.getPersistenceService();
persistenceService.assignId(object);
}
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/taskmgmt/def/TaskMgmtDefinition.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/taskmgmt/def/TaskMgmtDefinition.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/taskmgmt/def/TaskMgmtDefinition.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -34,8 +34,8 @@
private static final long serialVersionUID = 1L;
- protected Map swimlanes = null;
- protected Map tasks = null;
+ protected Map<String, Swimlane> swimlanes = null;
+ protected Map<String, Task> tasks = null;
protected Task startTask = null;
// constructors /////////////////////////////////////////////////////////////
@@ -50,35 +50,35 @@
// swimlanes ////////////////////////////////////////////////////////////////
public void addSwimlane( Swimlane swimlane ) {
- if (swimlanes==null) swimlanes = new HashMap();
+ if (swimlanes==null) swimlanes = new HashMap<String, Swimlane>();
swimlanes.put(swimlane.getName(), swimlane);
swimlane.setTaskMgmtDefinition(this);
}
- public Map getSwimlanes() {
+ public Map<String, Swimlane> getSwimlanes() {
return swimlanes;
}
public Swimlane getSwimlane( String swimlaneName ) {
if (swimlanes==null) return null;
- return (Swimlane) swimlanes.get( swimlaneName );
+ return swimlanes.get( swimlaneName );
}
// tasks ////////////////////////////////////////////////////////////////////
public void addTask( Task task ) {
- if (tasks==null) tasks = new HashMap();
+ if (tasks==null) tasks = new HashMap<String, Task>();
tasks.put(task.getName(), task);
task.setTaskMgmtDefinition(this);
}
- public Map getTasks() {
+ public Map<String, Task> getTasks() {
return tasks;
}
public Task getTask( String taskName ) {
if (tasks==null) return null;
- return (Task) tasks.get( taskName );
+ return tasks.get( taskName );
}
// start task ///////////////////////////////////////////////////////////////
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/taskmgmt/exe/TaskMgmtInstance.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/taskmgmt/exe/TaskMgmtInstance.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/taskmgmt/exe/TaskMgmtInstance.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -126,13 +126,6 @@
// assign an id to the task instance
Services.assignId(taskInstance);
- // copy the task properties
- /*
- * XXX property initialization was already done in taskInstance.setTask(task) String description = null; if
- * (task!=null) { description = task.getDescription(); taskInstance.setDescription(description);
- * taskInstance.setBlocking(task.isBlocking()); taskInstance.setSignalling(task.isSignalling()); }
- */
-
if (executionContext != null)
{
Token token = executionContext.getToken();
@@ -329,23 +322,17 @@
void performAssignmentActorIdExpr(String actorIdExpression, Assignable assignable, ExecutionContext executionContext)
{
- Object result = null;
- String actorId = null;
- try
+ Object result = JbpmExpressionEvaluator.evaluate(actorIdExpression, executionContext);
+ if (result == null)
{
- result = JbpmExpressionEvaluator.evaluate(actorIdExpression, executionContext);
- if (result == null)
- {
- throw new JbpmException("actor-id expression '" + actorIdExpression + "' returned null");
- }
- actorId = (String)result;
+ throw new JbpmException("actor-id expression '" + actorIdExpression + "' returned null");
}
- catch (ClassCastException e)
+ if (!(result instanceof String))
{
throw new JbpmException("actor-id expression '" + actorIdExpression + "' didn't resolve to a java.lang.String: '" + result + "' ("
- + result.getClass().getName() + ")");
+ + result.getClass().getName() + ")");
}
- assignable.setActorId(actorId);
+ assignable.setActorId((String) result);
}
void performAssignmentPooledActorsExpr(String pooledActorsExpression, Assignable assignable, ExecutionContext executionContext)
@@ -360,23 +347,21 @@
if (result instanceof String[])
{
pooledActors = (String[])result;
-
}
else if (result instanceof Collection)
{
- Collection collection = (Collection)result;
- pooledActors = (String[])collection.toArray(new String[collection.size()]);
-
+ Collection<?> collection = (Collection<?>)result;
+ pooledActors = collection.toArray(new String[collection.size()]);
}
else if (result instanceof String)
{
- List pooledActorList = new ArrayList();
+ List<String> pooledActorList = new ArrayList<String>();
StringTokenizer tokenizer = new StringTokenizer((String)result, ",");
while (tokenizer.hasMoreTokens())
{
pooledActorList.add(tokenizer.nextToken().trim());
}
- pooledActors = (String[])pooledActorList.toArray(new String[pooledActorList.size()]);
+ pooledActors = pooledActorList.toArray(new String[pooledActorList.size()]);
}
else
{
@@ -559,8 +544,6 @@
Class<?> persistentMapClass = swimlaneInstances.getClass();
Field mapField = persistentMapClass.getDeclaredField("map");
mapField.setAccessible(true);
- // TODO remove the size when we switch to hibernate 3.2.1 (it's a workaround for a bug)
- swimlaneInstances.size();
swimlaneInstances.put(swimlaneInstance.getName(), swimlaneInstance);
}
catch (Exception e)
Modified: jbpm3/trunk/modules/core/src/main/java/org/jbpm/util/ClassLoaderUtil.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/util/ClassLoaderUtil.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/util/ClassLoaderUtil.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -27,12 +27,9 @@
import org.jbpm.JbpmConfiguration;
import org.jbpm.JbpmException;
-import org.jbpm.graph.def.ProcessDefinition;
-import org.jbpm.instantiation.ProcessClassLoader;
-import org.jbpm.instantiation.ProcessClassLoaderFactory;
/**
- * provides centralized classloader lookup.
+ * provides centralized classloader lookup.
*/
public class ClassLoaderUtil
{
@@ -42,7 +39,7 @@
// hide default constructor to prevent instantiation
}
- public static Class loadClass(String className)
+ public static Class<?> loadClass(String className)
{
try
{
@@ -54,11 +51,17 @@
}
}
- /*
- * returns the {@link ClassLoader} which is used in jbpm. Can be configured in jbpm.cfg.xml by the property <b>'jbpm.classloader'</b> <td> <li>'jbpm': (default value)
- * uses the {@link ClassLoaderUtil}.class.getClassLoader() {@link ClassLoader}. This was the only behavior available before <a
- * href="https://jira.jboss.org/jira/browse/JBPM-1148">JBPM-1148</a>.</li> <li>'context': uses the Thread.currentThread().getContextClassLoader().</li> <li>'custom':
- * means that a ClassLoader class has to be provided in the property <b>'jbpm.classloader.classname'</b></li> </td>
+ /**
+ * returns the {@link ClassLoader} which is used in jbpm. Can be configured in jbpm.cfg.xml by the
+ * property <code>jbpm.classLoader</code>.
+ * <ul>
+ * <li><code>jbpm</code> (default) uses the {@link ClassLoaderUtil#getClassLoader()}. This
+ * was the only behavior available before <a
+ * href="https://jira.jboss.org/jira/browse/JBPM-1148">JBPM-1148</a>.</li>
+ * <li><code>context</code> uses the {@link Thread#getContextClassLoader()}.</li>
+ * <li><code>custom</code> means that a ClassLoader class has to be provided in the property
+ * <code>jbpm.classLoader.className</code></li>
+ * </ul>
*/
public static ClassLoader getClassLoader()
{
@@ -76,41 +79,52 @@
}
else if (jbpmClassloader.equals("custom"))
{
- String jbpmClassloaderClassname = null;
+ String classloaderClassname = null;
try
{
if (!JbpmConfiguration.Configs.hasObject("jbpm.customClassLoader.className"))
{
- throw new JbpmException("'jbpm.classloader' property set to 'custom' but 'jbpm.customClassLoader.className' is empty!");
+ throw new JbpmException(
+ "'jbpm.classLoader' property set to 'custom' but 'jbpm.customClassLoader.className' is absent!");
}
- jbpmClassloaderClassname = JbpmConfiguration.Configs.getString("jbpm.customClassLoader.className");
- if (jbpmClassloaderClassname == null)
+ classloaderClassname = JbpmConfiguration.Configs
+ .getString("jbpm.customClassLoader.className");
+ if (classloaderClassname == null)
{
- throw new JbpmException("'jbpm.classloader' property set to 'custom' but 'jbpm.customClassLoader.className' is empty!");
+ throw new JbpmException(
+ "'jbpm.classloader' property set to 'custom' but 'jbpm.customClassLoader.className' is null!");
}
- Class clazz = ClassLoaderUtil.class.getClassLoader().loadClass(jbpmClassloaderClassname);
- if (clazz == null)
- clazz = Thread.currentThread().getContextClassLoader().loadClass(jbpmClassloaderClassname);
+ Class<?> clazz = ClassLoaderUtil.class.getClassLoader()
+ .loadClass(classloaderClassname);
+ if (clazz == null) {
+ clazz = Thread.currentThread().getContextClassLoader()
+ .loadClass(classloaderClassname);
+ }
- return (ClassLoader)clazz.newInstance();
+ return (ClassLoader) clazz.newInstance();
}
catch (InstantiationException e)
{
- throw new JbpmException("Error instantiating custom classloader " + jbpmClassloaderClassname, e);
+ throw new JbpmException("Error instantiating custom classloader "
+ + classloaderClassname, e);
}
catch (IllegalAccessException e)
{
- throw new JbpmException("Error accessing custom classloader " + jbpmClassloaderClassname, e);
+ throw new JbpmException("Error accessing custom classloader " + classloaderClassname,
+ e);
}
catch (ClassNotFoundException e)
{
- throw new JbpmException("Custom classloader " + jbpmClassloaderClassname + " not found ", e);
+ throw new JbpmException("Custom classloader " + classloaderClassname + " not found ",
+ e);
}
}
else
{
- throw new JbpmException("'jbpm.classloader' property set to '" + jbpmClassloader + "' but only the values 'jbpm'/'context'/'custom' are supported!");
+ throw new JbpmException("'jbpm.classloader' property set to '"
+ + jbpmClassloader
+ + "' but only the values 'jbpm'/'context'/'custom' are supported!");
}
}
else
@@ -126,14 +140,17 @@
}
/*
- * Load jbpm configuration related resources as stream (normally jbpm.cfg.xml). This method first tries to load the resource from the {@link ClassLoaderUtil} class
- * loader, if not found it tries the context class loader. If this doesn't return any ressource the call is delegated to the class loader configured by calling
- * getClassLoader(). This is a special method because the class loader which has to be used for loading the jbpm.cfg.xml cannot be configured in the jbpm.cfg.xml
- * itself.
+ * Load jbpm configuration related resources as stream (normally jbpm.cfg.xml). This method first
+ * tries to load the resource from the {@link ClassLoaderUtil} class loader, if not found it tries
+ * the context class loader. If this doesn't return any ressource the call is delegated to the
+ * class loader configured by calling getClassLoader(). This is a special method because the class
+ * loader which has to be used for loading the jbpm.cfg.xml cannot be configured in the
+ * jbpm.cfg.xml itself.
*/
public static InputStream getJbpmConfigurationStream(String resource)
{
- InputStream jbpmCfgStream = ClassLoaderUtil.class.getClassLoader().getResourceAsStream(resource);
+ InputStream jbpmCfgStream = ClassLoaderUtil.class.getClassLoader()
+ .getResourceAsStream(resource);
if (jbpmCfgStream == null)
{
jbpmCfgStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
Added: jbpm3/trunk/modules/core/src/main/java/org/jbpm/util/CollectionUtil.java
===================================================================
--- jbpm3/trunk/modules/core/src/main/java/org/jbpm/util/CollectionUtil.java (rev 0)
+++ jbpm3/trunk/modules/core/src/main/java/org/jbpm/util/CollectionUtil.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -0,0 +1,96 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jbpm.util;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * @author Alejandro Guizar
+ */
+public class CollectionUtil {
+
+ /** Indicates whether collection elements should be actually checked. */
+ private static final boolean DEBUG = true;
+
+ private CollectionUtil() {
+ // hide default constructor to prevent instantiation
+ }
+
+ /**
+ * Ensures that all elements of the given collection can be cast to a desired type.
+ *
+ * @param collection the collection to check
+ * @param type the desired type
+ * @return a collection of the desired type
+ * @throws ClassCastException if an element cannot be cast to the desired type
+ */
+ @SuppressWarnings("unchecked")
+ public static <E> Collection<E> checkCollection(Collection<?> collection, Class<E> type) {
+ if (DEBUG) {
+ for (Object element : collection) {
+ if (element != null && !type.isInstance(element))
+ throw new ClassCastException(element.getClass().toString());
+ }
+ }
+ return (Collection<E>) collection;
+ }
+
+ /**
+ * Ensures that all elements of the given list can be cast to a desired type.
+ *
+ * @param list the list to check
+ * @param type the desired type
+ * @return a list of the desired type
+ * @throws ClassCastException if an element cannot be cast to the desired type
+ */
+ @SuppressWarnings("unchecked")
+ public static <E> List<E> checkList(List<?> list, Class<E> type) {
+ if (DEBUG) {
+ for (Object element : list) {
+ if (element != null && !type.isInstance(element))
+ throw new ClassCastException(element.getClass().toString());
+ }
+ }
+ return (List<E>) list;
+ }
+
+ /**
+ * Ensures that all elements of the given set can be cast to a desired type.
+ *
+ * @param list the set to check
+ * @param type the desired type
+ * @return a set of the desired type
+ * @throws ClassCastException if an element cannot be cast to the desired type
+ */
+ @SuppressWarnings("unchecked")
+ public static <E> Set<E> checkSet(Set<?> set, Class<E> type) {
+ if (DEBUG) {
+ for (Object element : set) {
+ if (element != null && !type.isInstance(element))
+ throw new ClassCastException(element.getClass().toString());
+ }
+ }
+ return (Set<E>) set;
+ }
+}
Modified: jbpm3/trunk/modules/core/src/main/resources/org/jbpm/db/hibernate.queries.hbm.xml
===================================================================
--- jbpm3/trunk/modules/core/src/main/resources/org/jbpm/db/hibernate.queries.hbm.xml 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/main/resources/org/jbpm/db/hibernate.queries.hbm.xml 2009-01-16 18:23:36 UTC (rev 3664)
@@ -56,7 +56,7 @@
order by pd.name, pd.version desc
]]>
</query>
-
+
<query name="GraphSession.findAllProcessDefinitionVersions">
<![CDATA[
select pd
@@ -65,6 +65,24 @@
order by pd.version desc
]]>
</query>
+
+ <query name="GraphSession.findLatestProcessDefinitions">
+ <![CDATA[
+ select pd.name, max(pd.version)
+ from org.jbpm.graph.def.ProcessDefinition as pd
+ group by pd.name
+ ]]>
+ <!-- better alternative, if your database supports ansi sql tuple syntax -->
+ <!--
+ select pd
+ from org.jbpm.graph.def.ProcessDefinition as pd
+ where ( pd.name, pd.version ) in (
+ select pd.name, max(pd.version)
+ from org.jbpm.graph.def.ProcessDefinition as pd
+ group by pd.name
+ )
+ -->
+ </query>
<query name="GraphSession.findAllProcessInstancesForADefinition">
<![CDATA[
@@ -77,22 +95,21 @@
<query name="GraphSession.findReferencingProcessStates">
<![CDATA[
- select processState
- from org.jbpm.graph.node.ProcessState as processState
- where processState.subProcessDefinition = :subProcessDefinition
+ select ps
+ from org.jbpm.graph.node.ProcessState as ps
+ where ps.subProcessDefinition = :subProcessDefinition
]]>
</query>
<!-- related to ProcessInstance -->
<!-- ########################## -->
-
<query name="GraphSession.findAllRunningProcessInstancesWithProcessName">
<![CDATA[
select pi
from org.jbpm.graph.exe.ProcessInstance as pi
where pi.processDefinition.name = :processDefinitionName
- and pi.end = null
+ and pi.end is null
order by pi.start desc
]]>
</query>
@@ -110,7 +127,7 @@
<![CDATA[
select pi
from org.jbpm.graph.exe.ProcessInstance as pi
- where pi.end = null
+ where pi.end is null
order by pi.start desc
]]>
</query>
@@ -127,7 +144,7 @@
<![CDATA[
select pi
from org.jbpm.graph.exe.ProcessInstance as pi
- where pi.superProcessToken!=null
+ where pi.superProcessToken is not null
and pi.superProcessToken.processInstance = :processInstance
order by pi.start desc
]]>
@@ -154,10 +171,10 @@
<query name="GraphSession.findProcessInstanceByKey">
<![CDATA[
- select processInstance
- from org.jbpm.graph.exe.ProcessInstance processInstance
- where processInstance.processDefinition = :processDefinition
- and processInstance.key = :key
+ select pi
+ from org.jbpm.graph.exe.ProcessInstance pi
+ where pi.processDefinition = :processDefinition
+ and pi.key = :key
]]>
</query>
@@ -172,17 +189,17 @@
<query name="GraphSession.findTaskInstanceIdsForProcessInstance">
<![CDATA[
- select t
- from org.jbpm.taskmgmt.exe.TaskInstance t
- where t.taskMgmtInstance.processInstance = :processInstance
+ select ti.id
+ from org.jbpm.taskmgmt.exe.TaskInstance ti
+ where ti.taskMgmtInstance.processInstance = :processInstance
]]>
</query>
<query name="GraphSession.deleteTaskInstancesById">
<![CDATA[
delete
- from org.jbpm.taskmgmt.exe.TaskInstance t
- where t.id in (:taskInstanceIds)
+ from org.jbpm.taskmgmt.exe.TaskInstance ti
+ where ti.id in (:taskInstanceIds)
]]>
</query>
@@ -218,7 +235,7 @@
org.jbpm.graph.exe.ProcessInstance processInstance
where token.processInstance = :processInstance
and token.node = node
- and token.isSuspended != true
+ and token.isSuspended = false
and token.parent is not null
and token.end is null
]]>
@@ -234,7 +251,6 @@
<!-- Logging -->
<!-- ########################### -->
-
<query name="LoggingSession.findLogsByToken">
<![CDATA[
select pl
@@ -247,7 +263,6 @@
<!-- JobSession -->
<!-- ########################### -->
-
<query name="JobSession.getFirstAcquirableJob">
<![CDATA[
select job
@@ -255,7 +270,7 @@
where ( (job.lockOwner is null) or (job.lockOwner = :lockOwner) )
and job.retries > 0
and job.dueDate <= :now
- and job.isSuspended != true
+ and job.isSuspended = false
order by job.dueDate asc
]]>
</query>
@@ -269,7 +284,7 @@
and job.dueDate <= :now
and job.processInstance = :processInstance
and job.isExclusive = true
- and job.isSuspended != true
+ and job.isSuspended = false
order by job.dueDate asc
]]>
</query>
@@ -280,7 +295,7 @@
from org.jbpm.job.Job as job
where ( (job.lockOwner is null) or (job.lockOwner = :lockOwner) )
and job.retries > 0
- and job.isSuspended != true
+ and job.isSuspended = false
order by job.dueDate asc
]]>
</query>
@@ -292,7 +307,7 @@
where ( (job.lockOwner is null) or (job.lockOwner = :lockOwner) )
and job.id not in ( :jobIdsToIgnore )
and job.retries > 0
- and job.isSuspended != true
+ and job.isSuspended = false
order by job.dueDate asc
]]>
</query>
@@ -357,7 +372,7 @@
select ti
from org.jbpm.taskmgmt.exe.TaskInstance as ti
where ti.actorId = :actorId
- and ti.isSuspended != true
+ and ti.isSuspended = false
and ti.isOpen = true
]]>
</query>
@@ -367,7 +382,7 @@
select ti
from org.jbpm.taskmgmt.exe.TaskInstance as ti
where ti.actorId in ( :actorIds )
- and ti.isSuspended != true
+ and ti.isSuspended = false
and ti.isOpen = true
]]>
</query>
@@ -377,9 +392,9 @@
select distinct ti.id
from org.jbpm.taskmgmt.exe.TaskInstance ti
join ti.pooledActors pooledActor
- where pooledActor.actorId = :swimlaneActorId
+ where pooledActor.actorId = :actorId
and ti.actorId is null
- and ti.isSuspended != true
+ and ti.isSuspended = false
and ti.isOpen = true
]]>
</query>
@@ -391,31 +406,17 @@
join ti.pooledActors pooledActor
where pooledActor.actorId in ( :actorIds )
and ti.actorId is null
- and ti.isSuspended != true
+ and ti.isSuspended = false
and ti.isOpen = true
]]>
</query>
-<!-- old one from camunda, I think we can sjip that, but not sure yet
- <query name="TaskMgmtSession.findPooledTaskInstancesByActorId">
- <![CDATA[
- select distinct ti
- from org.jbpm.taskmgmt.exe.PooledActor pooledActor
- join pooledActor.taskInstances ti
- where pooledActor.actorId = :swimlaneActorId
- and ti.actorId != null
- and ti.end = null
- and ti.isCancelled = false
- ]]>
- </query>
--->
-
<query name="TaskMgmtSession.findTaskInstancesByTokenId">
<![CDATA[
select ti
from org.jbpm.taskmgmt.exe.TaskInstance ti
where ti.token.id = :tokenId
- and ti.isSuspended != true
+ and ti.isSuspended = false
and ti.isOpen = true
]]>
</query>
@@ -425,7 +426,7 @@
select ti
from org.jbpm.taskmgmt.exe.TaskInstance ti
where ti.token.processInstance = :processInstance
- and ti.isSuspended != true
+ and ti.isSuspended = false
and ti.isOpen = true
]]>
</query>
@@ -444,7 +445,7 @@
select ti
from org.jbpm.taskmgmt.exe.TaskInstance ti
where ti.token.processInstance = :instance
- and ti.end IS NULL
+ and ti.end is null
]]>
</query>
Modified: jbpm3/trunk/modules/core/src/test/java/org/jbpm/JbpmConfigurationTest.java
===================================================================
--- jbpm3/trunk/modules/core/src/test/java/org/jbpm/JbpmConfigurationTest.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/test/java/org/jbpm/JbpmConfigurationTest.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -21,8 +21,6 @@
*/
package org.jbpm;
-import java.util.HashMap;
-
import org.jbpm.configuration.ConfigurationException;
import org.jbpm.configuration.ObjectFactory;
import org.jbpm.configuration.ObjectFactoryImpl;
@@ -36,21 +34,11 @@
protected void setUp() throws Exception
{
super.setUp();
- JbpmConfiguration.instances = new HashMap();
+ JbpmConfiguration.instances.clear();
JbpmConfiguration.defaultObjectFactory = null;
- JbpmConfiguration.jbpmConfigurationsStacks = new ThreadLocal();
- JbpmContext.currentContextsStack = new ThreadLocal();
+ JbpmConfiguration.jbpmConfigurationsStacks.remove();
}
- protected void tearDown() throws Exception
- {
- JbpmConfiguration.instances = new HashMap();
- JbpmConfiguration.defaultObjectFactory = null;
- JbpmConfiguration.jbpmConfigurationsStacks = new ThreadLocal();
- JbpmContext.currentContextsStack = new ThreadLocal();
- super.tearDown();
- }
-
public void testSingleton() {
JbpmConfiguration.defaultObjectFactory = new ObjectFactoryImpl(null, null);
JbpmConfiguration instance = JbpmConfiguration.getInstance();
Modified: jbpm3/trunk/modules/core/src/test/java/org/jbpm/JbpmContextTest.java
===================================================================
--- jbpm3/trunk/modules/core/src/test/java/org/jbpm/JbpmContextTest.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/test/java/org/jbpm/JbpmContextTest.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -21,8 +21,6 @@
*/
package org.jbpm;
-import java.util.HashMap;
-
import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.logging.LoggingService;
import org.jbpm.logging.log.MessageLog;
@@ -37,18 +35,9 @@
protected void setUp() throws Exception
{
super.setUp();
- JbpmConfiguration.instances = new HashMap();
+ JbpmConfiguration.instances.clear();
JbpmConfiguration.defaultObjectFactory = null;
- JbpmContext.currentContextsStack = new ThreadLocal();
}
-
- protected void tearDown() throws Exception
- {
- JbpmConfiguration.instances = new HashMap();
- JbpmConfiguration.defaultObjectFactory = null;
- JbpmContext.currentContextsStack = new ThreadLocal();
- super.tearDown();
- }
public void testServices() {
JbpmConfiguration jbpmConfiguration = JbpmConfiguration.parseXmlString(
Modified: jbpm3/trunk/modules/core/src/test/java/org/jbpm/SerializabilityTest.java
===================================================================
--- jbpm3/trunk/modules/core/src/test/java/org/jbpm/SerializabilityTest.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/test/java/org/jbpm/SerializabilityTest.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -24,10 +24,6 @@
import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Modifier;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
import org.jbpm.file.def.FileDefinitionFileSystemConfigTest;
import org.jbpm.util.ClassLoaderUtil;
@@ -36,7 +32,7 @@
String testRootDir = FileDefinitionFileSystemConfigTest.class.getProtectionDomain().getCodeSource().getLocation().getFile().toString();
- static Set excusedClasses = new HashSet(Arrays.asList(new String[] {
+ static String[] excusedClasses = {
"org.jbpm.ant",
"org.jbpm.context.exe.JbpmType",
"org.jbpm.db.hibernate.ConverterEnumType",
@@ -110,7 +106,7 @@
"org.jbpm.web.JbpmConfigurationCloser",
"org.jbpm.JbpmContextTestHelper",
"org.jbpm.EventCallback$1"
- }));
+ };
public void testForNonSerializableClasses() {
File jbpmRoot = new File(testRootDir+"../classes/");
@@ -139,8 +135,7 @@
}
private void assertSerializabilityOfClass(String className) {
- Class clazz = ClassLoaderUtil.loadClass(className);
-
+ Class<?> clazz = ClassLoaderUtil.loadClass(className);
if ( ! ( Serializable.class.isAssignableFrom(clazz)
|| Modifier.isAbstract(clazz.getModifiers())
|| isExcused(className)
@@ -152,15 +147,12 @@
}
boolean isExcused(String className) {
- boolean isExcused = false;
- Iterator iter = excusedClasses.iterator();
- while (iter.hasNext() && !isExcused) {
- String excusedClassName = (String) iter.next();
+ for (String excusedClassName : excusedClasses) {
if (className.startsWith(excusedClassName)) {
- isExcused = true;
- }
+ return true;
+ }
}
- return isExcused;
+ return false;
}
}
Modified: jbpm3/trunk/modules/core/src/test/java/org/jbpm/jbpm1778/JBPM1778Test.java
===================================================================
--- jbpm3/trunk/modules/core/src/test/java/org/jbpm/jbpm1778/JBPM1778Test.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/core/src/test/java/org/jbpm/jbpm1778/JBPM1778Test.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -21,11 +21,11 @@
{
ProcessDefinition pd = getProcessDefinition();
- ProcessInstance pi = pd.createProcessInstance(new HashMap<String, String>());
+ ProcessInstance pi = pd.createProcessInstance(new HashMap<String, Object>());
TaskMgmtInstance tmi = pi.getTaskMgmtInstance();
tmi.createStartTaskInstance();
- Map piVars = pi.getContextInstance().getVariables();
+ Map<String, Object> piVars = pi.getContextInstance().getVariables();
assertNotNull("ProcessInstance vars not null", piVars);
assertEquals("ProcessInstance vars empty", 0, piVars.size());
}
@@ -34,14 +34,14 @@
{
ProcessDefinition pd = getProcessDefinition();
- HashMap<String, String> vars = new HashMap<String, String>();
+ HashMap<String, Object> vars = new HashMap<String, Object>();
vars.put("uno", "dos");
ProcessInstance pi = pd.createProcessInstance(vars);
TaskMgmtInstance tmi = pi.getTaskMgmtInstance();
tmi.createStartTaskInstance();
- Map piVars = pi.getContextInstance().getVariables();
+ Map<String, Object> piVars = pi.getContextInstance().getVariables();
assertNotNull("ProcessInstance vars not null", piVars);
assertEquals("ProcessInstance vars not empty", 1, piVars.size());
}
Modified: jbpm3/trunk/modules/db/src/main/resources/hibernate.extra.hbm.xml
===================================================================
--- jbpm3/trunk/modules/db/src/main/resources/hibernate.extra.hbm.xml 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/db/src/main/resources/hibernate.extra.hbm.xml 2009-01-16 18:23:36 UTC (rev 3664)
@@ -6,4 +6,8 @@
<hibernate-mapping>
+ <!-- ################################################## -->
+ <!-- # Additional mappings defined per module go here # -->
+ <!-- ################################################## -->
+
</hibernate-mapping>
Modified: jbpm3/trunk/modules/enterprise/src/main/java/org/jbpm/ejb/impl/TimerEntityBean.java
===================================================================
--- jbpm3/trunk/modules/enterprise/src/main/java/org/jbpm/ejb/impl/TimerEntityBean.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/enterprise/src/main/java/org/jbpm/ejb/impl/TimerEntityBean.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -54,6 +54,7 @@
private EntityContext entityContext;
private LocalCommandService commandService;
+ private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(TimerEntityBean.class);
public abstract Long getTimerId();
Modified: jbpm3/trunk/modules/examples/src/test/java/org/jbpm/examples/assignment/RulesAssignmentTest.java
===================================================================
--- jbpm3/trunk/modules/examples/src/test/java/org/jbpm/examples/assignment/RulesAssignmentTest.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/examples/src/test/java/org/jbpm/examples/assignment/RulesAssignmentTest.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -180,7 +180,7 @@
public ProcessInstance getProcessInstance(long processInstanceId)
{
- ProcessInstance processInstance = (ProcessInstance)jbpmContext.loadProcessInstanceForUpdate(processInstanceId);
+ ProcessInstance processInstance = jbpmContext.loadProcessInstanceForUpdate(processInstanceId);
return processInstance;
}
Modified: jbpm3/trunk/modules/examples/src/test/java/org/jbpm/examples/rulesaction/RulesActionTest.java
===================================================================
--- jbpm3/trunk/modules/examples/src/test/java/org/jbpm/examples/rulesaction/RulesActionTest.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/examples/src/test/java/org/jbpm/examples/rulesaction/RulesActionTest.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -118,7 +118,7 @@
public ProcessInstance getProcessInstance(long processInstanceId)
{
- ProcessInstance processInstance = (ProcessInstance)jbpmContext.loadProcessInstanceForUpdate(processInstanceId);
+ ProcessInstance processInstance = jbpmContext.loadProcessInstanceForUpdate(processInstanceId);
return processInstance;
}
}
Modified: jbpm3/trunk/modules/identity/src/main/java/org/jbpm/identity/Membership.java
===================================================================
--- jbpm3/trunk/modules/identity/src/main/java/org/jbpm/identity/Membership.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/identity/src/main/java/org/jbpm/identity/Membership.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -32,7 +32,7 @@
* The name of the membership can be used as the role name. Meaning
* which role does the user fullfill in the group.
*/
-public class Membership extends Entity implements Serializable {
+public class Membership extends Entity {
private static final long serialVersionUID = 1L;
Modified: jbpm3/trunk/modules/simulation/src/test/java/org/jbpm/sim/BusinessFiguresTest.java
===================================================================
--- jbpm3/trunk/modules/simulation/src/test/java/org/jbpm/sim/BusinessFiguresTest.java 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/modules/simulation/src/test/java/org/jbpm/sim/BusinessFiguresTest.java 2009-01-16 18:23:36 UTC (rev 3664)
@@ -1,17 +1,13 @@
package org.jbpm.sim;
-import java.util.Date;
+import junit.framework.TestCase;
import org.jbpm.graph.exe.ExecutionContext;
import org.jbpm.sim.def.JbpmSimulationExperiment;
-import org.jbpm.sim.def.JbpmSimulationScenario;
import org.jbpm.sim.exe.ExperimentReader;
import org.jbpm.sim.kpi.BusinessFigureCalculator;
import org.jbpm.sim.report.ScenarioReport;
-import org.jbpm.sim.report.dto.ValueStatisticResult;
-import junit.framework.TestCase;
-
public class BusinessFiguresTest extends TestCase {
private String testProcessXml =
@@ -113,9 +109,9 @@
"</experiment>";
public void testBusinessFigureConfiguredInExperiment() {
- ExperimentReader reader = new ExperimentReader(experimentConfiguration);
+ ExperimentReader reader = new ExperimentReader(experimentConfiguration2);
// inject process definition
- reader.addProcessDefinition("test", testProcessXml );
+ reader.addProcessDefinition("test", testProcessXml2 );
JbpmSimulationExperiment experiment = reader.readExperiment();
experiment.run();
Modified: jbpm3/trunk/pom.xml
===================================================================
--- jbpm3/trunk/pom.xml 2009-01-16 17:16:26 UTC (rev 3663)
+++ jbpm3/trunk/pom.xml 2009-01-16 18:23:36 UTC (rev 3664)
@@ -89,6 +89,8 @@
<mysql.connector.version>5.0.8</mysql.connector.version>
<postgresql.version>8.3-603.jdbc3</postgresql.version>
<jtds.version>1.2.2</jtds.version>
+ <jconnect.version>6.0.5</jconnect.version>
+ <ojdbc.version>10.0.2.0</ojdbc.version>
</properties>
<!-- DependencyManagement -->
@@ -574,7 +576,7 @@
<dependency>
<groupId>com.sybase</groupId>
<artifactId>jconnect</artifactId>
- <version>6.0.5</version>
+ <version>${jconnect.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -599,7 +601,7 @@
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
- <version>10.0.2.0</version>
+ <version>${ojdbc.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
More information about the jbpm-commits
mailing list