[jbpm-commits] JBoss JBPM SVN: r3994 - in jbpm3/branches/jbpm-3.2.5.SP/modules/core/src: main/java/org/jbpm/graph/def and 13 other directories.
do-not-reply at jboss.org
do-not-reply at jboss.org
Sat Feb 21 22:15:07 EST 2009
Author: alex.guizar at jboss.com
Date: 2009-02-21 22:15:07 -0500 (Sat, 21 Feb 2009)
New Revision: 3994
Added:
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/util/CollectionUtil.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/jbpm2036/
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/jbpm2036/JBPM2036Test.java
Removed:
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/jbpm2036/JBPM2036Test.java
Modified:
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/AbstractDbTestCase.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/GraphSession.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/JbpmSchema.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/JobSession.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/TaskMgmtSession.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/graph/def/Action.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/graph/def/GraphElement.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/graph/exe/ProcessInstance.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/graph/exe/Token.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/job/Job.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/job/Timer.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/job/executor/LockMonitorThread.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/msg/db/DbMessageService.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/scheduler/def/CreateTimerAction.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/resources/org/jbpm/db/hibernate.queries.hbm.xml
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/db/DeleteProcessInstanceDbTest.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/graph/exe/SubProcessCancellationTest.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/jpdl/par/ProcessArchiveClassLoadingDbTest.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/taskmgmt/exe/TaskTimerExecutionDbTest.java
jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/taskmgmt/exe/TaskVariablesDbTest.java
Log:
merge revisions 3832, 3844:3846, 3848, 3856:3857 from trunk
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/AbstractDbTestCase.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/AbstractDbTestCase.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/AbstractDbTestCase.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -23,10 +23,7 @@
// $Id$
-import java.util.Iterator;
import java.util.Map;
-import java.util.Timer;
-import java.util.TimerTask;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -39,16 +36,13 @@
import org.jbpm.JbpmContext;
import org.jbpm.graph.def.ProcessDefinition;
import org.jbpm.graph.exe.ProcessInstance;
-import org.jbpm.job.Job;
import org.jbpm.job.executor.JobExecutor;
import org.jbpm.logging.log.ProcessLog;
import org.jbpm.persistence.db.DbPersistenceServiceFactory;
import org.jbpm.svc.Services;
import org.jbpm.taskmgmt.exe.TaskInstance;
-public abstract class AbstractDbTestCase extends AbstractJbpmTestCase
-{
- private static final Log log = LogFactory.getLog(AbstractDbTestCase.class);
+public abstract class AbstractDbTestCase extends AbstractJbpmTestCase {
protected JbpmConfiguration jbpmConfiguration;
@@ -64,265 +58,204 @@
protected JobExecutor jobExecutor;
- protected void setUp() throws Exception
- {
+ private static final Log log = LogFactory.getLog(AbstractDbTestCase.class);
+
+ protected void setUp() throws Exception {
super.setUp();
beginSessionTransaction();
}
- protected void tearDown() throws Exception
- {
+ protected void tearDown() throws Exception {
commitAndCloseSession();
ensureCleanDatabase();
super.tearDown();
}
- private void ensureCleanDatabase()
- {
+ private void ensureCleanDatabase() {
boolean hasLeftOvers = false;
- DbPersistenceServiceFactory dbPersistenceServiceFactory = (DbPersistenceServiceFactory)getJbpmConfiguration().getServiceFactory("persistence");
+ DbPersistenceServiceFactory dbPersistenceServiceFactory = (DbPersistenceServiceFactory) getJbpmConfiguration().getServiceFactory("persistence");
Configuration configuration = dbPersistenceServiceFactory.getConfiguration();
JbpmSchema jbpmSchema = new JbpmSchema(configuration);
- Map jbpmTablesRecordCount = jbpmSchema.getJbpmTablesRecordCount();
- for (Iterator iter = jbpmTablesRecordCount.entrySet().iterator(); iter.hasNext();)
- {
- Map.Entry entry = (Map.Entry)iter.next();
- String tableName = (String)entry.getKey();
- Integer count = (Integer)entry.getValue();
+ Map<String, Integer> recordCountPerTable = jbpmSchema.getRecordCountPerTable();
+ for (Map.Entry<String, Integer> entry : recordCountPerTable.entrySet()) {
+ // String tableName = entry.getKey();
+ Integer count = entry.getValue();
- if ((count == null) || (count != 0))
- {
+ if ((count == null) || (count != 0)) {
hasLeftOvers = true;
// [JBPM-1812] Fix tests that don't cleanup the database
- // Only uncomment this if you intnde to fix it. Otherwise it just generates noise.
- // System.err.println("FIXME: " + getClass().getName() + "." + getName() + " left " + count + " records in " + tableName);
+ // Only uncomment this if you intend to fix it. Otherwise it just generates noise.
+ // System.err.println("FIXME: " + getClass().getName() + "." + getName() + " left " + count
+ // + " records in " + tableName);
}
}
- if (hasLeftOvers)
- {
+ if (hasLeftOvers) {
// TODO: JBPM-1781
// jbpmSchema.cleanSchema();
}
}
- protected String getHibernateDialect()
- {
- DbPersistenceServiceFactory factory = (DbPersistenceServiceFactory)jbpmContext.getServiceFactory(Services.SERVICENAME_PERSISTENCE);
+ protected String getHibernateDialect() {
+ DbPersistenceServiceFactory factory = (DbPersistenceServiceFactory) jbpmContext.getServiceFactory(Services.SERVICENAME_PERSISTENCE);
return factory.getConfiguration().getProperty(Environment.DIALECT);
}
- protected void beginSessionTransaction()
- {
+ protected void beginSessionTransaction() {
createJbpmContext();
initializeMembers();
}
- protected void commitAndCloseSession()
- {
+ protected void commitAndCloseSession() {
closeJbpmContext();
resetMembers();
}
- protected void newTransaction()
- {
+ protected void newTransaction() {
commitAndCloseSession();
beginSessionTransaction();
}
- protected ProcessInstance saveAndReload(ProcessInstance pi)
- {
+ protected ProcessInstance saveAndReload(ProcessInstance pi) {
jbpmContext.save(pi);
newTransaction();
return graphSession.loadProcessInstance(pi.getId());
}
- protected TaskInstance saveAndReload(TaskInstance taskInstance)
- {
+ protected TaskInstance saveAndReload(TaskInstance taskInstance) {
jbpmContext.save(taskInstance);
newTransaction();
- return (TaskInstance)session.load(TaskInstance.class, new Long(taskInstance.getId()));
+ return (TaskInstance) session.load(TaskInstance.class, new Long(taskInstance.getId()));
}
- protected ProcessDefinition saveAndReload(ProcessDefinition pd)
- {
+ protected ProcessDefinition saveAndReload(ProcessDefinition pd) {
graphSession.saveProcessDefinition(pd);
newTransaction();
return graphSession.loadProcessDefinition(pd.getId());
}
- protected ProcessLog saveAndReload(ProcessLog processLog)
- {
+ protected ProcessLog saveAndReload(ProcessLog processLog) {
loggingSession.saveProcessLog(processLog);
newTransaction();
return loggingSession.loadProcessLog(processLog.getId());
}
- protected void createSchema()
- {
+ protected void createSchema() {
getJbpmConfiguration().createSchema();
}
- protected void cleanSchema()
- {
+ protected void cleanSchema() {
getJbpmConfiguration().cleanSchema();
}
- protected void dropSchema()
- {
+ protected void dropSchema() {
getJbpmConfiguration().dropSchema();
}
- protected String getJbpmTestConfig()
- {
+ protected String getJbpmTestConfig() {
return "org/jbpm/db/jbpm.db.test.cfg.xml";
}
- protected JbpmConfiguration getJbpmConfiguration()
- {
- if (jbpmConfiguration == null)
- {
+ protected JbpmConfiguration getJbpmConfiguration() {
+ if (jbpmConfiguration == null) {
String jbpmTestConfiguration = getJbpmTestConfig();
jbpmConfiguration = JbpmConfiguration.getInstance(jbpmTestConfiguration);
}
return jbpmConfiguration;
}
- protected void createJbpmContext()
- {
+ protected void createJbpmContext() {
jbpmContext = getJbpmConfiguration().createJbpmContext();
}
- protected void closeJbpmContext()
- {
- if (jbpmContext != null)
- {
+ protected void closeJbpmContext() {
+ if (jbpmContext != null) {
jbpmContext.close();
jbpmContext = null;
}
}
- protected void startJobExecutor()
- {
+ protected void startJobExecutor() {
jobExecutor = getJbpmConfiguration().getJobExecutor();
jobExecutor.start();
}
- protected void waitForJobs(long timeout)
- {
- // install a timer that will interrupt if it takes too long
- // if that happens, it will lead to an interrupted exception and the test
- // will fail
- TimerTask interruptTask = new TimerTask()
- {
- Thread testThread = Thread.currentThread();
-
- public void run()
- {
- log.debug("test " + getName() + " took too long. going to interrupt...");
- testThread.interrupt();
+ protected void waitForJobs(long timeout) {
+ long startTime = System.currentTimeMillis();
+ while (getNbrOfJobsAvailable() > 0) {
+ if (System.currentTimeMillis() - startTime > timeout) {
+ fail("test execution exceeded treshold of " + timeout + " milliseconds");
}
- };
- Timer timer = new Timer();
- timer.schedule(interruptTask, timeout);
-
- try
- {
- while (getNbrOfJobsAvailable() > 0)
- {
- log.debug("going to sleep for 200 millis, waiting for the job executor to process more jobs");
- Thread.sleep(200);
+ log.debug("waiting for the job executor to process more jobs");
+ try {
+ Thread.sleep(500);
}
+ catch (InterruptedException e) {
+ // keep going
+ }
}
- catch (InterruptedException e)
- {
- fail("test execution exceeded treshold of " + timeout + " milliseconds");
- }
- finally
- {
- timer.cancel();
- }
}
- protected int getNbrOfJobsAvailable()
- {
- if (session != null)
- {
+ protected int getNbrOfJobsAvailable() {
+ if (session != null) {
return getNbrOfJobsAvailable(session);
}
- else
- {
+ else {
beginSessionTransaction();
- try
- {
+ try {
return getNbrOfJobsAvailable(session);
}
- finally
- {
+ finally {
commitAndCloseSession();
}
}
}
- private int getNbrOfJobsAvailable(Session session)
- {
+ private int getNbrOfJobsAvailable(Session session) {
int nbrOfJobsAvailable = 0;
- Number jobs = (Number)session.createQuery("select count(*) from org.jbpm.job.Job").uniqueResult();
+ Number jobs = (Number) session.createQuery("select count(*) from org.jbpm.job.Job")
+ .uniqueResult();
log.debug("there are " + jobs + " jobs in the database");
- if (jobs != null)
- {
+ if (jobs != null) {
nbrOfJobsAvailable = jobs.intValue();
}
return nbrOfJobsAvailable;
}
- protected int getTimerCount()
- {
- Number timerCount = (Number)session.createQuery("select count(*) from org.jbpm.job.Timer").uniqueResult();
+ protected int getTimerCount() {
+ Number timerCount = (Number) session.createQuery("select count(*) from org.jbpm.job.Timer")
+ .uniqueResult();
log.debug("there are " + timerCount + " timers in the database");
return timerCount.intValue();
}
- protected Job getJob()
- {
- return (Job)session.createQuery("from org.jbpm.job.Job").uniqueResult();
- }
-
- protected void processJobs(long maxWait)
- {
+ protected void processJobs(long maxWait) {
commitAndCloseSession();
- startJobExecutor();
- try
- {
+ try {
+ startJobExecutor();
waitForJobs(maxWait);
}
- finally
- {
+ finally {
stopJobExecutor();
beginSessionTransaction();
}
}
- protected void stopJobExecutor()
- {
- if (jobExecutor != null)
- {
- try
- {
+ protected void stopJobExecutor() {
+ if (jobExecutor != null) {
+ try {
jobExecutor.stopAndJoin();
}
- catch (InterruptedException e)
- {
+ catch (InterruptedException e) {
throw new RuntimeException("waiting for job executor to stop and join got interrupted", e);
}
}
}
- protected void initializeMembers()
- {
+ protected void initializeMembers() {
session = jbpmContext.getSession();
graphSession = jbpmContext.getGraphSession();
taskMgmtSession = jbpmContext.getTaskMgmtSession();
@@ -331,8 +264,7 @@
contextSession = jbpmContext.getContextSession();
}
- protected void resetMembers()
- {
+ protected void resetMembers() {
session = null;
graphSession = null;
taskMgmtSession = null;
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/GraphSession.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/GraphSession.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/GraphSession.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -22,92 +22,79 @@
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.HibernateException;
import org.hibernate.LockMode;
-import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
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;
+ final Session session;
+ final JbpmSession jbpmSession;
- public GraphSession(JbpmSession jbpmSession)
- {
- this.jbpmSession = jbpmSession;
+ public GraphSession(JbpmSession jbpmSession) {
this.session = jbpmSession.getSession();
+ this.jbpmSession = jbpmSession;
}
- public GraphSession(Session session)
- {
+ public GraphSession(Session session) {
this.session = session;
- this.jbpmSession = new JbpmSession(session);
+ this.jbpmSession = null;
}
// 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)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't save process definition '" + processDefinition + "'", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not save " + processDefinition, e);
}
}
@@ -116,17 +103,14 @@
*
* @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)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't load process definition '" + processDefinitionId + "'", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not load process definition " + processDefinitionId, e);
}
}
@@ -135,232 +119,196 @@
*
* @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)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't get process definition '" + processDefinitionId + "'", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not get process definition " + processDefinitionId, e);
}
}
/**
* queries the database for a process definition with the given name and version.
*/
- public ProcessDefinition findProcessDefinition(String name, int version)
- {
- ProcessDefinition processDefinition = null;
- try
- {
- Query query = session.getNamedQuery("GraphSession.findProcessDefinitionByNameAndVersion");
- query.setString("name", name);
- query.setInteger("version", version);
- processDefinition = (ProcessDefinition)query.uniqueResult();
+ public ProcessDefinition findProcessDefinition(String name, int version) {
+ try {
+ return (ProcessDefinition) session.getNamedQuery("GraphSession.findProcessDefinitionByNameAndVersion")
+ .setString("name", name)
+ .setInteger("version", version)
+ .uniqueResult();
}
- catch (Exception e)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't get process definition with name '" + name + "' and version '" + version + "'", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not find process definition '"
+ + name
+ + "' at version "
+ + version, e);
}
- return processDefinition;
}
/**
* queries the database for the latest version of a process definition with the given name.
*/
- public ProcessDefinition findLatestProcessDefinition(String name)
- {
- ProcessDefinition processDefinition = null;
- try
- {
- Query query = session.getNamedQuery("GraphSession.findLatestProcessDefinitionQuery");
- query.setString("name", name);
- query.setMaxResults(1);
- processDefinition = (ProcessDefinition)query.uniqueResult();
+ public ProcessDefinition findLatestProcessDefinition(String name) {
+ try {
+ return (ProcessDefinition) session.getNamedQuery("GraphSession.findLatestProcessDefinitionQuery")
+ .setString("name", name)
+ .setMaxResults(1)
+ .uniqueResult();
}
- catch (Exception e)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't find process definition '" + name + "'", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not find process definition '" + name + "'", e);
}
- return processDefinition;
}
/**
- * 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 {
+ List<?> tuples = session.getNamedQuery("GraphSession.findLatestProcessDefinitions")
+ .list();
+ List<ProcessDefinition> result = new ArrayList<ProcessDefinition>();
+ for (Object[] tuple : CollectionUtil.checkList(tuples, Object[].class)) {
+ 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)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't find latest versions of process definitions", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not find latest versions of process definitions", e);
}
- return processDefinitions;
}
+ public List<ProcessDefinition> findProcessDefinitions(Collection<Long> processDefinitionIds) {
+ List<?> processDefinitions = session.createCriteria(ProcessDefinition.class)
+ .add(Restrictions.in("id", processDefinitionIds))
+ .list();
+ return CollectionUtil.checkList(processDefinitions, 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
- {
- Query query = session.getNamedQuery("GraphSession.findAllProcessDefinitions");
- return query.list();
+ public List<ProcessDefinition> findAllProcessDefinitions() {
+ try {
+ List<?> processDefinitions = session.getNamedQuery("GraphSession.findAllProcessDefinitions")
+ .list();
+ return CollectionUtil.checkList(processDefinitions, ProcessDefinition.class);
}
- catch (Exception e)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't find all process definitions", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not find all process definitions", e);
}
}
/**
- * 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
- {
- Query query = session.getNamedQuery("GraphSession.findAllProcessDefinitionVersions");
- query.setString("name", name);
- return query.list();
+ public List<ProcessDefinition> findAllProcessDefinitionVersions(String name) {
+ try {
+ List<?> processDefinitions = session.getNamedQuery("GraphSession.findAllProcessDefinitionVersions")
+ .setString("name", name)
+ .list();
+ return CollectionUtil.checkList(processDefinitions, ProcessDefinition.class);
}
- catch (HibernateException e)
- {
+ catch (HibernateException e) {
log.error(e);
- throw new JbpmException("couldn't find all versions of process definition '" + name + "'", e);
+ throw new JbpmException("could not 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)
- {
- throw new JbpmException("processDefinition is null");
+ public void deleteProcessDefinition(ProcessDefinition processDefinition) {
+ if (processDefinition == null) {
+ throw new IllegalArgumentException("processDefinition cannot be null");
}
- try
- {
+
+ try {
// delete all the process instances of this definition
- for (ProcessInstance processInstance; ((processInstance = findNextProcessInstance(processDefinition)) != null);)
- {
- deleteProcessInstance(processInstance);
+ List<?> processInstanceIds = session.getNamedQuery("GraphSession.findAllProcessInstanceIdsForDefinition")
+ .setLong("processDefinitionId", processDefinition.getId())
+ .list();
+ for (Long processInstanceId : CollectionUtil.checkList(processInstanceIds, Long.class)) {
+ ProcessInstance processInstance = getProcessInstance(processInstanceId);
+ if (processInstance != null) {
+ deleteProcessInstance(processInstance);
+ }
+ else {
+ log.debug("process instance " + processInstanceId + " has been deleted already");
+ }
}
- 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)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't delete process definition '" + processDefinition.getId() + "'", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not delete " + processDefinition, e);
}
}
- protected ProcessInstance findNextProcessInstance(ProcessDefinition processDefinition)
- {
- return (ProcessInstance)session.createCriteria(ProcessInstance.class).add(Restrictions.eq("processDefinition", processDefinition)).setMaxResults(1)
- .uniqueResult();
+ List<ProcessState> findReferencingProcessStates(ProcessDefinition subProcessDefinition) {
+ List<?> processStates = session.getNamedQuery("GraphSession.findReferencingProcessStates")
+ .setEntity("subProcessDefinition", subProcessDefinition)
+ .list();
+ return CollectionUtil.checkList(processStates, ProcessState.class);
}
- protected List findReferencingProcessStates(ProcessDefinition subProcessDefinition)
- {
- Query query = session.getNamedQuery("GraphSession.findReferencingProcessStates");
- query.setEntity("subProcessDefinition", subProcessDefinition);
- return query.list();
- }
-
// process instances ////////////////////////////////////////////////////////
/**
* @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));
- return processInstance;
+ public ProcessInstance loadProcessInstance(long processInstanceId) {
+ try {
+ return (ProcessInstance) session.load(ProcessInstance.class, new Long(processInstanceId));
}
- catch (Exception e)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't load process instance '" + processInstanceId + "'", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not load process instance " + processInstanceId, e);
}
}
/**
- * 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));
- return processInstance;
+ public ProcessInstance getProcessInstance(long processInstanceId) {
+ try {
+ return (ProcessInstance) session.get(ProcessInstance.class, new Long(processInstanceId));
}
- catch (Exception e)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't get process instance '" + processInstanceId + "'", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not get process instance " + processInstanceId, e);
}
}
@@ -370,18 +318,13 @@
* @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));
- return token;
+ public Token loadToken(long tokenId) {
+ try {
+ return (Token) session.load(Token.class, new Long(tokenId));
}
- catch (Exception e)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't load token '" + tokenId + "'", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not load token " + tokenId, e);
}
}
@@ -390,181 +333,153 @@
*
* @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));
- return token;
+ public Token getToken(long tokenId) {
+ try {
+ return (Token) session.get(Token.class, new Long(tokenId));
}
- catch (Exception e)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't get token '" + tokenId + "'", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not get token " + tokenId, e);
}
}
/**
* locks a process instance in the database.
*/
- public void lockProcessInstance(long processInstanceId)
- {
- lockProcessInstance(loadProcessInstance(processInstanceId));
+ public void lockProcessInstance(long processInstanceId) {
+ try {
+ session.load(ProcessInstance.class, processInstanceId, LockMode.UPGRADE);
+ }
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not lock process instance " + processInstanceId, e);
+ }
}
/**
* 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)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't lock process instance '" + processInstance.getId() + "'", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not lock " + processInstance, e);
}
}
/**
- * 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
- {
- Query query = session.getNamedQuery("GraphSession.findAllProcessInstancesForADefinition");
- query.setLong("processDefinitionId", processDefinitionId);
- processInstances = query.list();
-
+ public List<ProcessInstance> findProcessInstances(long processDefinitionId) {
+ try {
+ List<?> processInstances = session.getNamedQuery("GraphSession.findAllProcessInstancesForDefinition")
+ .setLong("processDefinitionId", processDefinitionId)
+ .list();
+ return CollectionUtil.checkList(processInstances, ProcessInstance.class);
}
- catch (Exception e)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't load process instances for process definition '" + processDefinitionId + "'", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not find 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)
- {
- if (processInstance == null)
- throw new JbpmException("processInstance is null in JbpmSession.deleteProcessInstance()");
- log.debug("deleting process instance " + processInstance.getId());
+ public void deleteProcessInstance(ProcessInstance processInstance, boolean includeTasks,
+ boolean includeJobs) {
+ if (processInstance == null) {
+ throw new IllegalArgumentException("processInstance cannot be null");
+ }
- try
- {
- // jobs
- if (includeJobs)
- {
- log.debug("deleting jobs for process instance " + processInstance.getId());
- Query query = session.getNamedQuery("GraphSession.deleteJobsForProcessInstance");
- query.setEntity("processInstance", processInstance);
- query.executeUpdate();
+ try {
+ // delete outstanding jobs
+ if (includeJobs) {
+ log.debug("deleting jobs for " + processInstance);
+ int entityCount = session.getNamedQuery("GraphSession.deleteJobsForProcessInstance")
+ .setEntity("processInstance", processInstance)
+ .executeUpdate();
+ log.debug("deleted " + entityCount + " jobs for " + processInstance);
}
- // tasks
- if (includeTasks)
- {
- Query query = session.getNamedQuery("GraphSession.findTaskInstanceIdsForProcessInstance");
- query.setEntity("processInstance", processInstance);
- List taskInstanceIds = query.list();
-
- if ((taskInstanceIds != null) && (!taskInstanceIds.isEmpty()))
- {
- log.debug("deleting tasks " + taskInstanceIds + " for process instance " + processInstance.getId());
- query = session.getNamedQuery("GraphSession.deleteTaskInstancesById");
- query.setParameterList("taskInstanceIds", taskInstanceIds);
- }
- }
-
- // delete the logs
- log.debug("deleting logs for process instance " + processInstance.getId());
+ // delete logs
+ log.debug("deleting logs for " + processInstance);
deleteLogs(processInstance);
- // delete the tokens and subprocess instances
- log.debug("deleting subprocesses for process instance " + processInstance.getId());
- deleteSubProcesses(processInstance.getRootToken());
-
- // null out the parent process token
+ // detach from 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("detaching "
+ + processInstance
+ + " from super process token "
+ + superProcessToken.getId());
+ processInstance.setSuperProcessToken(null);
superProcessToken.setSubProcessInstance(null);
}
- // add the process instance
- log.debug("hibernate session delete for process instance " + processInstance.getId());
+ // delete tokens and subprocess instances
+ log.debug("deleting subprocesses for " + processInstance);
+ deleteSubProcesses(processInstance);
+
+ // delete tasks (TaskLogs reference tasks, so tasks must be deleted after logs)
+ if (includeTasks) {
+ log.debug("deleting tasks for " + processInstance);
+ List<?> tasks = session.getNamedQuery("GraphSession.findTaskInstancesForProcessInstance")
+ .setEntity("processInstance", processInstance)
+ .list();
+ for (Object task : tasks) {
+ session.delete(task);
+ }
+ }
+
+ // delete the process instance
+ log.debug("deleting " + processInstance);
session.delete(processInstance);
}
- catch (Exception e)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't delete process instance '" + processInstance.getId() + "'", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not delete " + processInstance, e);
}
}
- 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();
+ void deleteLogs(ProcessInstance processInstance) {
+ List<?> logs = session.getNamedQuery("GraphSession.findLogsForProcessInstance")
+ .setEntity("processInstance", processInstance)
+ .list();
+ for (ProcessLog processLog : CollectionUtil.checkList(logs, ProcessLog.class)) {
session.delete(processLog);
}
}
- void deleteSubProcesses(Token token)
- {
- if (token != null)
- {
- Query query = session.getNamedQuery("GraphSession.findSubProcessInstances");
- query.setEntity("processInstance", token.getProcessInstance());
- List processInstances = query.list();
+ void deleteSubProcesses(ProcessInstance processInstance) {
+ if (processInstance != null) {
+ List<?> subProcessInstances = session.getNamedQuery("GraphSession.findSubProcessInstances")
+ .setEntity("processInstance", processInstance)
+ .list();
- if (processInstances == null || processInstances.isEmpty())
- {
- log.debug("no subprocesses to delete for token " + token.getId());
+ if (subProcessInstances.isEmpty()) {
+ log.debug("no subprocesses to delete for " + processInstance);
return;
}
- Iterator iter = processInstances.iterator();
- while (iter.hasNext())
- {
- ProcessInstance subProcessInstance = (ProcessInstance)iter.next();
- subProcessInstance.setSuperProcessToken(null);
- token.setSubProcessInstance(null);
- log.debug("deleting sub process " + subProcessInstance.getId());
+ for (ProcessInstance subProcessInstance : CollectionUtil.checkList(subProcessInstances, ProcessInstance.class)) {
+ log.debug("preparing to delete sub process instance " + subProcessInstance.getId());
deleteProcessInstance(subProcessInstance);
}
}
}
- public static class AverageNodeTimeEntry
- {
+ public static class AverageNodeTimeEntry {
+
private long nodeId;
private String nodeName;
private int count;
@@ -572,168 +487,129 @@
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
- {
- Query query = session.getNamedQuery("GraphSession.calculateAverageTimeByNode");
- query.setLong("processDefinitionId", processDefinitionId);
- query.setDouble("minimumDuration", minumumDurationMillis);
- List listResults = query.list();
+ public List<AverageNodeTimeEntry> calculateAverageTimeByNode(long processDefinitionId,
+ long minumumDurationMillis) {
+ try {
+ List<?> tuples = session.getNamedQuery("GraphSession.calculateAverageTimeByNode")
+ .setLong("processDefinitionId", processDefinitionId)
+ .setDouble("minimumDuration", minumumDurationMillis)
+ .list();
- if (listResults != null)
- {
- results = new ArrayList();
- Iterator iter = listResults.iterator();
- while (iter.hasNext())
- {
- Object[] values = (Object[])iter.next();
+ List<AverageNodeTimeEntry> results;
+ if (!tuples.isEmpty()) {
+ results = new ArrayList<AverageNodeTimeEntry>();
+ for (Object[] values : CollectionUtil.checkList(tuples, Object[].class)) {
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)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't load process instances for process definition '" + processDefinitionId + "'", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not calculate average time by node for process definition "
+ + processDefinitionId, e);
}
- return results;
}
- public List findActiveNodesByProcessInstance(ProcessInstance processInstance)
- {
- List results = null;
- try
- {
- Query query = session.getNamedQuery("GraphSession.findActiveNodesByProcessInstance");
- query.setEntity("processInstance", processInstance);
- results = query.list();
-
+ public List<Node> findActiveNodesByProcessInstance(ProcessInstance processInstance) {
+ try {
+ List<?> nodes = session.getNamedQuery("GraphSession.findActiveNodesByProcessInstance")
+ .setEntity("processInstance", processInstance)
+ .list();
+ return CollectionUtil.checkList(nodes, Node.class);
}
- catch (Exception e)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't active nodes for process instance '" + processInstance + "'", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not find active nodes for " + processInstance, e);
}
- return results;
}
- public ProcessInstance getProcessInstance(ProcessDefinition processDefinition, String key)
- {
- ProcessInstance processInstance = null;
- try
- {
- Query query = session.getNamedQuery("GraphSession.findProcessInstanceByKey");
- query.setEntity("processDefinition", processDefinition);
- query.setString("key", key);
- processInstance = (ProcessInstance)query.uniqueResult();
-
+ public ProcessInstance getProcessInstance(ProcessDefinition processDefinition, String key) {
+ try {
+ return (ProcessInstance) session.getNamedQuery("GraphSession.findProcessInstanceByKey")
+ .setEntity("processDefinition", processDefinition)
+ .setString("key", key)
+ .uniqueResult();
}
- catch (Exception e)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't get process instance with key '" + key + "'", e);
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("could not get process instance with key '" + key + "'", e);
}
- return processInstance;
}
- public ProcessInstance loadProcessInstance(ProcessDefinition processDefinition, String key)
- {
- ProcessInstance processInstance = null;
- try
- {
- Query query = session.getNamedQuery("GraphSession.findProcessInstanceByKey");
- query.setEntity("processDefinition", processDefinition);
- query.setString("key", key);
- processInstance = (ProcessInstance)query.uniqueResult();
- if (processInstance == null)
- {
- throw new JbpmException("no process instance was found with key " + key);
- }
-
+ public ProcessInstance loadProcessInstance(ProcessDefinition processDefinition, String key) {
+ ProcessInstance processInstance = getProcessInstance(processDefinition, key);
+ if (processInstance == null) {
+ throw new JbpmException("no process instance was found with key '" + key + "'");
}
- catch (Exception e)
- {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't load process instance with key '" + key + "'", e);
- }
return processInstance;
}
+ private void handle(Exception e) {
+ log.error(e);
+ if (jbpmSession != null) jbpmSession.handleException();
+ }
+
private static final Log log = LogFactory.getLog(GraphSession.class);
}
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/JbpmSchema.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/JbpmSchema.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/JbpmSchema.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -23,7 +23,6 @@
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -49,236 +48,266 @@
import org.hibernate.engine.Mapping;
import org.hibernate.mapping.ForeignKey;
import org.hibernate.mapping.Table;
-import org.hibernate.tool.hbm2ddl.SchemaExport;
+import org.hibernate.tool.hbm2ddl.DatabaseMetadata;
+import org.hibernate.tool.hbm2ddl.TableMetadata;
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;
+ final Configuration configuration;
+ final Settings settings;
ConnectionProvider connectionProvider = null;
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)
- {
- createSql = configuration.generateSchemaCreationScript(settings.getDialect());
- }
- return createSql;
+ public String[] getCreateSql() {
+ return configuration.generateSchemaCreationScript(settings.getDialect());
}
- public String[] getDropSql()
- {
- if (dropSql == null)
- {
- dropSql = configuration.generateDropSchemaScript(settings.getDialect());
- }
- return dropSql;
+ public String[] getDropSql() {
+ return configuration.generateDropSchemaScript(settings.getDialect());
}
- public String[] getCleanSql()
- {
- if (cleanSql == null)
- {
- new SchemaExport(configuration);
+ public String[] getCleanSql() {
+ Dialect dialect = settings.getDialect();
+ String catalog = settings.getDefaultCatalogName();
+ String schema = settings.getDefaultSchemaName();
+ Mapping mapping = configuration.buildMapping();
- Dialect dialect = settings.getDialect();
- String catalog = settings.getDefaultCatalogName();
- String schema = settings.getDefaultSchemaName();
+ // loop over all foreign key constraints
+ List<String> dropForeignKeysSql = new ArrayList<String>();
+ List<String> createForeignKeysSql = new ArrayList<String>();
+ List<String> deleteSql = new ArrayList<String>();
- // loop over all foreign key constraints
- List dropForeignKeysSql = new ArrayList();
- List createForeignKeysSql = new ArrayList();
- Iterator iter = configuration.getTableMappings();
- while (iter.hasNext())
- {
- Table table = (Table)iter.next();
- if (table.isPhysicalTable())
- {
- Iterator subIter = table.getForeignKeyIterator();
- while (subIter.hasNext())
- {
- ForeignKey fk = (ForeignKey)subIter.next();
+ for (Iterator<?> ti = configuration.getTableMappings(); ti.hasNext();) {
+ Table table = (Table) ti.next();
+ if (!table.isPhysicalTable()) continue;
- if (fk.isPhysicalConstraint())
- {
- // collect the drop foreign key constraint sql
- String sqlDropString = fk.sqlDropString(dialect, catalog, schema);
- dropForeignKeysSql.add(sqlDropString);
+ for (Iterator<?> fki = table.getForeignKeyIterator(); fki.hasNext();) {
+ ForeignKey fk = (ForeignKey) fki.next();
+ if (!fk.isPhysicalConstraint()) continue;
- // and collect the create foreign key constraint sql
- String sqlCreateString = fk.sqlCreateString(dialect, mapping, catalog, schema);
- createForeignKeysSql.add(sqlCreateString);
- }
- }
- }
- }
+ // collect the drop foreign key sql
+ String sqlDropString = fk.sqlDropString(dialect, catalog, schema);
+ dropForeignKeysSql.add(sqlDropString);
- List deleteSql = new ArrayList();
- iter = configuration.getTableMappings();
- while (iter.hasNext())
- {
- Table table = (Table)iter.next();
- deleteSql.add("delete from " + table.getName());
+ // and collect the create foreign key sql
+ String sqlCreateString = fk.sqlCreateString(dialect, mapping, catalog, schema);
+ createForeignKeysSql.add(sqlCreateString);
}
+ 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);
+ // glue
+ // - drop foreign key constraints
+ // - delete contents of all tables
+ // - create foreign key constraints
+ // together to form the clean script
+ return concat(dropForeignKeysSql, deleteSql, createForeignKeysSql);
+ }
- cleanSql = (String[])cleanSqlList.toArray(new String[cleanSqlList.size()]);
+ private static String[] concat(List<?>... lists) {
+ int length = 0;
+ for (List<?> list : lists) {
+ length += list.size();
}
- return cleanSql;
+ String[] array = new String[length];
+ int index = 0;
+ for (List<?> list : lists) {
+ for (Object element : list) {
+ array[index++] = (String) element;
+ }
+ }
+ return array;
}
- public boolean hasJbpmTables()
- {
- return (getJbpmTables().size() > 0);
- }
-
- 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())
- {
- jbpmTableNames.add(table.getName());
+ public List<String> getTableNames() {
+ List<String> tableNames = new ArrayList<String>();
+ for (Iterator<?> iter = configuration.getTableMappings(); iter.hasNext();) {
+ Table table = (Table) iter.next();
+ if (table.isPhysicalTable()) {
+ tableNames.add(table.getName());
}
}
- return jbpmTableNames;
+ return tableNames;
}
-
- public Map getJbpmTablesRecordCount() {
- Map recordCounts = new HashMap();
-
- String sql = null;
-
- try
- {
- Iterator iter = getJbpmTables().iterator();
+ public Map<String, Integer> getRecordCountPerTable() {
+ Map<String, Integer> recordCounts = new HashMap<String, Integer>();
+ try {
createConnection();
- while (iter.hasNext()) {
- statement = connection.createStatement();
- String tableName = (String) iter.next();
- sql = "SELECT COUNT(*) FROM "+tableName;
+ Statement statement = connection.createStatement();
+ for (String tableName : getTableNames()) {
+ String sql = "SELECT COUNT(*) FROM " + tableName;
ResultSet resultSet = statement.executeQuery(sql);
resultSet.next();
- int count = resultSet.getInt(1);
+ recordCounts.put(tableName, resultSet.getInt(1));
resultSet.close();
- statement.close();
- recordCounts.put(tableName, count);
}
+ statement.close();
}
- catch (SQLException e)
- {
- throw new JbpmException("couldn't execute sql '" + sql + "'", e);
+ catch (SQLException e) {
+ throw new JbpmException("could not count records", e);
}
- finally
- {
+ finally {
closeConnection();
}
-
return recordCounts;
}
- public void dropSchema()
- {
- execute(getDropSql());
+ public void dropSchema() {
+ try {
+ execute(getDropSql());
+ }
+ catch (SQLException e) {
+ throw new JbpmException("could not drop schema", e);
+ }
}
- public void createSchema()
- {
- execute(getCreateSql());
+ public void createSchema() {
+ try {
+ execute(getCreateSql());
+ }
+ catch (SQLException e) {
+ throw new JbpmException("could not create schema", e);
+ }
}
- public void cleanSchema()
- {
- if (getJbpmTables().size() > 0)
+ public void cleanSchema() {
+ try {
execute(getCleanSql());
+ }
+ catch (SQLException e) {
+ throw new JbpmException("could not clean schema", e);
+ }
}
- 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 boolean tableExists(String tableName) {
+ Table table = findTableMapping(tableName);
+ try {
+ createConnection();
+ return getTableMetadata(table) != null;
+ }
+ catch (SQLException e) {
+ throw new JbpmException("could not tell whether table exists: " + tableName, e);
+ }
+ finally {
+ closeConnection();
+ }
+ }
+
+ public void createTable(String tableName) {
+ Table table = findTableMapping(tableName);
+ String sql = table.sqlCreateString(settings.getDialect(), configuration.buildMapping(),
+ settings.getDefaultCatalogName(), settings.getDefaultSchemaName());
+ try {
+ execute(sql);
+ }
+ catch (SQLException e) {
+ throw new JbpmException("could not create table: " + tableName, e);
+ }
+ }
+
+ public void updateTable(String tableName) {
+ Table table = findTableMapping(tableName);
+ try {
+ createConnection();
+ Iterator<?> sqls = table.sqlAlterStrings(settings.getDialect(), configuration.buildMapping(),
+ getTableMetadata(table), settings.getDefaultCatalogName(),
+ settings.getDefaultSchemaName());
+
+ Statement statement = connection.createStatement();
+ while (sqls.hasNext()) {
+ String sql = (String) sqls.next();
+ statement.executeUpdate(sql);
+ }
+ statement.close();
+ }
+ catch (SQLException e) {
+ throw new JbpmException("could not update table: " + tableName, e);
+ }
+ finally {
+ closeConnection();
+ }
+ }
+
+ private Table findTableMapping(String tableName) {
+ for (Iterator<?> i = configuration.getTableMappings(); i.hasNext();) {
+ Table table = (Table) i.next();
+ if (tableName.equals(table.getName())) {
+ return table;
+ }
+ }
+ throw new JbpmException("no mapping found for table: " + tableName);
+ }
+
+ private TableMetadata getTableMetadata(Table table) throws SQLException {
+ DatabaseMetadata databaseMetadata = new DatabaseMetadata(connection, settings.getDialect());
+ return databaseMetadata.getTableMetadata(table.getName(),
+ table.getSchema() == null ? settings.getDefaultSchemaName() : table.getSchema(),
+ table.getCatalog() == null ? settings.getDefaultCatalogName() : table.getCatalog(),
+ table.isQuoted());
+ }
+
+ 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>]]");
@@ -286,24 +315,20 @@
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,102 +336,59 @@
return configuration;
}
- void saveSqlScript(String fileName, String[] sql) throws FileNotFoundException
- {
- FileOutputStream fileOutputStream = new FileOutputStream(fileName);
- try
- {
- PrintStream printStream = new PrintStream(fileOutputStream);
- for (int i = 0; i < sql.length; i++)
- {
- printStream.println(sql[i] + getSqlDelimiter());
+ void saveSqlScript(String fileName, String[] sql) throws IOException {
+ PrintStream out = new PrintStream(new FileOutputStream(fileName));
+ try {
+ for (String line : sql) {
+ out.println(line + getSqlDelimiter());
}
}
- finally
- {
- try
- {
- fileOutputStream.close();
- }
- catch (IOException e)
- {
- log.debug("failed to close file", e);
- }
+ finally {
+ out.close();
}
}
- public void execute(String[] sqls)
- {
- String sql = null;
+ void execute(String... sqls) throws SQLException {
boolean showSql = settings.isShowSqlEnabled();
-
- try
- {
+ try {
createConnection();
- statement = connection.createStatement();
-
- for (int i = 0; i < sqls.length; i++)
- {
- sql = sqls[i];
-
- if (showSql)
- log.debug(sql);
+ Statement statement = connection.createStatement();
+ for (String sql : sqls) {
+ if (showSql) System.out.println(sql);
statement.executeUpdate(sql);
}
-
+ statement.close();
}
- catch (SQLException e)
- {
- throw new JbpmException("couldn't execute sql '" + sql + "'", e);
- }
- finally
- {
+ finally {
closeConnection();
}
}
- void closeConnection()
- {
- if (statement != null)
- {
- try
- {
- statement.close();
- }
- catch (SQLException e)
- {
- log.debug("could not close jdbc statement", e);
- }
- }
- if (connection != null)
- {
- try
- {
- JDBCExceptionReporter.logWarnings(connection.getWarnings());
- connection.clearWarnings();
- connectionProvider.closeConnection(connection);
- connectionProvider.close();
- }
- 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()
- {
+ void closeConnection() {
+ if (connection != null) {
+ try {
+ JDBCExceptionReporter.logAndClearWarnings(connection);
+ connectionProvider.closeConnection(connection);
+ }
+ catch (SQLException e) {
+ log.debug("could not close " + connection, e);
+ }
+ finally {
+ connectionProvider.close();
+ }
+ }
+ }
+
+ public Properties getProperties() {
return configuration.getProperties();
}
@@ -414,10 +396,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/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/JobSession.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/JobSession.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/JobSession.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -21,213 +21,246 @@
*/
package org.jbpm.db;
+import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.jbpm.JbpmException;
-import org.jbpm.graph.def.Action;
import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.graph.exe.Token;
import org.jbpm.job.Job;
import org.jbpm.job.Timer;
+import org.jbpm.util.CollectionUtil;
public class JobSession {
- private Session session;
+ private final Session session;
public JobSession(Session session) {
this.session = session;
}
public Job getFirstAcquirableJob(String lockOwner) {
- Job job = null;
try {
- Query query = session.getNamedQuery("JobSession.getFirstAcquirableJob");
- query.setString("lockOwner", lockOwner);
- query.setTimestamp("now", new Date());
- query.setMaxResults(1);
- job = (Job) query.uniqueResult();
-
- } catch (Exception e) {
- log.error(e);
- throw new JbpmException("couldn't get acquirable jobs", e);
+ return (Job) session.getNamedQuery("JobSession.getFirstAcquirableJob")
+ .setString("lockOwner", lockOwner)
+ .setTimestamp("now", new Date())
+ .setMaxResults(1)
+ .uniqueResult();
}
- return job;
+ catch (HibernateException e) {
+ throw new JbpmException("could not get first acquirable job", e);
+ }
}
- 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();
-
- } catch (Exception e) {
- log.error(e);
- throw new JbpmException("couldn't find exclusive jobs for thread '"+lockOwner+"' and process instance '"+processInstance+"'", e);
+ List<?> jobs = session.getNamedQuery("JobSession.findExclusiveJobs")
+ .setString("lockOwner", lockOwner)
+ .setTimestamp("now", new Date())
+ .setParameter("processInstance", processInstance)
+ .list();
+ return CollectionUtil.checkList(jobs, Job.class);
}
- return jobs;
+ catch (HibernateException e) {
+ throw new JbpmException("could not find exclusive jobs owned by '"
+ + lockOwner
+ + "' for "
+ + processInstance, e);
+ }
}
-
- /**
- * find all jobs
- */
+
public List<Job> findJobsByToken(Token token) {
try {
- Query query = session.getNamedQuery("JobSession.findJobsByToken");
- query.setParameter("token", token);
- List<Job> jobs = query.list();
- return jobs;
- } catch (Exception e) {
- throw new JbpmException("couldn't find jobs for token '"+token+"'", e);
+ List<?> jobs = session.getNamedQuery("JobSession.findJobsByToken")
+ .setParameter("token", token)
+ .list();
+ return CollectionUtil.checkList(jobs, Job.class);
}
+ catch (HibernateException e) {
+ throw new JbpmException("could not find jobs for " + token, e);
+ }
}
- public Job getFirstDueJob(String lockOwner, Collection jobIdsToIgnore) {
- Job job = null;
+ public Job getFirstDueJob(String lockOwner, Collection<Long> monitoredJobs) {
try {
- Query query = null;
- if ( (jobIdsToIgnore==null)
- || (jobIdsToIgnore.isEmpty() )
- ) {
+ Query query;
+ if (monitoredJobs == null || monitoredJobs.isEmpty()) {
query = session.getNamedQuery("JobSession.getFirstDueJob");
- query.setString("lockOwner", lockOwner);
-
- } else {
- query = session.getNamedQuery("JobSession.getFirstDueJobExlcMonitoredJobs");
- query.setString("lockOwner", lockOwner);
- query.setParameterList("jobIdsToIgnore", jobIdsToIgnore);
-
}
- query.setMaxResults(1);
- job = (Job) query.uniqueResult();
-
- } catch (Exception e) {
- log.error(e);
- throw new JbpmException("couldn't get acquirable jobs", e);
+ else {
+ query = session.getNamedQuery("JobSession.getFirstDueJobExcludingMonitoredJobs");
+ query.setParameterList("monitoredJobIds", monitoredJobs);
+ }
+ return (Job) query.setString("lockOwner", lockOwner)
+ .setMaxResults(1)
+ .uniqueResult();
}
- return job;
+ catch (HibernateException e) {
+ throw new JbpmException("could not get first due job owned by '"
+ + lockOwner
+ + "' ignoring jobs "
+ + monitoredJobs, e);
+ }
}
public void saveJob(Job job) {
- session.saveOrUpdate(job);
- if (job instanceof Timer) {
- Timer timer = (Timer) job;
- Action action = timer.getAction();
- if (action != null && !session.contains(action)) {
- log.debug("cascading timer save to action");
- session.save(action);
- }
+ try {
+ session.save(job);
}
+ catch (HibernateException e) {
+ throw new JbpmException("could not save " + job, e);
+ }
}
public void deleteJob(Job job) {
- session.delete(job);
+ try {
+ session.delete(job);
+ log.debug("deleted " + job);
+ }
+ catch (HibernateException e) {
+ throw new JbpmException("could not delete " + job, e);
+ }
}
public Job loadJob(long jobId) {
try {
return (Job) session.load(Job.class, new Long(jobId));
- } catch (Exception e) {
- log.error(e);
- throw new JbpmException("couldn't load job '"+jobId+"'", e);
}
+ catch (HibernateException e) {
+ throw new JbpmException("could not load job " + jobId, e);
+ }
}
public Timer loadTimer(long timerId) {
try {
return (Timer) session.load(Timer.class, new Long(timerId));
- } catch (Exception e) {
- log.error(e);
- throw new JbpmException("couldn't load timer " + timerId, e);
}
+ catch (HibernateException e) {
+ throw new JbpmException("could not load timer " + timerId, e);
+ }
}
- public List 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]);
+ public List<Job> loadJobs(long... jobIds) {
+ try {
+ List<?> jobs = session.createCriteria(Job.class)
+ .add(Restrictions.in("id", toObjectArray(jobIds)))
+ .list();
+ return CollectionUtil.checkList(jobs, Job.class);
}
- return session.createCriteria(Job.class)
- .add(Restrictions.in("id", jobs))
- .list();
+ catch (HibernateException e) {
+ throw new JbpmException("could not load jobs " + Arrays.toString(jobIds), e);
+ }
}
+ private static Long[] toObjectArray(long[] primitives) {
+ final int length = primitives.length;
+ Long[] objects = new Long[length];
+ for (int i = 0; i < length; i++) {
+ objects[i] = primitives[i];
+ }
+ return objects;
+ }
+
public Job getJob(long jobId) {
try {
return (Job) session.get(Job.class, new Long(jobId));
- } catch (Exception e) {
- log.error(e);
- throw new JbpmException("couldn't get job '"+jobId+"'", e);
}
+ catch (HibernateException e) {
+ throw new JbpmException("could not get job " + jobId, e);
+ }
}
public void suspendJobs(Token token) {
try {
- Query query = session.getNamedQuery("JobSession.suspendJobs");
- query.setParameter("token", token);
- query.executeUpdate();
-
- } catch (Exception e) {
- log.error(e);
- throw new JbpmException("couldn't suspend jobs for "+token, e);
+ session.getNamedQuery("JobSession.suspendJobs").setParameter("token", token).executeUpdate();
}
+ catch (HibernateException e) {
+ throw new JbpmException("could not suspend jobs for " + token, e);
+ }
}
public void resumeJobs(Token token) {
try {
- Query query = session.getNamedQuery("JobSession.resumeJobs");
- query.setParameter("token", token);
- query.executeUpdate();
-
- } catch (Exception e) {
- log.error(e);
- throw new JbpmException("couldn't resume jobs for "+token, e);
+ session.getNamedQuery("JobSession.resumeJobs").setParameter("token", token).executeUpdate();
}
+ catch (HibernateException e) {
+ throw new JbpmException("could not resume jobs for " + token, e);
+ }
}
public void deleteTimersByName(String name, Token token) {
try {
- log.debug("deleting timers by name '" + name + "' for " + token);
- Query query = session.getNamedQuery("JobSession.deleteTimersByName");
- query.setString("name", name);
- query.setParameter("token", token);
- int entityCount = query.executeUpdate();
- log.debug(entityCount + " timers by name '" + name + "' for " + token + " were deleted");
- } catch (Exception e) {
- log.error(e);
- throw new JbpmException("couldn't delete timers by name '" + name + "' for " + token, e);
+ // delete unowned timers
+ int entityCount = session.getNamedQuery("JobSession.deleteTimersByName")
+ .setString("name", name)
+ .setParameter("token", token)
+ .executeUpdate();
+ log.debug("deleted " + entityCount + " timers by name '" + name + "' for " + token);
+
+ // prevent further repetitions
+ List<?> timers = session.getNamedQuery("JobSession.findRepeatingTimersByName")
+ .setString("name", name)
+ .setParameter("token", token)
+ .list();
+ preventFurtherRepetitions(timers);
}
+ catch (HibernateException e) {
+ throw new JbpmException("could not delete timers by name '" + name + "' for " + token, e);
+ }
}
public void deleteJobsForProcessInstance(ProcessInstance processInstance) {
- log.debug("deleting timers for "+processInstance);
- Query query = session.getNamedQuery("JobSession.deleteTimersForProcessInstance");
- query.setParameter("processInstance", processInstance);
- int entityCount = query.executeUpdate();
- log.debug(entityCount+" remaining timers for "+processInstance+" were deleted");
+ try {
+ // delete node execution jobs
+ int entityCount = session.getNamedQuery("JobSession.deleteExecuteNodeJobsForProcessInstance")
+ .setParameter("processInstance", processInstance)
+ .executeUpdate();
+ log.debug("deleted " + entityCount + " execute-node-jobs for " + processInstance);
- log.debug("deleting execute-node-jobs for "+processInstance);
- query = session.getNamedQuery("JobSession.deleteExecuteNodeJobsForProcessInstance");
- query.setParameter("processInstance", processInstance);
- entityCount = query.executeUpdate();
- log.debug(entityCount+" remaining execute-node-jobs for "+processInstance+" were deleted");
+ // delete unowned timers
+ entityCount = session.getNamedQuery("JobSession.deleteTimersForProcessInstance")
+ .setParameter("processInstance", processInstance)
+ .executeUpdate();
+ log.debug("deleted " + entityCount + " timers for " + processInstance);
+
+ // prevent further repetitions
+ List<?> timers = session.getNamedQuery("JobSession.findRepeatingTimersForProcessInstance")
+ .setParameter("processInstance", processInstance)
+ .list();
+ preventFurtherRepetitions(timers);
+ }
+ catch (HibernateException e) {
+ throw new JbpmException("could not delete jobs for " + processInstance, e);
+ }
}
+ private static void preventFurtherRepetitions(List<?> timers) {
+ if (!timers.isEmpty()) {
+ for (Timer timer : CollectionUtil.checkList(timers, Timer.class)) {
+ timer.setRepeat(null);
+ }
+ log.debug("prevented further repetitions of " + timers);
+ }
+ }
- public List findJobsWithOverdueLockTime(Date treshold) {
- Query query = session.getNamedQuery("JobSession.findJobsWithOverdueLockTime");
- query.setDate("now", treshold);
- return query.list();
+ public List<Job> findJobsWithOverdueLockTime(Date threshold) {
+ try {
+ List<?> jobs = session.getNamedQuery("JobSession.findJobsWithOverdueLockTime")
+ .setDate("threshold", threshold)
+ .list();
+ return CollectionUtil.checkList(jobs, Job.class);
+ }
+ catch (HibernateException e) {
+ throw new JbpmException("could not find jobs with lock time over " + threshold, e);
+ }
}
private static Log log = LogFactory.getLog(JobSession.class);
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/TaskMgmtSession.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/TaskMgmtSession.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/db/TaskMgmtSession.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -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,131 @@
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;
-
+
+ final Session session;
+ final JbpmSession jbpmSession;
+
public TaskMgmtSession(JbpmSession jbpmSession) {
- this.jbpmSession = jbpmSession;
this.session = jbpmSession.getSession();
+ this.jbpmSession = jbpmSession;
}
-
+
public TaskMgmtSession(Session session) {
this.session = session;
- this.jbpmSession = new JbpmSession(session);
+ this.jbpmSession = null;
}
/**
- * 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) {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't get task instances list for actor '"+actorId+"'", e);
- }
- return result;
+ return CollectionUtil.checkList(query.list(), TaskInstance.class);
+ }
+ catch (Exception e) {
+ handle(e);
+ 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.
+ *
+ * @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()]));
+ public List<TaskInstance> findTaskInstances(List<String> actorIds) {
+ try {
+ Query query = session.getNamedQuery("TaskMgmtSession.findTaskInstancesByActorIds");
+ query.setParameterList("actorIds", actorIds);
+ return CollectionUtil.checkList(query.list(), TaskInstance.class);
+ }
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("couldn't get task instances list for actors '" + actorIds + "'", e);
+ }
}
/**
* get all the task instances for all the given actorIds.
*/
- public List findTaskInstances(String[] actorIds) {
- List result = null;
- try {
- Query query = session.getNamedQuery("TaskMgmtSession.findTaskInstancesByActorIds");
- query.setParameterList("actorIds", actorIds);
- result = query.list();
- } catch (Exception e) {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't get task instances list for actors '"+actorIds+"'", e);
- }
- return result;
+ public List<TaskInstance> findTaskInstances(String[] actorIds) {
+ return findTaskInstances(Arrays.asList(actorIds));
}
/**
- * 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(String actorId) {
- List result = null;
+ 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) {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't get pooled task instances list for actor '"+actorId+"'", e);
- }
- return result;
+ query.setString("actorId", actorId);
+ List<Long> taskInstanceIds = CollectionUtil.checkList(query.list(), Long.class);
+ return findTaskInstancesByIds(taskInstanceIds);
+ }
+ catch (Exception e) {
+ handle(e);
+ 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) {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't get pooled task instances list for actors '"+actorIds+"'", e);
- }
- return result;
+ List<Long> taskInstanceIds = CollectionUtil.checkList(query.list(), Long.class);
+ return findTaskInstancesByIds(taskInstanceIds);
+ }
+ catch (Exception e) {
+ handle(e);
+ 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) {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't get task instances by token '"+tokenId+"'", e);
- }
- return result;
+ return CollectionUtil.checkList(query.list(), TaskInstance.class);
+ }
+ catch (Exception e) {
+ handle(e);
+ 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) {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't get task instances by process instance '"+processInstance+"'", e);
- }
- return result;
+ return CollectionUtil.checkList(query.list(), TaskInstance.class);
+ }
+ catch (Exception e) {
+ handle(e);
+ 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 +166,14 @@
TaskInstance taskInstance = null;
try {
taskInstance = (TaskInstance) session.load(TaskInstance.class, new Long(taskInstanceId));
- } catch (Exception e) {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't get task instance '"+taskInstanceId+"'", e);
- }
+ }
+ catch (Exception e) {
+ handle(e);
+ throw new JbpmException("couldn't get task instance '" + taskInstanceId + "'", e);
+ }
return taskInstance;
}
-
+
/**
* get the task instance for a given task instance-id.
*/
@@ -206,27 +181,38 @@
TaskInstance taskInstance = null;
try {
taskInstance = (TaskInstance) session.get(TaskInstance.class, new Long(taskInstanceId));
- } catch (Exception e) {
- log.error(e);
- jbpmSession.handleException();
- throw new JbpmException("couldn't get task instance '"+taskInstanceId+"'", e);
- }
+ }
+ catch (Exception e) {
+ handle(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) {
+ handle(e);
+ throw new JbpmException("couldn't get task instances by ids '" + taskInstanceIds + "'", e);
+ }
+ }
return result;
}
+ private void handle(Exception exception) {
+ log.error(exception);
+ if (jbpmSession != null)
+ jbpmSession.handleException();
+ }
+
private static final Log log = LogFactory.getLog(TaskMgmtSession.class);
}
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/graph/def/Action.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/graph/def/Action.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/graph/def/Action.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -58,17 +58,14 @@
public String toString() {
String toString = null;
- if (name!=null) {
- toString = "action["+name+"]";
- } else if (actionExpression!=null) {
- toString = "action["+actionExpression+"]";
+ if (actionExpression!=null) {
+ toString = "Action("+actionExpression+')';
} else {
- String className = getClass().getName();
- className = className.substring(className.lastIndexOf('.')+1);
+ String className = getClass().getSimpleName();
if (name!=null) {
- toString = className+"("+name+")";
+ toString = className+'('+name+')';
} else {
- toString = className+"("+Integer.toHexString(System.identityHashCode(this))+")";
+ toString = className+'@'+Integer.toHexString(hashCode());
}
}
return toString;
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/graph/def/GraphElement.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/graph/def/GraphElement.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/graph/def/GraphElement.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -177,7 +177,7 @@
// event handling ///////////////////////////////////////////////////////////
public void fireEvent(String eventType, ExecutionContext executionContext) {
- log.debug("event '" + eventType + "' on '" + this + "' for '" + executionContext.getToken() + "'");
+ log.debug("event '" + eventType + "' on " + this + " for " + executionContext.getToken());
try {
executionContext.setEventSource(this);
@@ -271,7 +271,7 @@
executionContext.setAction(action);
// execute the action
- log.debug("executing action '" + action + "'");
+ log.debug("executing " + action);
String lockOwnerId = "token[" + token.getId() + "]";
try {
if (actionMustBeLocked) {
@@ -472,14 +472,8 @@
}
public String toString() {
- String className = getClass().getName();
- className = className.substring(className.lastIndexOf('.') + 1);
- if (name != null) {
- className = className + "(" + name + ")";
- } else {
- className = className + "(" + Integer.toHexString(System.identityHashCode(this)) + ")";
- }
- return className;
+ return getClass().getSimpleName() + (name != null ? '(' + name + ')'
+ : '@' + Integer.toHexString(hashCode()));
}
// equals ///////////////////////////////////////////////////////////////////
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/graph/exe/ProcessInstance.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/graph/exe/ProcessInstance.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/graph/exe/ProcessInstance.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -515,7 +515,8 @@
public String toString()
{
- return "ProcessInstance" + (key != null ? '(' + key + ')' : "@" + Integer.toHexString(hashCode()));
+ return "ProcessInstance" + (key != null ? '(' + key + ')'
+ : id != 0 ? "(" + id + ')' : '@' + Integer.toHexString(hashCode()));
}
// getters and setters //////////////////////////////////////////////////////
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/graph/exe/Token.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/graph/exe/Token.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/graph/exe/Token.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -466,7 +466,7 @@
public String toString()
{
- return "Token(" + getFullName() + ")";
+ return "Token(" + getFullName() + ')';
}
public boolean hasEnded()
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/job/Job.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/job/Job.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/job/Job.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -58,7 +58,7 @@
public abstract boolean execute(JbpmContext jbpmContext) throws Exception;
public String toString() {
- return "job["+id+"]";
+ return "Job("+id+')';
}
public String toStringLongFormat() {
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/job/Timer.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/job/Timer.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/job/Timer.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -107,25 +107,25 @@
}
public String toString() {
- StringBuffer buffer = new StringBuffer("Timer");
+ StringBuilder text = new StringBuilder("Timer");
if (name != null || dueDate != null) {
- buffer.append("(");
- if (name!=null) {
- buffer.append(name).append(",");
- }
- if (dueDate!=null) {
- buffer.append(formatDueDate(dueDate)).append(",");
- }
+ text.append('(');
+
+ if (name!=null)
+ text.append(name).append(",");
+ if (dueDate!=null)
+ text.append(formatDueDate(dueDate)).append(",");
if (taskInstance!=null)
- buffer.append(taskInstance).append(",");
+ text.append(taskInstance).append(",");
+
if (token!=null)
- buffer.append(token);
+ text.append(token);
else if (processInstance!=null)
- buffer.append(processInstance);
+ text.append(processInstance);
- buffer.append(")");
+ text.append(')');
}
- return buffer.toString();
+ return text.toString();
}
public static String formatDueDate(Date date) {
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/job/executor/LockMonitorThread.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/job/executor/LockMonitorThread.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/job/executor/LockMonitorThread.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -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;
@@ -11,18 +10,20 @@
import org.jbpm.db.JobSession;
import org.jbpm.job.Job;
import org.jbpm.persistence.JbpmPersistenceException;
+import org.jbpm.persistence.db.StaleObjectLogConfigurer;
import org.jbpm.svc.Services;
public class LockMonitorThread extends Thread {
-
+
JbpmConfiguration jbpmConfiguration;
int lockMonitorInterval;
int maxLockTime;
int lockBufferTime;
- boolean isActive = true;
+ volatile boolean isActive = true;
- public LockMonitorThread(JbpmConfiguration jbpmConfiguration, int lockMonitorInterval, int maxLockTime, int lockBufferTime) {
+ public LockMonitorThread(JbpmConfiguration jbpmConfiguration, int lockMonitorInterval,
+ int maxLockTime, int lockBufferTime) {
this.jbpmConfiguration = jbpmConfiguration;
this.lockMonitorInterval = lockMonitorInterval;
this.maxLockTime = maxLockTime;
@@ -34,55 +35,59 @@
while (isActive) {
try {
unlockOverdueJobs();
- if ( (isActive)
- && (lockMonitorInterval>0)
- ) {
+ if ((isActive) && (lockMonitorInterval > 0)) {
sleep(lockMonitorInterval);
}
- } catch (InterruptedException e) {
- log.info("lock monitor thread '"+getName()+"' got interrupted");
- } catch (Exception e) {
- log.error("exception in lock monitor thread. waiting "+lockMonitorInterval+" milliseconds", e);
+ }
+ catch (InterruptedException e) {
+ log.info("lock monitor thread '" + getName() + "' got interrupted");
+ }
+ catch (Exception e) {
+ log.error("exception in lock monitor thread. waiting "
+ + lockMonitorInterval
+ + " milliseconds", e);
try {
sleep(lockMonitorInterval);
- } catch (InterruptedException e2) {
+ }
+ catch (InterruptedException e2) {
log.debug("delay after exception got interrupted", e2);
}
}
}
- } catch (Exception e) {
+ }
+ catch (Exception e) {
log.error("exception in lock monitor thread", e);
- } finally {
- log.info(getName()+" leaves cyberspace");
}
+ finally {
+ log.info(getName() + " leaves cyberspace");
+ }
}
-
protected void unlockOverdueJobs() {
+ List<Job> overdueJobs = null;
JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
try {
+ Date threshold = new Date(System.currentTimeMillis() - maxLockTime - lockBufferTime);
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
- log.debug("unlocking "+job+ " owned by thread "+job.getLockOwner());
+ overdueJobs = jobSession.findJobsWithOverdueLockTime(threshold);
+ for (Job job : overdueJobs) {
+ log.debug("unlocking " + job + " owned by thread " + job.getLockOwner());
job.setLockOwner(null);
job.setLockTime(null);
- jobSession.saveJob(job);
}
-
- } 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 unlock overdue jobs");
- } else {
+ log.debug("optimistic locking failed, could not unlock overdue jobs: " + overdueJobs);
+ StaleObjectLogConfigurer.getStaleObjectExceptionsLog().error(
+ "problem unlocking overdue jobs: optimistic locking failed", e);
+ }
+ else {
throw e;
}
}
@@ -93,18 +98,16 @@
* @deprecated As of jBPM 3.2.3, replaced by {@link #deactivate()}
*/
public void setActive(boolean isActive) {
- if (isActive == false)
- deactivate();
+ 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/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/msg/db/DbMessageService.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/msg/db/DbMessageService.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/msg/db/DbMessageService.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -49,7 +49,7 @@
public void send(Job job) {
jobSession.saveJob(job);
- log.debug("saved job["+job.getId()+", "+job.getClass().getName()+"]");
+ log.debug("saved "+job);
hasProducedJobs = true;
}
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/scheduler/def/CreateTimerAction.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/scheduler/def/CreateTimerAction.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/scheduler/def/CreateTimerAction.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -113,7 +113,7 @@
} else {
durationString = dueDate;
}
- if (baseDate != null && (durationString == null || "".equals(durationString))) {
+ if (baseDate != null && (durationString == null || durationString.length() == 0)) {
dueDateDate = baseDate;
} else {
duration = new Duration(durationString);
Added: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/util/CollectionUtil.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/util/CollectionUtil.java (rev 0)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/java/org/jbpm/util/CollectionUtil.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -0,0 +1,105 @@
+/*
+ * 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.Map;
+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) {
+ type.cast(element);
+ }
+ }
+ 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) {
+ type.cast(element);
+ }
+ }
+ 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) {
+ type.cast(element);
+ }
+ }
+ return (Set<E>) set;
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <K, V> Map<K, V> checkMap(Map<?, ?> map, Class<K> keyType, Class<V> valueType) {
+ if (DEBUG) {
+ for (Map.Entry<?, ?> entry : map.entrySet()) {
+ keyType.cast(entry.getKey());
+ valueType.cast(entry.getValue());
+ }
+ }
+ return (Map<K, V>) map;
+ }
+}
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/resources/org/jbpm/db/hibernate.queries.hbm.xml
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/resources/org/jbpm/db/hibernate.queries.hbm.xml 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/main/resources/org/jbpm/db/hibernate.queries.hbm.xml 2009-02-22 03:15:07 UTC (rev 3994)
@@ -1,8 +1,7 @@
<?xml version="1.0"?>
-
<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
@@ -15,14 +14,14 @@
from org.jbpm.graph.def.ProcessDefinition pd
]]>
</query>
-
+
<query name="GraphSession.NumberOfDeployedProcesses">
<![CDATA[
select count (distinct pd.name)
from org.jbpm.graph.def.ProcessDefinition pd
]]>
</query>
-
+
<query name="GraphSession.NumberOfActiveProcessInstances">
<![CDATA[
select count (pi.id)
@@ -30,7 +29,7 @@
where pi.end is null
]]>
</query>
-
+
<query name="GraphSession.findLatestProcessDefinitionQuery">
<![CDATA[
select pd
@@ -39,7 +38,7 @@
order by pd.version desc
]]>
</query>
-
+
<query name="GraphSession.findProcessDefinitionByNameAndVersion">
<![CDATA[
select pd
@@ -48,7 +47,7 @@
and pd.version = :version
]]>
</query>
-
+
<query name="GraphSession.findAllProcessDefinitions">
<![CDATA[
select pd
@@ -56,7 +55,7 @@
order by pd.name, pd.version desc
]]>
</query>
-
+
<query name="GraphSession.findAllProcessDefinitionVersions">
<![CDATA[
select pd
@@ -65,34 +64,59 @@
order by pd.version desc
]]>
</query>
-
- <query name="GraphSession.findAllProcessInstancesForADefinition">
+
+ <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.findAllProcessInstancesForDefinition">
+ <![CDATA[
select pi
from org.jbpm.graph.exe.ProcessInstance as pi
where pi.processDefinition.id = :processDefinitionId
order by pi.start desc
]]>
</query>
-
+
+ <query name="GraphSession.findAllProcessInstanceIdsForDefinition">
+ <![CDATA[
+ select pi.id
+ from org.jbpm.graph.exe.ProcessInstance as pi
+ where pi.processDefinition.id = :processDefinitionId
+ ]]>
+ </query>
+
<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 +134,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>
@@ -122,17 +146,17 @@
order by pi.start desc
]]>
</query>
-
+
<query name="GraphSession.findSubProcessInstances">
<![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
]]>
</query>
-
+
<query name="GraphSession.findTokensForProcessInNode">
<![CDATA[
select token
@@ -151,16 +175,16 @@
and token.node.name = :nodeName
]]>
</query>
-
+
<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>
-
+
<query name="GraphSession.findLogsForProcessInstance">
<![CDATA[
select pl
@@ -168,23 +192,14 @@
where pl.token.processInstance = :processInstance
]]>
</query>
-
-
- <query name="GraphSession.findTaskInstanceIdsForProcessInstance">
+
+ <query name="GraphSession.findTaskInstancesForProcessInstance">
<![CDATA[
- select t
- from org.jbpm.taskmgmt.exe.TaskInstance t
- where t.taskMgmtInstance.processInstance = :processInstance
+ select ti
+ from org.jbpm.taskmgmt.exe.TaskInstance ti
+ where ti.processInstance = :processInstance
]]>
</query>
-
- <query name="GraphSession.deleteTaskInstancesById">
- <![CDATA[
- delete
- from org.jbpm.taskmgmt.exe.TaskInstance t
- where t.id in (:taskInstanceIds)
- ]]>
- </query>
<query name="GraphSession.deleteJobsForProcessInstance">
<![CDATA[
@@ -218,7 +233,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
]]>
@@ -230,11 +245,10 @@
from org.jbpm.taskmgmt.def.Swimlane as swimlane
]]>
</query>
-
+
<!-- Logging -->
<!-- ########################### -->
-
<query name="LoggingSession.findLogsByToken">
<![CDATA[
select pl
@@ -243,11 +257,10 @@
order by pl.index
]]>
</query>
-
+
<!-- JobSession -->
<!-- ########################### -->
-
<query name="JobSession.getFirstAcquirableJob">
<![CDATA[
select job
@@ -255,7 +268,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 +282,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,19 +293,19 @@
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>
- <query name="JobSession.getFirstDueJobExlcMonitoredJobs">
+ <query name="JobSession.getFirstDueJobExcludingMonitoredJobs">
<![CDATA[
select job
from org.jbpm.job.Job as job
where ( (job.lockOwner is null) or (job.lockOwner = :lockOwner) )
- and job.id not in ( :jobIdsToIgnore )
+ and job.id not in ( :monitoredJobIds )
and job.retries > 0
- and job.isSuspended != true
+ and job.isSuspended = false
order by job.dueDate asc
]]>
</query>
@@ -318,20 +331,37 @@
delete from org.jbpm.job.Timer timer
where timer.token = :token
and timer.name = :name
- and (timer.lockOwner is null
- or timer.repeat is not null)
+ and timer.lockOwner is null
]]>
</query>
+ <query name="JobSession.findRepeatingTimersByName">
+ <![CDATA[
+ select timer
+ from org.jbpm.job.Timer timer
+ where timer.token = :token
+ and timer.name = :name
+ and timer.repeat is not null
+ ]]>
+ </query>
+
<query name="JobSession.deleteTimersForProcessInstance">
<![CDATA[
delete from org.jbpm.job.Timer timer
where timer.processInstance = :processInstance
- and (timer.lockOwner is null
- or timer.repeat is not null)
+ and timer.lockOwner is null
]]>
</query>
+ <query name="JobSession.findRepeatingTimersForProcessInstance">
+ <![CDATA[
+ select timer
+ from org.jbpm.job.Timer timer
+ where timer.processInstance = :processInstance
+ and timer.repeat is not null
+ ]]>
+ </query>
+
<query name="JobSession.deleteExecuteNodeJobsForProcessInstance">
<![CDATA[
delete from org.jbpm.job.ExecuteNodeJob job
@@ -339,7 +369,7 @@
and job.lockOwner is null
]]>
</query>
-
+
<query name="JobSession.findJobsByToken">
<![CDATA[
select job
@@ -348,16 +378,23 @@
]]>
</query>
+ <query name="JobSession.findJobsWithOverdueLockTime">
+ <![CDATA[
+ select job
+ from org.jbpm.job.Job as job
+ where job.lockTime > :threshold
+ ]]>
+ </query>
+
<!-- related to Tasks -->
<!-- ########################### -->
-
<query name="TaskMgmtSession.findTaskInstancesByActorId">
<![CDATA[
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 +404,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 +414,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 +428,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 +448,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>
@@ -437,14 +460,13 @@
where ti.id in ( :taskInstanceIds )
]]>
</query>
-
-
+
<query name="TaskMgmtSession.findOpenTasksOfProcessInstance">
<![CDATA[
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>
@@ -456,5 +478,5 @@
and task.taskNode.id = :taskNodeId
]]>
</query>
-
+
</hibernate-mapping>
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/db/DeleteProcessInstanceDbTest.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/db/DeleteProcessInstanceDbTest.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/db/DeleteProcessInstanceDbTest.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -15,18 +15,15 @@
+ " <state name='buy cheese' />"
+ "</process-definition>");
jbpmContext.deployProcessDefinition(processDefinition);
+ newTransaction();
try {
- newTransaction();
-
ProcessInstance processInstance = jbpmContext.newProcessInstance("make fondue");
processInstance.signal();
processInstance = saveAndReload(processInstance);
-
jbpmContext.getGraphSession().deleteProcessInstance(processInstance);
newTransaction();
-
assertDeleted(processInstance);
}
finally {
@@ -44,18 +41,15 @@
+ " </task-node>"
+ "</process-definition>");
jbpmContext.deployProcessDefinition(processDefinition);
+ newTransaction();
try {
- newTransaction();
-
ProcessInstance processInstance = jbpmContext.newProcessInstance("make fondue");
processInstance.signal();
processInstance = saveAndReload(processInstance);
-
jbpmContext.getGraphSession().deleteProcessInstance(processInstance);
newTransaction();
-
assertDeleted(processInstance);
}
finally {
@@ -81,18 +75,16 @@
+ " </process-state>"
+ "</process-definition>");
jbpmContext.deployProcessDefinition(makeFondue);
- try {
- newTransaction();
+ newTransaction();
+ try {
ProcessInstance processInstance = jbpmContext.newProcessInstance("make fondue");
processInstance.signal();
processInstance = saveAndReload(processInstance);
-
jbpmContext.getGraphSession().deleteProcessInstance(processInstance);
newTransaction();
-
assertDeleted(processInstance.getRootToken().getProcessInstance());
assertDeleted(processInstance);
}
@@ -115,9 +107,8 @@
+ " <state name='bake bread' />"
+ "</process-definition>");
jbpmContext.deployProcessDefinition(makeFondue);
+ newTransaction();
try {
- newTransaction();
-
ProcessInstance processInstance = jbpmContext.newProcessInstance("make fondue");
ContextInstance contextInstance = processInstance.getContextInstance();
contextInstance.setVariable("a", "asterix");
@@ -134,11 +125,9 @@
contextInstance.setVariable("b", "janneke", bread);
processInstance = saveAndReload(processInstance);
-
jbpmContext.getGraphSession().deleteProcessInstance(processInstance);
newTransaction();
-
assertDeleted(processInstance);
}
finally {
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/graph/exe/SubProcessCancellationTest.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/graph/exe/SubProcessCancellationTest.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/graph/exe/SubProcessCancellationTest.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -1,76 +1,67 @@
package org.jbpm.graph.exe;
-import java.util.Iterator;
-
import org.jbpm.db.AbstractDbTestCase;
import org.jbpm.graph.def.ProcessDefinition;
import org.jbpm.taskmgmt.exe.TaskInstance;
-public class SubProcessCancellationTest extends AbstractDbTestCase
+public class SubProcessCancellationTest extends AbstractDbTestCase
{
- public void testWithSubProcess()
+ public void testWithSubProcess()
{
- ProcessDefinition subProcess = ProcessDefinition.parseXmlString(
- "<process-definition name='sub'>" +
- " <start-state>" +
- " <transition to='wait' />" +
- " </start-state>" +
- " <task-node name='wait'>" +
- " <task>" +
- " <timer duedate='2 seconds' class='MyTimerClass' />" +
- " </task>" +
- " <transition to='end' />" +
- " </task-node>" +
- " <end-state name='end' />" +
- "</process-definition>"
- );
+ ProcessDefinition subProcess = ProcessDefinition.parseXmlString("<process-definition name='sub'>"
+ + " <start-state>"
+ + " <transition to='wait' />"
+ + " </start-state>"
+ + " <task-node name='wait'>"
+ + " <task>"
+ + " <timer duedate='2 seconds' class='MyTimerClass' />"
+ + " </task>"
+ + " <transition to='end' />"
+ + " </task-node>"
+ + " <end-state name='end' />"
+ + "</process-definition>");
jbpmContext.deployProcessDefinition(subProcess);
-
- ProcessDefinition superProcess = ProcessDefinition.parseXmlString(
- "<process-definition name='super'>" +
- " <start-state>" +
- " <transition to='subprocess' />" +
- " </start-state>" +
- " <process-state name='subprocess'>" +
- " <sub-process name='sub' />" +
- " <transition to='s'/>" +
- " </process-state>" +
- " <state name='s' />" +
- "</process-definition>"
- );
+
+ ProcessDefinition superProcess = ProcessDefinition.parseXmlString("<process-definition name='super'>"
+ + " <start-state>"
+ + " <transition to='subprocess' />"
+ + " </start-state>"
+ + " <process-state name='subprocess'>"
+ + " <sub-process name='sub' />"
+ + " <transition to='s'/>"
+ + " </process-state>"
+ + " <state name='s' />"
+ + "</process-definition>");
jbpmContext.deployProcessDefinition(superProcess);
-
+
+ newTransaction();
try
{
- newTransaction();
-
ProcessInstance pi = jbpmContext.newProcessInstanceForUpdate("super");
pi.signal();
-
+
ProcessInstance subPi = pi.getRootToken().getSubProcessInstance();
assertEquals("wait", subPi.getRootToken().getNode().getName());
-
- newTransaction();
- pi = jbpmContext.loadProcessInstance(pi.getId());
- subPi = pi.getRootToken().getSubProcessInstance();
+ pi = saveAndReload(pi);
pi.end();
pi.getTaskMgmtInstance().endAll();
- jbpmContext.save(pi);
+ pi = saveAndReload(pi);
assertTrue(pi.hasEnded());
+ subPi = pi.getRootToken().getSubProcessInstance();
assertTrue(subPi.hasEnded());
- Iterator iter = subPi.getTaskMgmtInstance().getTaskInstances().iterator();
- while (iter.hasNext()) {
- TaskInstance taskInstance = (TaskInstance) iter.next();
+
+ for (TaskInstance taskInstance : subPi.getTaskMgmtInstance().getTaskInstances())
+ {
assertFalse(taskInstance.isSignalling());
assertFalse(taskInstance.hasEnded());
}
}
finally
{
- jbpmContext.getGraphSession().deleteProcessDefinition(superProcess.getId());
- jbpmContext.getGraphSession().deleteProcessDefinition(subProcess.getId());
+ graphSession.deleteProcessDefinition(superProcess.getId());
+ graphSession.deleteProcessDefinition(subProcess.getId());
}
}
}
Copied: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/jbpm2036 (from rev 3832, jbpm3/trunk/modules/core/src/test/java/org/jbpm/jbpm2036)
Deleted: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/jbpm2036/JBPM2036Test.java
===================================================================
--- jbpm3/trunk/modules/core/src/test/java/org/jbpm/jbpm2036/JBPM2036Test.java 2009-02-11 13:33:15 UTC (rev 3832)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/jbpm2036/JBPM2036Test.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -1,69 +0,0 @@
-package org.jbpm.jbpm2036;
-
-import org.jbpm.db.AbstractDbTestCase;
-import org.jbpm.graph.def.ActionHandler;
-import org.jbpm.graph.def.ProcessDefinition;
-import org.jbpm.graph.exe.ExecutionContext;
-import org.jbpm.graph.exe.ProcessInstance;
-import org.jbpm.graph.exe.Token;
-
-/**
- * StaleObjectStateException when timer ends process
- *
- * https://jira.jboss.org/jira/browse/JBPM-2036
- *
- * @author Thomas.Diesler at jboss.com
- * @since 11-Feb-2009
- */
-public class JBPM2036Test extends AbstractDbTestCase
-{
- public void testTimerAction()
- {
- if (true)
- {
- System.out.println("FIXME: [JBPM-2036] StaleObjectStateException when timer ends process");
- return;
- }
-
- ProcessDefinition pd = getProcessDefinition();
- jbpmContext.deployProcessDefinition(pd);
- newTransaction();
- try
- {
- ProcessInstance pi = pd.createProcessInstance();
- Token tok = pi.getRootToken();
- tok.signal();
- }
- finally {
- graphSession.deleteProcessDefinition(pd.getId());
- }
- }
-
- private ProcessDefinition getProcessDefinition()
- {
- ProcessDefinition pd = ProcessDefinition.parseXmlString("<process-definition name='jbpm2036' initial='start'>"
- + " <node name='start'>"
- + " <transition to='state1'/>"
- + " </node>"
- + " <state name='state1'>"
- + " <timer name='timer-to-end-with-repeat' duedate='1 second' repeat='5 seconds'>"
- + " <action class='" + TimerAction.class.getName() + "' />"
- + " </timer>"
- + " <transition to='end'/>"
- + " </state>"
- + " <end-state name='end' />"
- + "</process-definition>");
- return pd;
- }
-
- public static class TimerAction implements ActionHandler
- {
- private static final long serialVersionUID = 1L;
-
- public void execute(ExecutionContext executionContext) throws Exception
- {
- System.out.println("leaveNode");
- executionContext.leaveNode();
- }
- }
-}
Copied: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/jbpm2036/JBPM2036Test.java (from rev 3832, jbpm3/trunk/modules/core/src/test/java/org/jbpm/jbpm2036/JBPM2036Test.java)
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/jbpm2036/JBPM2036Test.java (rev 0)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/jbpm2036/JBPM2036Test.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -0,0 +1,78 @@
+package org.jbpm.jbpm2036;
+
+import org.jbpm.db.AbstractDbTestCase;
+import org.jbpm.graph.def.ActionHandler;
+import org.jbpm.graph.def.ProcessDefinition;
+import org.jbpm.graph.exe.ExecutionContext;
+import org.jbpm.graph.exe.ProcessInstance;
+
+/**
+ * StaleObjectStateException when repeating timer signals the token.
+ *
+ * @see <a href="https://jira.jboss.org/jira/browse/JBPM-2036">JBPM-2036</a>
+ * @author Thomas.Diesler at jboss.com
+ * @since 11-Feb-2009
+ */
+public class JBPM2036Test extends AbstractDbTestCase
+{
+ public void testTimerAction()
+ {
+ ProcessDefinition processDefinition = getProcessDefinition();
+ jbpmContext.deployProcessDefinition(processDefinition);
+
+ newTransaction();
+ try
+ {
+ ProcessInstance processInstance = new ProcessInstance(processDefinition);
+ processInstance.signal();
+ jbpmContext.save(processInstance);
+
+ processJobs(30000);
+
+ long piId = processInstance.getId();
+ assertTrue("expected process instance " + piId + " to have ended",
+ jbpmContext.loadProcessInstance(piId).hasEnded());
+ assertEquals(1, TimerAction.getExecutionCount());
+ }
+ finally
+ {
+ graphSession.deleteProcessDefinition(processDefinition.getId());
+ }
+ }
+
+ private ProcessDefinition getProcessDefinition()
+ {
+ return ProcessDefinition.parseXmlString("<process-definition name='jbpm2036'>"
+ + " <start-state name='start'>"
+ + " <transition to='midway'/>"
+ + " </start-state>"
+ + " <state name='midway'>"
+ + " <timer name='chaos' duedate='1 second' repeat='5 seconds'>"
+ + " <action class='"
+ + TimerAction.class.getName()
+ + "' />"
+ + " </timer>"
+ + " <transition to='end'/>"
+ + " </state>"
+ + " <end-state name='end' />"
+ + "</process-definition>");
+ }
+
+ public static class TimerAction implements ActionHandler
+ {
+ private static int executionCount = 0;
+
+ private static final long serialVersionUID = 1L;
+
+ public void execute(ExecutionContext executionContext) throws Exception
+ {
+ executionContext.leaveNode();
+ executionCount++;
+ }
+
+ public static int getExecutionCount()
+ {
+ return executionCount;
+ }
+ }
+}
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/jpdl/par/ProcessArchiveClassLoadingDbTest.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/jpdl/par/ProcessArchiveClassLoadingDbTest.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/jpdl/par/ProcessArchiveClassLoadingDbTest.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -43,7 +43,10 @@
public static Log log = LogFactory.getLog(ProcessArchiveClassLoadingDbTest.class);
String getTestClassesDir() {
- return ProcessArchiveDeploymentDbTest.class.getProtectionDomain().getCodeSource().getLocation().getFile();
+ return ProcessArchiveDeploymentDbTest.class.getProtectionDomain()
+ .getCodeSource()
+ .getLocation()
+ .getFile();
}
public void testExecuteResourceUsingProcess() throws Exception {
@@ -51,8 +54,10 @@
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(baos);
addEntry(zipOutputStream, "processdefinition.xml", "org/jbpm/jpdl/par/resourceprocess.xml");
- addEntry(zipOutputStream, "classes/org/jbpm/jpdl/par/ResourceAction.class", "org/jbpm/jpdl/par/ResourceAction.class");
- addEntry(zipOutputStream, "classes/org/jbpm/jpdl/par/classresource.txt", "org/jbpm/jpdl/par/classresource.txt");
+ addEntry(zipOutputStream, "classes/org/jbpm/jpdl/par/ResourceAction.class",
+ "org/jbpm/jpdl/par/ResourceAction.class");
+ addEntry(zipOutputStream, "classes/org/jbpm/jpdl/par/classresource.txt",
+ "org/jbpm/jpdl/par/classresource.txt");
addEntry(zipOutputStream, "archiveresource.txt", "org/jbpm/jpdl/par/archiveresource.txt");
zipOutputStream.close();
byte[] zipBytes = baos.toByteArray();
@@ -66,7 +71,8 @@
String resourceTmpName = resourceOriginalName + ".hiddenFromTestClasspath";
assertTrue(new File(resourceOriginalName).renameTo(new File(resourceTmpName)));
- String archiveResourceOriginalName = getTestClassesDir() + "org/jbpm/jpdl/par/archiveresource.txt";
+ String archiveResourceOriginalName = getTestClassesDir()
+ + "org/jbpm/jpdl/par/archiveresource.txt";
String archiveResourceTmpName = archiveResourceOriginalName + ".hiddenFromTestClasspath";
assertTrue(new File(archiveResourceOriginalName).renameTo(new File(archiveResourceTmpName)));
@@ -77,7 +83,8 @@
try {
testClassLoader.loadClass("org.jbpm.jpdl.par.ResourceAction");
fail("expected exception");
- } catch (ClassNotFoundException e) {
+ }
+ catch (ClassNotFoundException e) {
// OK
}
@@ -85,15 +92,18 @@
ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(zipBytes));
ProcessDefinition processDefinition = ProcessDefinition.parseParZipInputStream(zipInputStream);
jbpmContext.deployProcessDefinition(processDefinition);
+
+ newTransaction();
try {
- newTransaction();
-
ProcessInstance processInstance = jbpmContext.newProcessInstance("resourceprocess");
processInstance.signal();
- } finally {
+ jbpmContext.save(processInstance);
+ }
+ finally {
jbpmContext.getGraphSession().deleteProcessDefinition(processDefinition.getId());
}
- } finally {
+ }
+ finally {
// put the files back into original position
new File(classTmpName).renameTo(new File(classOriginalName));
new File(resourceTmpName).renameTo(new File(resourceOriginalName));
@@ -106,17 +116,21 @@
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(baos);
addEntry(zipOutputStream, "processdefinition.xml", "org/jbpm/jpdl/par/instantiateprocess.xml");
- addEntry(zipOutputStream, "classes/org/jbpm/jpdl/par/InstantiateAction.class", "org/jbpm/jpdl/par/InstantiateAction.class");
- addEntry(zipOutputStream, "classes/org/jbpm/jpdl/par/InstantiateClass.class", "org/jbpm/jpdl/par/InstantiateClass.class");
+ addEntry(zipOutputStream, "classes/org/jbpm/jpdl/par/InstantiateAction.class",
+ "org/jbpm/jpdl/par/InstantiateAction.class");
+ addEntry(zipOutputStream, "classes/org/jbpm/jpdl/par/InstantiateClass.class",
+ "org/jbpm/jpdl/par/InstantiateClass.class");
zipOutputStream.close();
byte[] zipBytes = baos.toByteArray();
// move the files
- String instantiateActionOriginalName = getTestClassesDir() + "org/jbpm/jpdl/par/InstantiateAction.class";
+ String instantiateActionOriginalName = getTestClassesDir()
+ + "org/jbpm/jpdl/par/InstantiateAction.class";
String instantiateActionTmpName = instantiateActionOriginalName + ".hiddenFromTestClasspath";
assertTrue(new File(instantiateActionOriginalName).renameTo(new File(instantiateActionTmpName)));
- String instantiateClassOriginalName = getTestClassesDir() + "org/jbpm/jpdl/par/InstantiateClass.class";
+ String instantiateClassOriginalName = getTestClassesDir()
+ + "org/jbpm/jpdl/par/InstantiateClass.class";
String instantiateClassTmpName = instantiateClassOriginalName + ".hiddenFromTestClasspath";
assertTrue(new File(instantiateClassOriginalName).renameTo(new File(instantiateClassTmpName)));
@@ -125,13 +139,16 @@
try {
testClassLoader.loadClass("org.jbpm.jpdl.par.InstantiateAction");
fail("expected exception");
- } catch (ClassNotFoundException e) {
+ }
+ catch (ClassNotFoundException e) {
// OK
}
+
try {
testClassLoader.loadClass("org.jbpm.jpdl.par.InstantiateClass");
fail("expected exception");
- } catch (ClassNotFoundException e) {
+ }
+ catch (ClassNotFoundException e) {
// OK
}
@@ -139,16 +156,18 @@
ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(zipBytes));
ProcessDefinition processDefinition = ProcessDefinition.parseParZipInputStream(zipInputStream);
jbpmContext.deployProcessDefinition(processDefinition);
+
+ newTransaction();
try {
- newTransaction();
-
ProcessInstance processInstance = jbpmContext.newProcessInstance("instantiateprocess");
processInstance.signal();
-
- } finally {
+ jbpmContext.save(processInstance);
+ }
+ finally {
jbpmContext.getGraphSession().deleteProcessDefinition(processDefinition.getId());
}
- } finally {
+ }
+ finally {
// put the files back into original position
new File(instantiateActionTmpName).renameTo(new File(instantiateActionOriginalName));
new File(instantiateClassTmpName).renameTo(new File(instantiateClassOriginalName));
@@ -160,12 +179,14 @@
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(baos);
addEntry(zipOutputStream, "processdefinition.xml", "org/jbpm/jpdl/par/instantiateprocess.xml");
- addEntry(zipOutputStream, "classes/org/jbpm/jpdl/par/InstantiateAction.class", "org/jbpm/jpdl/par/InstantiateAction.class");
+ addEntry(zipOutputStream, "classes/org/jbpm/jpdl/par/InstantiateAction.class",
+ "org/jbpm/jpdl/par/InstantiateAction.class");
zipOutputStream.close();
byte[] zipBytes = baos.toByteArray();
// move the files
- String instantiateActionOriginalName = getTestClassesDir() + "org/jbpm/jpdl/par/InstantiateAction.class";
+ String instantiateActionOriginalName = getTestClassesDir()
+ + "org/jbpm/jpdl/par/InstantiateAction.class";
String instantiateActionTmpName = instantiateActionOriginalName + ".hiddenFromTestClasspath";
assertTrue(new File(instantiateActionOriginalName).renameTo(new File(instantiateActionTmpName)));
@@ -174,7 +195,8 @@
try {
testClassLoader.loadClass("org.jbpm.jpdl.par.InstantiateAction");
fail("expected exception");
- } catch (ClassNotFoundException e) {
+ }
+ catch (ClassNotFoundException e) {
// OK
}
// InstantiateClass should be visible on the test classpath
@@ -184,29 +206,33 @@
ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(zipBytes));
ProcessDefinition processDefinition = ProcessDefinition.parseParZipInputStream(zipInputStream);
jbpmContext.deployProcessDefinition(processDefinition);
+
+ newTransaction();
try {
- newTransaction();
-
ProcessInstance processInstance = jbpmContext.newProcessInstance("instantiateprocess");
processInstance.signal();
-
- } finally {
+ jbpmContext.save(processInstance);
+ }
+ finally {
jbpmContext.getGraphSession().deleteProcessDefinition(processDefinition.getId());
}
- } finally {
+ }
+ finally {
// put the files back into original position
new File(instantiateActionTmpName).renameTo(new File(instantiateActionOriginalName));
}
}
- private static void addEntry(ZipOutputStream zipOutputStream, String entryName, String resource) throws IOException {
+ private static void addEntry(ZipOutputStream zipOutputStream, String entryName, String resource)
+ throws IOException {
InputStream inputStream = ClassLoaderUtil.getStream(resource);
byte[] bytes = IoUtil.readBytes(inputStream);
addEntry(zipOutputStream, entryName, bytes);
inputStream.close();
}
- private static void addEntry(ZipOutputStream zipOutputStream, String entryName, byte[] content) throws IOException {
+ private static void addEntry(ZipOutputStream zipOutputStream, String entryName, byte[] content)
+ throws IOException {
ZipEntry zipEntry = new ZipEntry(entryName);
zipOutputStream.putNextEntry(zipEntry);
zipOutputStream.write(content);
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/taskmgmt/exe/TaskTimerExecutionDbTest.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/taskmgmt/exe/TaskTimerExecutionDbTest.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/taskmgmt/exe/TaskTimerExecutionDbTest.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -35,83 +35,78 @@
public class TaskTimerExecutionDbTest extends AbstractDbTestCase {
static int counter = 0;
-
+
public static class PlusPlus implements ActionHandler {
private static final long serialVersionUID = 1L;
+
public void execute(ExecutionContext executionContext) throws Exception {
counter++;
}
}
-
+
protected void setUp() throws Exception {
super.setUp();
counter = 0;
}
public void testTimerCreation() {
- ProcessDefinition processDefinition = ProcessDefinition.parseXmlString(
- "<process-definition>" +
- " <start-state>" +
- " <transition to='a' />" +
- " </start-state>" +
- " <task-node name='a'>" +
- " <task name='clean ceiling'>" +
- " <timer name='ceiling-timer' duedate='0 seconds'>" +
- " <action class='org.jbpm.taskmgmt.exe.TaskTimerExecutionDbTest$PlusPlus' />" +
- " </timer>" +
- " </task>" +
- " </task-node>" +
- "</process-definition>"
- );
+ ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
+ + " <start-state>"
+ + " <transition to='a' />"
+ + " </start-state>"
+ + " <task-node name='a'>"
+ + " <task name='clean ceiling'>"
+ + " <timer name='ceiling-timer' duedate='0 seconds'>"
+ + " <action class='org.jbpm.taskmgmt.exe.TaskTimerExecutionDbTest$PlusPlus' />"
+ + " </timer>"
+ + " </task>"
+ + " </task-node>"
+ + "</process-definition>");
processDefinition = saveAndReload(processDefinition);
- try
- {
+ try {
ProcessInstance processInstance = new ProcessInstance(processDefinition);
processInstance.signal();
-
+
processInstance = saveAndReload(processInstance);
- Timer timer = (Timer) getJob();
+ Timer timer = getTimer();
assertEquals("ceiling-timer", timer.getName());
}
- finally
- {
+ finally {
jbpmContext.getGraphSession().deleteProcessDefinition(processDefinition.getId());
}
}
public void testTimerDeletion() {
- ProcessDefinition processDefinition = ProcessDefinition.parseXmlString(
- "<process-definition>" +
- " <start-state>" +
- " <transition to='a' />" +
- " </start-state>" +
- " <task-node name='a'>" +
- " <task name='clean ceiling'>" +
- " <timer name='ceiling-timer' duedate='0 seconds'>" +
- " <action class='org.jbpm.taskmgmt.exe.TaskTimerExecutionDbTest$PlusPlus' />" +
- " </timer>" +
- " </task>" +
- " <transition to='b' />" +
- " </task-node>" +
- " <state name='b' />" +
- "</process-definition>"
- );
+ ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
+ + " <start-state>"
+ + " <transition to='a' />"
+ + " </start-state>"
+ + " <task-node name='a'>"
+ + " <task name='clean ceiling'>"
+ + " <timer name='ceiling-timer' duedate='0 seconds'>"
+ + " <action class='org.jbpm.taskmgmt.exe.TaskTimerExecutionDbTest$PlusPlus' />"
+ + " </timer>"
+ + " </task>"
+ + " <transition to='b' />"
+ + " </task-node>"
+ + " <state name='b' />"
+ + "</process-definition>");
processDefinition = saveAndReload(processDefinition);
- try
- {
+ try {
ProcessInstance processInstance = new ProcessInstance(processDefinition);
processInstance.signal();
jbpmContext.save(processInstance);
newTransaction();
- List taskInstances = taskMgmtSession.findTaskInstancesByToken(processInstance.getRootToken().getId());
+ List<TaskInstance> taskInstances = taskMgmtSession.findTaskInstancesByToken(processInstance.getRootToken()
+ .getId());
assertEquals(1, taskInstances.size());
- TaskInstance taskInstance = (TaskInstance) taskInstances.get(0);
+ TaskInstance taskInstance = taskInstances.get(0);
taskInstance.end();
jbpmContext.save(taskInstance);
@@ -119,98 +114,86 @@
assertEquals(0, getTimerCount());
}
- finally
- {
+ finally {
jbpmContext.getGraphSession().deleteProcessDefinition(processDefinition.getId());
}
}
public void testTimerExecution() {
- ProcessDefinition processDefinition = ProcessDefinition.parseXmlString(
- "<process-definition>" +
- " <start-state>" +
- " <transition to='a' />" +
- " </start-state>" +
- " <task-node name='a'>" +
- " <task name='clean ceiling'>" +
- " <timer name='ceiling-timer' duedate='0 seconds'>" +
- " <action class='org.jbpm.taskmgmt.exe.TaskTimerExecutionDbTest$PlusPlus' />" +
- " </timer>" +
- " </task>" +
- " </task-node>" +
- "</process-definition>"
- );
+ ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
+ + " <start-state>"
+ + " <transition to='a' />"
+ + " </start-state>"
+ + " <task-node name='a'>"
+ + " <task name='clean ceiling'>"
+ + " <timer name='ceiling-timer' duedate='0 seconds'>"
+ + " <action class='org.jbpm.taskmgmt.exe.TaskTimerExecutionDbTest$PlusPlus' />"
+ + " </timer>"
+ + " </task>"
+ + " </task-node>"
+ + "</process-definition>");
processDefinition = saveAndReload(processDefinition);
- try
- {
+ try {
ProcessInstance processInstance = new ProcessInstance(processDefinition);
processInstance.signal();
jbpmContext.save(processInstance);
-
+
processJobs(5000);
assertEquals(1, counter);
}
- finally
- {
+ finally {
jbpmContext.getGraphSession().deleteProcessDefinition(processDefinition.getId());
}
-
+
}
public void testTaskNodeTimerExecution() {
- ProcessDefinition processDefinition = ProcessDefinition.parseXmlString(
- "<process-definition>" +
- " <start-state>" +
- " <transition to='a' />" +
- " </start-state>" +
- " <task-node name='a'>" +
- " <timer name='ceiling-timer' duedate='0 seconds'>" +
- " <action class='org.jbpm.taskmgmt.exe.TaskTimerExecutionDbTest$PlusPlus' />" +
- " </timer>" +
- " <task name='clean ceiling' />" +
- " </task-node>" +
- "</process-definition>"
- );
+ ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
+ + " <start-state>"
+ + " <transition to='a' />"
+ + " </start-state>"
+ + " <task-node name='a'>"
+ + " <timer name='ceiling-timer' duedate='0 seconds'>"
+ + " <action class='org.jbpm.taskmgmt.exe.TaskTimerExecutionDbTest$PlusPlus' />"
+ + " </timer>"
+ + " <task name='clean ceiling' />"
+ + " </task-node>"
+ + "</process-definition>");
processDefinition = saveAndReload(processDefinition);
- try
- {
+ try {
ProcessInstance processInstance = new ProcessInstance(processDefinition);
processInstance.signal();
jbpmContext.save(processInstance);
-
+
newTransaction();
processJobs(5000);
assertEquals(1, counter);
}
- finally
- {
+ finally {
jbpmContext.getGraphSession().deleteProcessDefinition(processDefinition.getId());
}
}
public void testTimerExecutionRepeat() throws Exception {
- ProcessDefinition processDefinition = ProcessDefinition.parseXmlString(
- "<process-definition>" +
- " <start-state>" +
- " <transition to='a' />" +
- " </start-state>" +
- " <task-node name='a'>" +
- " <task name='clean ceiling'>" +
- " <timer name='ceiling-timer' duedate='0 seconds' repeat='60 second'>" +
- " <action class='org.jbpm.taskmgmt.exe.TaskTimerExecutionDbTest$PlusPlus' />" +
- " </timer>" +
- " </task>" +
- " </task-node>" +
- "</process-definition>"
- );
+ ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
+ + " <start-state>"
+ + " <transition to='a' />"
+ + " </start-state>"
+ + " <task-node name='a'>"
+ + " <task name='clean ceiling'>"
+ + " <timer name='ceiling-timer' duedate='0 seconds' repeat='60 second'>"
+ + " <action class='org.jbpm.taskmgmt.exe.TaskTimerExecutionDbTest$PlusPlus' />"
+ + " </timer>"
+ + " </task>"
+ + " </task-node>"
+ + "</process-definition>");
processDefinition = saveAndReload(processDefinition);
- try
- {
+ try {
ProcessInstance processInstance = new ProcessInstance(processDefinition);
processInstance.signal();
jbpmContext.save(processInstance);
@@ -218,7 +201,7 @@
newTransaction();
// fetch the original duedate
- Timer timer = (Timer) getJob();
+ Timer timer = getTimer();
assertNotNull(timer);
long originalDueDate = timer.getDueDate().getTime();
@@ -226,37 +209,33 @@
assertEquals(1, counter);
// check if the timer has be re-scheduled because of the repeat.
- timer = (Timer) getJob();
+ timer = getTimer();
assertNotNull(timer);
// check that the timer was rescheduled with a duedate 60 seconds after the original duedate.
- assertEquals(originalDueDate+60000, timer.getDueDate().getTime());
+ assertEquals(originalDueDate + 60000, timer.getDueDate().getTime());
}
- finally
- {
+ finally {
newTransaction();
jbpmContext.getGraphSession().deleteProcessDefinition(processDefinition.getId());
}
}
-
+
public void testTimerELCreation() {
- ProcessDefinition processDefinition = ProcessDefinition.parseXmlString(
- "<process-definition>" +
- " <start-state>" +
- " <transition to='a' />" +
- " </start-state>" +
- " <task-node name='a'>" +
- " <task name='clean ceiling'>" +
- " <timer name='ceiling-timer' duedate='#{baseDate} + 2 days'>" +
- " <action class='org.jbpm.taskmgmt.exe.TaskTimerExecutionDbTest$PlusPlus' />" +
- " </timer>" +
- " </task>" +
- " </task-node>" +
- "</process-definition>"
- );
+ ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition>"
+ + " <start-state>"
+ + " <transition to='a' />"
+ + " </start-state>"
+ + " <task-node name='a'>"
+ + " <task name='clean ceiling'>"
+ + " <timer name='ceiling-timer' duedate='#{baseDate} + 2 days'>"
+ + " <action class='org.jbpm.taskmgmt.exe.TaskTimerExecutionDbTest$PlusPlus' />"
+ + " </timer>"
+ + " </task>"
+ + " </task-node>"
+ + "</process-definition>");
processDefinition = saveAndReload(processDefinition);
- try
- {
+ try {
Calendar baseDate = Calendar.getInstance();
Date dateTestDate = new Date();
baseDate.setTime(dateTestDate);
@@ -273,15 +252,18 @@
baseDateTest.clear(Calendar.MILLISECOND);
baseDateTest.add(Calendar.DAY_OF_YEAR, 2);
- Timer timer = (Timer) getJob();
+ Timer timer = getTimer();
assertEquals("ceiling-timer", timer.getName());
-
+
assertNotNull(timer.getDueDate());
- assertEquals(baseDateTest.getTime(), timer.getDueDate());
+ assertEquals(baseDateTest.getTime(), timer.getDueDate());
}
- finally
- {
+ finally {
jbpmContext.getGraphSession().deleteProcessDefinition(processDefinition.getId());
}
- }
+ }
+
+ private Timer getTimer() {
+ return (Timer) session.createCriteria(Timer.class).setMaxResults(1).uniqueResult();
+ }
}
Modified: jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/taskmgmt/exe/TaskVariablesDbTest.java
===================================================================
--- jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/taskmgmt/exe/TaskVariablesDbTest.java 2009-02-21 14:04:36 UTC (rev 3993)
+++ jbpm3/branches/jbpm-3.2.5.SP/modules/core/src/test/java/org/jbpm/taskmgmt/exe/TaskVariablesDbTest.java 2009-02-22 03:15:07 UTC (rev 3994)
@@ -22,25 +22,30 @@
package org.jbpm.taskmgmt.exe;
import java.util.HashMap;
+import java.util.Map;
import org.jbpm.context.exe.ContextInstance;
import org.jbpm.db.AbstractDbTestCase;
import org.jbpm.graph.def.ProcessDefinition;
import org.jbpm.graph.exe.ProcessInstance;
-public class TaskVariablesDbTest extends AbstractDbTestCase {
-
- public void testDefaultVariablePersistence() {
+public class TaskVariablesDbTest extends AbstractDbTestCase
+{
+ public void testDefaultVariablePersistence()
+ {
ProcessDefinition processDefinition = ProcessDefinition.createNewProcessDefinition();
- processDefinition = saveAndReload(processDefinition);
+ processDefinition.setName("default variable persistence");
+ jbpmContext.deployProcessDefinition(processDefinition);
+
+ newTransaction();
try
{
ProcessInstance processInstance = new ProcessInstance(processDefinition);
- TaskInstance taskInstance = processInstance.getTaskMgmtInstance().createTaskInstance(processInstance.getRootToken());
+ TaskInstance taskInstance = processInstance.getTaskMgmtInstance().createTaskInstance(
+ processInstance.getRootToken());
taskInstance.setVariable("key", "value");
taskInstance = saveAndReload(taskInstance);
-
assertNotNull(taskInstance);
assertEquals("value", taskInstance.getVariable("key"));
}
@@ -49,46 +54,44 @@
jbpmContext.getGraphSession().deleteProcessDefinition(processDefinition.getId());
}
}
-
- public void testSetOnTaskInstanceGetOnProcess() {
-
- ProcessDefinition processDefinition = ProcessDefinition.parseXmlString(
- "<process-definition>" +
- " <start-state>" +
- " <transition to='t' />" +
- " </start-state>" +
- " <task-node name='t'>" +
- " <task name='vartask' />" +
- " </task-node>" +
- "</process-definition>"
- );
- processDefinition = saveAndReload(processDefinition);
+
+ public void testSetOnTaskInstanceGetOnProcess()
+ {
+ ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition name='set on task get on process'>"
+ + " <start-state>"
+ + " <transition to='t' />"
+ + " </start-state>"
+ + " <task-node name='t'>"
+ + " <task name='vartask' />"
+ + " </task-node>"
+ + "</process-definition>");
+ jbpmContext.deployProcessDefinition(processDefinition);
+
+ newTransaction();
try
{
ProcessInstance processInstance = new ProcessInstance(processDefinition);
processInstance.signal();
-
+
processInstance = saveAndReload(processInstance);
ContextInstance contextInstance = processInstance.getContextInstance();
- TaskMgmtInstance taskMgmtInstance = processInstance.getTaskMgmtInstance();
- TaskInstance taskInstance = (TaskInstance) taskMgmtInstance.getTaskInstances().iterator().next();
-
- HashMap expectedVariables = new HashMap();
+ TaskInstance taskInstance = processInstance.getTaskMgmtInstance()
+ .getTaskInstances()
+ .iterator()
+ .next();
+
+ Map<String, Object> expectedVariables = new HashMap<String, Object>();
assertEquals(expectedVariables, taskInstance.getVariables());
+
assertFalse(taskInstance.hasVariable("a"));
assertNull(taskInstance.getVariable("a"));
-
assertNull(contextInstance.getVariable("a"));
-
+
taskInstance.setVariable("a", "1");
- jbpmContext.save(taskInstance);
- newTransaction();
-
- processInstance = jbpmContext.loadProcessInstance(processInstance.getId());
- contextInstance = processInstance.getContextInstance();
- taskMgmtInstance = processInstance.getTaskMgmtInstance();
- taskInstance = (TaskInstance) taskMgmtInstance.getTaskInstances().iterator().next();
-
+
+ taskInstance = saveAndReload(taskInstance);
+ contextInstance = taskInstance.getContextInstance();
+
expectedVariables.put("a", "1");
assertEquals(expectedVariables, taskInstance.getVariables());
@@ -100,58 +103,41 @@
{
jbpmContext.getGraphSession().deleteProcessDefinition(processDefinition.getId());
}
-
}
- public void testSetOnProcessGetOnTaskInstance() {
- ProcessDefinition processDefinition = ProcessDefinition.parseXmlString(
- "<process-definition>" +
- " <start-state>" +
- " <transition to='t' />" +
- " </start-state>" +
- " <task-node name='t'>" +
- " <task name='vartask' />" +
- " </task-node>" +
- "</process-definition>"
- );
- processDefinition = saveAndReload(processDefinition);
+ public void testSetOnProcessGetOnTaskInstance()
+ {
+ ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition name='set on process get on task'>"
+ + " <start-state>"
+ + " <transition to='t' />"
+ + " </start-state>"
+ + " <task-node name='t'>"
+ + " <task name='vartask' />"
+ + " </task-node>"
+ + "</process-definition>");
+ jbpmContext.deployProcessDefinition(processDefinition);
+
+ newTransaction();
try
{
ProcessInstance processInstance = new ProcessInstance(processDefinition);
- ContextInstance contextInstance = processInstance.getContextInstance();
- TaskMgmtInstance taskMgmtInstance = processInstance.getTaskMgmtInstance();
processInstance.signal();
- TaskInstance taskInstance = (TaskInstance) taskMgmtInstance.getTaskInstances().iterator().next();
- HashMap expectedVariables = new HashMap();
- jbpmContext.save(processInstance);
-
- newTransaction();
-
- processInstance = jbpmContext.loadProcessInstance(processInstance.getId());
- long taskInstanceId = taskInstance.getId();
- taskInstance = jbpmContext.loadTaskInstance(taskInstanceId);
- contextInstance = processInstance.getContextInstance();
- taskMgmtInstance = processInstance.getTaskMgmtInstance();
-
+
+ processInstance = saveAndReload(processInstance);
+ ContextInstance contextInstance = processInstance.getContextInstance();
contextInstance.setVariable("a", "1");
- jbpmContext.save(processInstance);
-
- newTransaction();
-
- processInstance = jbpmContext.loadProcessInstance(processInstance.getId());
- taskInstance = jbpmContext.loadTaskInstance(taskInstanceId);
- contextInstance = processInstance.getContextInstance();
- taskMgmtInstance = processInstance.getTaskMgmtInstance();
-
+ TaskInstance taskInstance = processInstance.getTaskMgmtInstance()
+ .getTaskInstances()
+ .iterator()
+ .next();
+
+ taskInstance = saveAndReload(taskInstance);
+ Map<String, Object> expectedVariables = new HashMap<String, Object>();
expectedVariables.put("a", "1");
assertEquals(expectedVariables, taskInstance.getVariables());
- newTransaction();
-
- processInstance = jbpmContext.loadProcessInstance(processInstance.getId());
- taskInstance = jbpmContext.loadTaskInstance(taskInstanceId);
- contextInstance = processInstance.getContextInstance();
- taskMgmtInstance = processInstance.getTaskMgmtInstance();
+ taskInstance = saveAndReload(taskInstance);
+ contextInstance = taskInstance.getContextInstance();
assertTrue(taskInstance.hasVariable("a"));
assertEquals("1", taskInstance.getVariable("a"));
@@ -161,54 +147,43 @@
{
jbpmContext.getGraphSession().deleteProcessDefinition(processDefinition.getId());
}
-
}
- public void testSetLocally() {
- ProcessDefinition processDefinition = ProcessDefinition.parseXmlString(
- "<process-definition>" +
- " <start-state>" +
- " <transition to='t' />" +
- " </start-state>" +
- " <task-node name='t'>" +
- " <task name='vartask' />" +
- " </task-node>" +
- "</process-definition>"
- );
- processDefinition = saveAndReload(processDefinition);
+ public void testSetLocally()
+ {
+ ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition name='set locally'>"
+ + " <start-state>"
+ + " <transition to='t' />"
+ + " </start-state>"
+ + " <task-node name='t'>"
+ + " <task name='vartask' />"
+ + " </task-node>"
+ + "</process-definition>");
+ jbpmContext.deployProcessDefinition(processDefinition);
+
+ newTransaction();
try
{
ProcessInstance processInstance = new ProcessInstance(processDefinition);
- ContextInstance contextInstance = processInstance.getContextInstance();
- TaskMgmtInstance taskMgmtInstance = processInstance.getTaskMgmtInstance();
processInstance.signal();
- TaskInstance taskInstance = (TaskInstance) taskMgmtInstance.getTaskInstances().iterator().next();
+ TaskInstance taskInstance = processInstance.getTaskMgmtInstance()
+ .getTaskInstances()
+ .iterator()
+ .next();
- jbpmContext.save(processInstance);
-
- newTransaction();
-
- processInstance = jbpmContext.loadProcessInstance(processInstance.getId());
- taskInstance = jbpmContext.loadTaskInstance(taskInstance.getId());
- contextInstance = processInstance.getContextInstance();
- taskMgmtInstance = processInstance.getTaskMgmtInstance();
+ taskInstance = saveAndReload(taskInstance);
+ ContextInstance contextInstance = taskInstance.getContextInstance();
- HashMap expectedVariables = new HashMap();
+ Map<String, Object> expectedVariables = new HashMap<String, Object>();
assertEquals(expectedVariables, taskInstance.getVariables());
assertFalse(taskInstance.hasVariable("a"));
assertNull(taskInstance.getVariable("a"));
assertNull(contextInstance.getVariable("a"));
-
+
taskInstance.setVariableLocally("a", "1");
-
- jbpmContext.save(taskInstance);
- newTransaction();
-
- processInstance = jbpmContext.loadProcessInstance(processInstance.getId());
- taskInstance = jbpmContext.loadTaskInstance(taskInstance.getId());
- contextInstance = processInstance.getContextInstance();
- taskMgmtInstance = processInstance.getTaskMgmtInstance();
+ taskInstance = saveAndReload(taskInstance);
+ contextInstance = taskInstance.getContextInstance();
expectedVariables.put("a", "1");
assertEquals(expectedVariables, taskInstance.getVariables());
@@ -222,79 +197,63 @@
jbpmContext.getGraphSession().deleteProcessDefinition(processDefinition.getId());
}
}
-
- public void testCopyWithController() {
- ProcessDefinition processDefinition = ProcessDefinition.parseXmlString(
- "<process-definition>" +
- " <start-state>" +
- " <transition to='t' />" +
- " </start-state>" +
- " <task-node name='t'>" +
- " <task name='vartask'>" +
- " <controller>" +
- " <variable name='a' />" +
- " <variable name='b' />" +
- " </controller>" +
- " </task>" +
- " </task-node>" +
- "</process-definition>"
- );
- processDefinition = saveAndReload(processDefinition);
+
+ public void testCopyWithController()
+ {
+ ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition name='copy with controller'>"
+ + " <start-state>"
+ + " <transition to='t' />"
+ + " </start-state>"
+ + " <task-node name='t'>"
+ + " <task name='vartask'>"
+ + " <controller>"
+ + " <variable name='a' />"
+ + " <variable name='b' />"
+ + " </controller>"
+ + " </task>"
+ + " </task-node>"
+ + "</process-definition>");
+ jbpmContext.deployProcessDefinition(processDefinition);
+
+ newTransaction();
try
{
ProcessInstance processInstance = new ProcessInstance(processDefinition);
ContextInstance contextInstance = processInstance.getContextInstance();
- TaskMgmtInstance taskMgmtInstance = processInstance.getTaskMgmtInstance();
-
contextInstance.setVariable("a", "1");
contextInstance.setVariable("b", "2");
contextInstance.setVariable("c", "3");
-
+
processInstance.signal();
- TaskInstance taskInstance = (TaskInstance) taskMgmtInstance.getTaskInstances().iterator().next();
+ TaskInstance taskInstance = processInstance.getTaskMgmtInstance()
+ .getTaskInstances()
+ .iterator()
+ .next();
- jbpmContext.save(processInstance);
-
- newTransaction();
-
- processInstance = jbpmContext.loadProcessInstance(processInstance.getId());
- taskInstance = jbpmContext.loadTaskInstance(taskInstance.getId());
- contextInstance = processInstance.getContextInstance();
- taskMgmtInstance = processInstance.getTaskMgmtInstance();
+ taskInstance = saveAndReload(taskInstance);
- HashMap expectedVariables = new HashMap();
+ Map<String, Object> expectedVariables = new HashMap<String, Object>();
expectedVariables.put("a", "1");
expectedVariables.put("b", "2");
expectedVariables.put("c", "3");
assertEquals(expectedVariables, taskInstance.getVariables());
-
+
taskInstance.setVariable("a", "1 modified");
taskInstance.setVariable("b", "2 modified");
taskInstance.setVariable("c", "3 modified");
-
- jbpmContext.save(processInstance);
- newTransaction();
-
- processInstance = jbpmContext.loadProcessInstance(processInstance.getId());
- taskInstance = jbpmContext.loadTaskInstance(taskInstance.getId());
- contextInstance = processInstance.getContextInstance();
- taskMgmtInstance = processInstance.getTaskMgmtInstance();
+ taskInstance = saveAndReload(taskInstance);
- expectedVariables = new HashMap();
+ expectedVariables.clear();
expectedVariables.put("a", "1 modified");
expectedVariables.put("b", "2 modified");
expectedVariables.put("c", "3 modified");
assertEquals(expectedVariables, taskInstance.getVariables());
- newTransaction();
-
- processInstance = jbpmContext.loadProcessInstance(processInstance.getId());
- taskInstance = jbpmContext.loadTaskInstance(taskInstance.getId());
- contextInstance = processInstance.getContextInstance();
- taskMgmtInstance = processInstance.getTaskMgmtInstance();
+ taskInstance = saveAndReload(taskInstance);
+ contextInstance = taskInstance.getContextInstance();
- expectedVariables = new HashMap();
+ expectedVariables.clear();
expectedVariables.put("a", "1"); // task instance had local copy for var a
expectedVariables.put("b", "2"); // task instance had local copy for var b
expectedVariables.put("c", "3 modified");
@@ -306,94 +265,90 @@
}
}
- public void testOverwriteNullValue() {
- ProcessDefinition processDefinition = ProcessDefinition.parseXmlString(
- "<process-definition>" +
- " <start-state>" +
- " <transition to='t' />" +
- " </start-state>" +
- " <task-node name='t'>" +
- " <task name='vartask'>" +
- " <controller>" +
- " <variable name='v' />" +
- " </controller>" +
- " </task>" +
- " </task-node>" +
- "</process-definition>"
- );
- processDefinition = saveAndReload(processDefinition);
+ public void testOverwriteNullValue()
+ {
+ ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition name='overwrite-null-value'>"
+ + " <start-state>"
+ + " <transition to='t' />"
+ + " </start-state>"
+ + " <task-node name='t'>"
+ + " <task name='vartask'>"
+ + " <controller>"
+ + " <variable name='v' />"
+ + " </controller>"
+ + " </task>"
+ + " </task-node>"
+ + "</process-definition>");
+ jbpmContext.deployProcessDefinition(processDefinition);
+
+ newTransaction();
try
{
ProcessInstance processInstance = new ProcessInstance(processDefinition);
processInstance.signal();
-
+
processInstance = saveAndReload(processInstance);
- TaskMgmtInstance taskMgmtInstance = processInstance.getTaskMgmtInstance();
- TaskInstance taskInstance = (TaskInstance) taskMgmtInstance.getTaskInstances().iterator().next();
-
+ TaskInstance taskInstance = processInstance.getTaskMgmtInstance()
+ .getTaskInstances()
+ .iterator()
+ .next();
+
assertNull(taskInstance.getVariable("v"));
taskInstance.setVariable("v", "facelets is great");
- jbpmContext.save(taskInstance);
-
- newTransaction();
-
- taskInstance = jbpmContext.loadTaskInstance(taskInstance.getId());
+
+ taskInstance = saveAndReload(taskInstance);
assertEquals("facelets is great", taskInstance.getVariable("v"));
}
finally
{
jbpmContext.getGraphSession().deleteProcessDefinition(processDefinition.getId());
}
-
}
- public void testNewTaskInstanceVariablesWithoutController() {
- ProcessDefinition processDefinition = ProcessDefinition.parseXmlString(
- "<process-definition>" +
- " <start-state>" +
- " <transition to='t' />" +
- " </start-state>" +
- " <task-node name='t'>" +
- " <task name='vartask'>" +
- " </task>" +
- " <transition to='u' />" +
- " </task-node>" +
- " <state name='u' />" +
- "</process-definition>"
- );
- processDefinition = saveAndReload(processDefinition);
+ public void testNewTaskInstanceVariablesWithoutController()
+ {
+ ProcessDefinition processDefinition = ProcessDefinition.parseXmlString("<process-definition name='task variables without controller'>"
+ + " <start-state>"
+ + " <transition to='t' />"
+ + " </start-state>"
+ + " <task-node name='t'>"
+ + " <task name='vartask' />"
+ + " <transition to='u' />"
+ + " </task-node>"
+ + " <state name='u' />"
+ + "</process-definition>");
+ jbpmContext.deployProcessDefinition(processDefinition);
+
+ newTransaction();
try
{
ProcessInstance processInstance = new ProcessInstance(processDefinition);
- TaskMgmtInstance taskMgmtInstance = processInstance.getTaskMgmtInstance();
processInstance.signal();
- TaskInstance taskInstance = (TaskInstance) taskMgmtInstance.getTaskInstances().iterator().next();
-
+ TaskInstance taskInstance = processInstance.getTaskMgmtInstance()
+ .getTaskInstances()
+ .iterator()
+ .next();
taskInstance.setVariableLocally("a", "value-a");
taskInstance.setVariableLocally("b", "value-b");
-
- jbpmContext.save(processInstance);
-
- processInstance = saveAndReload(processInstance);
- ContextInstance contextInstance = processInstance.getContextInstance();
- taskMgmtInstance = processInstance.getTaskMgmtInstance();
- taskInstance = (TaskInstance) taskMgmtInstance.getTaskInstances().iterator().next();
-
- assertFalse( contextInstance.hasVariable("a") );
- assertFalse( contextInstance.hasVariable("b") );
-
+
+ taskInstance = saveAndReload(taskInstance);
+ ContextInstance contextInstance = taskInstance.getContextInstance();
+
+ assertFalse(contextInstance.hasVariable("a"));
+ assertFalse(contextInstance.hasVariable("b"));
+
assertEquals("value-a", taskInstance.getVariable("a"));
assertEquals("value-b", taskInstance.getVariable("b"));
-
+
taskInstance.end();
-
+
assertEquals("value-a", contextInstance.getVariable("a"));
assertEquals("value-b", contextInstance.getVariable("b"));
-
- processInstance = saveAndReload(processInstance);
- contextInstance = processInstance.getContextInstance();
-
+
+ taskInstance = saveAndReload(taskInstance);
+ contextInstance = taskInstance.getContextInstance();
+
assertEquals("value-a", contextInstance.getVariable("a"));
assertEquals("value-b", contextInstance.getVariable("b"));
}
@@ -401,6 +356,5 @@
{
jbpmContext.getGraphSession().deleteProcessDefinition(processDefinition.getId());
}
-
}
}
More information about the jbpm-commits
mailing list